Created
July 3, 2016 21:10
-
-
Save oguzhanaslan/db56ef755c1b7273aa8a8288e0abdcee to your computer and use it in GitHub Desktop.
Angular JWT localStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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