Skip to content

Instantly share code, notes, and snippets.

@oguzhanaslan
Created July 3, 2016 21:10
Show Gist options
  • Select an option

  • Save oguzhanaslan/db56ef755c1b7273aa8a8288e0abdcee to your computer and use it in GitHub Desktop.

Select an option

Save oguzhanaslan/db56ef755c1b7273aa8a8288e0abdcee to your computer and use it in GitHub Desktop.
Angular JWT localStorage
(function () {
'use strict';
angular
.module('app')
.factory('AuthenticationService', Service);
function Service($http, $localStorage) {
var service = {};
service.Login = Login;
service.Logout = Logout;
return service;
function Login(username, password, callback) {
$http.post('/api/authenticate', { username: username, password: password })
.success(function (response) {
// login successful if there's a token in the response
if (response.token) {
// store username and token in local storage to keep user logged in between page refreshes
$localStorage.currentUser = { username: username, token: response.token };
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = 'Bearer ' + response.token;
// execute callback with true to indicate successful login
callback(true);
} else {
// execute callback with false to indicate failed login
callback(false);
}
});
}
function Logout() {
// remove user from local storage and clear http auth header
delete $localStorage.currentUser;
$http.defaults.headers.common.Authorization = '';
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment