Bad Request with errormessage: invalid_client - javascript

I want to create my own user system and make them login with a token.
I have used this tutorial as a starting point: http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
I have created a angular app.
Every time I try to login, I get a 400 error:
Bad Request with errormessage: invalid_client.
How can I fix this error?
I've created my endpoint class like this:
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
try
{
BCContext db = new BCContext();
UserHelper uh = new UserHelper();
// Retrieve user
var user = await uh.CheckLogin(context.UserName, context.Password);
if (user != null)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user.Firstname + " " + user.Lastname));
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
context.Validated(identity);
}
}
catch (Exception ex)
{
context.SetError("invalid_grant", ex.Message);
}
}
}
My authService.js:
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var serviceUrl = "http://localhost:55520/";
var authServiceFactory = {};
var authentication = {
isAuth: false,
username: ""
};
var register = function (data) {
console.log(data);
return $http.post(serviceUrl + 'api/users', data).then(function (response) {
return response;
});
};
var login = function (loginData) {
var data = "grant_type=password&username=" + loginData.username + "&password=" + loginData.password;
var deferred = $q.defer();
$http.defaults.headers.post["Content-Type"] = "text/plain";
$http.post(serviceUrl + 'api/security/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, username : loginData.username });
authentication.isAuth = true;
authentication.username = loginData.username;
$q.defer().resolve(response);
}).error(function (err, status) {
//alert(err);
console.log(err);
$q.defer().reject(err);
});
return $q.defer().promise;
};
var fillAuthData = function() {
var authData = localStorageService.get('authorizationData');
if(authData) {
authentication.isAuth = true;
authentication.username = authData.username;
}
}
authServiceFactory.login = login;
authServiceFactory.register = register;
authServiceFactory.fillAuthData = fillAuthData
authServiceFactory.authentication = authentication;
return authServiceFactory;
}]);
My loginController.js:
app.controller('loginController', ['$scope', '$location', 'authService', function ($scope, $location, authService) {
$scope.loginData = {
username: "",
password: ""
};
$scope.message = "";
$scope.login = function () {
authService.login($scope.loginData).then(function (response) {
$location.path('/users');
}),
function (err) {
$scope.message = err.error_description;
console.log(err);
}
};
}]);
My authInterceptor.js:
app.factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
var authInterceptorServiceFactory = {};
var request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
}
var responseError = function (rejection) {
if (rejection.status === 401) {
$location.path('/login');
}
return $q.reject(rejection);
}
authInterceptorServiceFactory.request = request;
authInterceptorServiceFactory.responseError = responseError;
return authInterceptorServiceFactory;
}]);
My login.html:
<form class="form-login" role="form">
<h2>Login</h2>
<input type="text" class="form-control" placeholder="Username" ng-model="loginData.username" required autofocus />
<input type="password" class="form-control" placeholder="Password" ng-model="loginData.password" required />
<button class="btn btn-primary" type="submit" ng-click="login()">Login</button>
<div ng-hide="message == ''" class="alert alert-danger">
{{message}}
</div>
</form>
This is what I send:

Related

Unable to store cookies and allow session

I'm trying to create a simple ticketing app.
Once the user logins it should show a dashboard with project name and 3 categories of tickets count and a add ticket button to add a new ticket
Problem I'm able to authenticate the user on login screen but when it navigates to the next screen that is dashboard the user get unauthenticated hence not able to fetch api and display the data being sent
index.js
var app = angular.module("loginTest", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
// login view definition
.when("/login", {
controller: "loginController",
controllerAs: "vm",
templateUrl: "login.html"
})
.when("/main", {
controller: "mainController",
controllerAs: "vm",
templateUrl: "main.html",
authenticated:true
})
.when("/setting", {
controller: "settingController",
controllerAs: "vm",
templateUrl: "project.html",
authenticated:true
})
.when("/about", {
controller: "aboutController",
controllerAs: "vm",
templateUrl: "about.html",
authenticated:true
})
.when("/addTicket",{
controller:"addTicketCtrl",
controllerAs:"vm",
templateUrl:"addTicket.hmtl",
authenticated:true
})
.otherwise({
redirectTo: "/main",
authenticated:true
});
});
app.run(function ($rootScope, $location) {
$rootScope.$on("$routeChangeStart", function (event, next) {
// check current login status and filter out if navigating to login
if (!$rootScope.loggedIn && next.originalPath !== "/login") {
// remember the original url
$location.url("/login?back=" + $location.url());
}
});
});
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.service("loginService",$cookies, function ($http, $cookies) {
console.log("service");
$cookies.get(email),
$cookies.get(password)
return {
checkLogin: function () {
return $http.post("/login").then(function (response) {
console.log(response.data);
return response.data;
});
},
login: function (email, pass, $cookies) {
console.log("loginn fucntion");
return $http.post("https://qa.workdaysync.io/getcadentapi/auth/login", {
email: email,
password : pass,
}).then(function (response) {
//console.log("1st response"+response.status);
return response.data;
}, function (response) {
var err = new Error(response.statusText);
//console.log("2st response" +response.errorCode);
err.code = response.status;
if (response.status == 401) {
var error = "USERNAME OR PASSWORD IS INCORRECT"
var loginfailed = true;
//alert(error);
//console.log(loginfailed);
}
throw err;
});
}
};
})
/* app.service("addTicketService",function($rootScope,$http){
var vm=this;
addTicket: function (description){
return $http.post("https://qa.workdaysync.io/getcadentapi/tickets", {
description: description,
id: name
}).then(function (response) {
//console.log("1st response"+response.status);
return response.data;
console.log(response.data);
}
})
}); */
app.controller("loginController",$cookies, function ($rootScope, $location, loginService,$cookies) {
var vm = this;
function success() {
$rootScope.loggedIn = true;
$rootScope.loginError = false;
$cookies.put('username', email);
$cookies.put('password', password);
var back = $location.search().back || "";
$location.url(back !== "/login" ? back : "");/*
$cookies.put('username', email);
$cookies.put('password', password); */
}
function failure() {
$rootScope.loggedIn = false;
$rootScope.loginError = true;
}
loginService.checkLogin().then(success);
vm.login = function () {
loginService.login(vm.user, vm.pass).then(success, failure);
};
vm.logout = function () {
loginService.logut(
localStorage.clear(),
sessionStorage.clear()
);
}
})
app.service('HttpService', function ($http) {
return {
getPost: function () {
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync')
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Post', response);
return response.data;
});
},
getUsers: function () {
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync')
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Users', response);
return response.data;
});
}
}
});
app.controller('mainController', function ($scope, HttpService) {
HttpService.getPost()
.then(function (response) {
$scope.post = response;
});
HttpService.getUsers()
.then(function (response) {
$scope.users = response;
console.log("asdfdsfsdf");
console.log("umm"+ $scope.users.inProgressCount);
console.log("asdfdsfsdf++++sdsad");
var myNumber = $scope.users.inProgressCount;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);
});
});
app.filter('counterValue', function(){
return function(value){
value = parseInt(value);
if(!isNaN(value) && value >= 0 && value < 10)
{return "0"+ value;
return "";
}else{
return value;
return "";
}
}
})
server.js
var express = require("express");
var cookieSession = require('cookie-session');
var bodyParser = require("body-parser");
var session = require("express-session");
var app = express();
app.use(express.static("app"));
app.use(cookieSession({
secret: '1234567qwerty',
signed: true,
}));
app.use(session({
cookie: {
maxAge: 60 * 10
},
resave: false,
rolling: true,
saveUninitialized: true,
secret: "COOKIE_SECRET"
}));
app.use(bodyParser.json());
app.get("/login", function (req, res, _next) {
console.log(req.session.id);
var email = req.body.email;
var pass = req.body.pass;
if (email == req.session.user && pass == req.session.pass) {
res.status(401).end();
console.log("Inside login else logic" + req.body.email);
} else {
req.session.user = req.body.email;
req.session.password = req.body.password;
console.log("Inside login if logic" + req.body.email);
res.end();
}
});
app.get("/me", function (req, res, next) {
console.log(req.session.id);
if (req.session.user) {
res.send(req.session.user);
} else {
res.status(405).end();
console.log("status");
}
});
var server = app.listen(4000, function () {
console.log("Sample login server running");
});
It should login and then display the ticket raised count and when clicked on add ticket button the cookie should be valid

Hide navbar item after successful Log in in AngularJS

I would like to hide the following Login and Register navbar items after successful login:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>LogOut</li>
<li>Register</li>
</ul>
</div>
Here is my Login Controller:
app.controller('loginController', ['$scope', '$window', 'accountService', '$location', function ($scope, $window, accountService, $location) {
$scope.loginPageHeader = "Login Page";
$scope.account = {
username: '',
password: ''
}
$scope.login = function () {
accountService.login($scope.account).then(function (data) {
$location.path('/home');
}, function (error) {
$scope.message = error.error_description;
})
}
$scope.logout = function () {
accountService.logout();
$location.path('/login');
}
}])
Here is my AccountService:
app.factory('accountService', ['$http', '$q', 'serviceBasePath', 'userService', '$window', function ($http, $q, serviceBasePath, userService, $window) {
var fac = {};
fac.login = function (user) {
var obj = { 'username': user.username, 'password': user.password, 'grant_type': 'password' };
Object.toparams = function ObjectsToParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/token",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
userService.SetCurrentUser(response.data);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
fac.logout = function () {
userService.CurrentUser = null;
userService.SetCurrentUser(userService.CurrentUser);
}
return fac;
}])
Here is my UserService:
app.factory('userService', function () {
var fac = {};
fac.CurrentUser = null;
fac.SetCurrentUser = function (user) {
fac.CurrentUser = user;
sessionStorage.user = angular.toJson(user);
}
fac.GetCurrentUser = function () {
fac.CurrentUser = angular.fromJson(sessionStorage.user);
return fac.CurrentUser;
}
return fac;
})
Tried with $rootScope but didn't work after page refresh as $rootScope is lost after page refresh. Any Help Please!!
You can add a check in your app's run function and set it on the $rootScope. This way a reload (f5) doesn't interfere with the login:
app.run(["$rootScope", "userService", function($rootScope, userService) {
var user = userService.GetCurrentUser();
if (user) {
$rootScope.user = user;
}
}]);
Then in your view:
<li>Login</li>
Also mind that you set it on the $rootScope when logging in:
fac.SetCurrentUser = function (user) {
fac.CurrentUser = user;
sessionStorage.user = angular.toJson(user);
$rootScope.user = user;
}
See jsfiddle

How to get username of currenlty logged on user authservice

I would like to get the currently loged in username so i can display it. But i dont know how to do it ? Any ideas ? I am using authservice Here is my angular controller in which i would like to get the username.
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my main angular controller code
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my second angular code :
var app = angular.module('myApp');
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
$scope.gotoregister = function () {
$location.path('/register');
};
$scope.gotoprive = function () {
$location.path('/prive');
};
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
and my services
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http) {
// create user variable
var user = null;
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
So this should probably work, maybe you will need to make some small adjustments because i don't know how exactly is your app structured, but this will work.
First you need to change your AuthService to look like this
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
after that changes in authService, you must make this on your app run, so each time application run (refresh) it first check coockie to see if there is active session(member) and if there is it will set it inside our AuthService.
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
And simply anywhere where you want to get auth member you have to do this, first include in your controller/directive AuthService and do this
AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
});
I hope this helps you, if you find any difficulties i'm happy to help
just a demo example
in login controller
var login = function(credentials) {
AuthService.login(credentials).then(function(result) {
var user = result.data;
AuthService.setCurrentUser(user);
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
}).catch(function(err) {
if (err.status < 0) {
comsole.error('Please check your internet connection!');
} else {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
}
});
};
in AuthService
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
}
}
return service;
});
in the controller which attached with your dashboard view
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.fullName = AuthService.getFullName();
vm.currentUser = AuthService.getCurrentUser();
}
});
There are few methods how you can get currently logged user, it mostly depends on you app structure and API, you probably should have API end point to get authenticated member and that call is made on each app refresh.
Also if you can show us your authservice.
Edit:
Also on successful login you can store information about logged user in coockie like this
function doLogin(admin) {
return authMemberResources.login(details).then(function(response) {
if (response) {
$cookies.putObject('loginSession', response);
} else {
console.log('wrong details');
}
});
So basically you can use angularjs coockies service and make loginSession coockie like that, and on app refresh or anywhere where you need logged user info, you can get that like this:
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
console.log(session);
}
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
},
getAuthenticatedMember: function() {
if ($cookies.get('currentUser')) {
return JSON.parse($cookies.get('currentUser'));
}
}
}
return service;
});
That should work, i added new function getAuthenticatedMember and you can use it where you need it. And you can use it like this:
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.currentUser = AuthService.getAuthenticatedMember();
}
});

Authentication and Authorization in AngularJS

I am following a tutorial from this blog
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.4st6f3te5
for Authentication and Authorization in angualrJS
Also trying to fallow some implementation in Stackoverflow
on this link
$injector:modulerr : authentication in AngularJS applications
I keep getting this error
$scope.setCurrentUser is not a function
which is coming from the loginController
Can someone help please?
this the AuthService
pmaster.factory('AuthService', ['$http', 'Session', function ($http,
Session) {
var authService = {};
authService.login = function (credentials)
{
return $http.get('/api/userLogin/' + credentials).then(function (data)
{
// this is the date coming from the Server //[{"sessionID":"aendypagaw5ytojlxjcvjgyo","userID":"ljanneh1","Role":"superAdmin"}]
Session.create(data.sessionID, data.userID, data.Role);
return data
});
};
authService.isAuthenticated = function()
{
return !!Session.userId;
};
authService.isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService; }]);
this is the login control
pmaster.controller('loginController', ['$scope', '$location',
'$rootScope', 'AUTH_EVENTS', 'AuthService',
function ($scope, $location, $rootScope, AUTH_EVENTS, AuthService)
{
$rootScope.menuHide = true;
$rootScope.sideHide = true;
$scope.Login = function()
{
$scope.loading = true;
var credentials =
{
'username': $scope.username,
'password': $scope.password
}
var obj = credentials.username + "-" + credentials.password;
AuthService.login(obj).then(function (data)
{
console.log(data);
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
//$scope.setCurrentUser = function (data)
//{
// $rootScope.$emit("setUserRoles", data);
//}
$scope.setCurrentUser(data);
$location.path('/addBank');
$scope.loading = false;
}, function (error) {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
alert("Bad");
$scope.loading = false;
});
}
}]);

Circular dependency in AngularJS

I've been trying to call UserService.openLogin() function from interceptorService (file: authenticationServices.js), but I'm not succeeding.
All is working right, but when I try to inject UserService as a dependency, in the interceptorService, AngularJS returns me the following error:
"Uncaught Error: [$injector:cdep] Circular dependency found: $http <- UserService <- interceptorService <- $http <- $templateRequest <- $compile".
Please, can someone help me?
file: authenticationModule.js
angular
.module('app.authentication', [
'app.authentication.controllers',
'app.authentication.services',
'app.authentication.directives']
)
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/register', {
templateUrl: 'app/modules/authentication/authenticationViews/authenticationUserCreate.html',
controller: 'authenticationController as loginCtrl',
css: 'app/modules/authentication/authenticationViews/css/authenticationStyles.css',
})
.when('/edit', {
templateUrl: 'app/modules/authentication/authenticationViews/authenticationProfileEdit.html',
controller: 'authenticationController as loginCtrl',
css: 'app/modules/authentication/authenticationViews/css/authenticationStyles.css',
})
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('interceptorService');
}])
file: authenticationControllers.js
angular.module('app.authentication.controllers', [])
.controller('authenticationController', ['UserService', '$location', '$uibModalInstance',
function (UserService, $location, $uibModalInstance) {
var self = this;
self.user = {
username: '',
password: ''
};
self.login = function () {
UserService.login(self.user).then(
function (success) {
if (success.status == '400') {
window.alert(success.data.error_description);
}
else {
$location.path('/jobs');
$uibModalInstance.close();
}
},
function (error) {
UserService.logout();
window.alert(error.message)
})
};
self.closeLogin = function () {
$uibModalInstance.dismiss();
}
self.logout = function () {
UserService.logout();
};
}])
file: authenticationServices.js
angular.module('app.authentication.services', [])
.factory('StorageService', [function () {
return {
isAuth: false,
userData: {
userName: "",
token: ""
},
}
}])
.factory('UserService', ['$http', '$uibModal', 'StorageService', function ($http, $uibModal, StorageService) {
return {
login: function (user) {
var data = "grant_type=password&username=" + user.userName + "&password=" + user.password;
var serviceBase = "http://localhost:53944/";
return $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(function (response) {
if (response.data.access_token) {
StorageService.isAuth = true;
StorageService.userData.token = response.data.access_token;
}
return response;
});
},
openLogin: function () {
$uibModal.open({
animation: true,
templateUrl: 'app/modules/authentication/authenticationViews/authenticationLogin.html',
controller: 'authenticationController',
controllerAs: 'loginCtrl',
size: 'md'
})
},
logout: function () {
StorageService.userData.token = "";
StorageService.userData.userName = "";
StorageService.isAuth = false;
}
};
}])
.factory('interceptorService', ['StorageService', 'UserService', function (StorageService, UserService) {
return {
request: function (config) {
var userData = StorageService.userData;
if (userData.token) {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + userData.token;
}
return config;
},
responseError: function (rejection) {
debugger;
switch (rejection.status) {
case 401:
UserService.openLogin();
//window.alert("Erro: " + rejection.status);
break;
case 400:
window.alert("Erro: " + rejection.status + "Descrição: " + rejection.data.error_description);
break;
default:
window.alert("Erro: " + rejection.status);
}
return rejection;
}
}
}])
I've found a way to inject the UserService without circular dependency error. But I don't know whether is correct. Does someone know?
Look at the temporary solution:
.factory('interceptorService', ['StorageService', '$injector', function (StorageService, $injector) {
return {
request: function (config) {
var userData = StorageService.userData;
if (userData.token) {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + userData.token;
}
return config;
},
responseError: function (rejection) {
debugger;
switch (rejection.status) {
case 401:
$injector.get('UserService').openLogin();
break;
case 400:
window.alert("Erro: " + rejection.status + "Descrição: " + rejection.data.error_description);
break;
default:
window.alert("Erro: " + rejection.status);
}
return rejection;
}
}
}])

Categories