我将使用基于令牌的身份验证,您可以在其中随每个请求发送令牌(自动)。您将必须登录一次,服务器将为您提供一个令牌,您可以将其用于发送每个请求。该令牌将添加到HTML标头中,因此您不必修改对浏览器的每个请求。
您可以在API中设置某些调用,以使它们始终需要令牌,而其他调用可能不受令牌保护。
对于Express,可以使用express-jwt(https://www.npmjs.org/package/express-
jwt)
var expressJwt = require('express-jwt');// Protect the /api routes with JWTapp.use('/api', expressJwt({secret: secret}));app.use(express.json());app.use(express.urlenpred());
如果要进行身份验证,可以在快递服务器中创建以下功能:
app.post('/authenticate', function (req, res) { //if is invalid, return 401 if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) { res.send(401, 'Wrong user or password'); return; } var profile = { first_name: 'John', last_name: 'Doe', email: 'john@doe.com', id: 123 }; // We are sending the profile inside the token var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 }); res.json({ token: token });});
对于受保护的呼叫,以/ api开头的内容:
app.get('/api/restricted', function (req, res) { console.log('user ' + req.user.email + ' is calling /api/restricted'); res.json({ name: 'foo' });});
在Angular应用程序中,您可以登录:
$http .post('/authenticate', $scope.user) .success(function (data, status, headers, config) { $window.sessionStorage.token = data.token; $scope.message = 'Welcome'; }) .error(function (data, status, headers, config) { // Erase the token if the user fails to log in delete $window.sessionStorage.token; // Handle login errors here $scope.message = 'Error: Invalid user or password'; });
通过创建身份验证拦截器,它将随每个请求自动发送令牌:
myApp.factory('authInterceptor', function ($rootScope, $q, $window) { return { request: function (config) { config.headers = config.headers || {}; if ($window.sessionStorage.token) { config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; } return config; }, response: function (response) { if (response.status === 401) { // handle the case where the user is not authenticated } return response || $q.when(response); } };});myApp.config(function ($httpProvider) { $httpProvider.interceptors.push('authInterceptor');});
如果必须支持不支持本地存储的旧浏览器。您可以将其
$window.sessionStorage与AmplifyJS(http://amplifyjs.com/)之类的库交换。例如,放大使用任何可用的本地存储。这将转换为以下内容:
if (data.status === 'OK') { //Save the data using Amplify.js localStorage.save('sessionToken', data.token); //This doesn't work on the file protocol or on some older browsers //$window.sessionStorage.token = data.token; $location.path('/pep'); } }).error(function (error) { // Erase the token if the user fails to log in localStorage.save('sessionToken', null); // Handle login errors here $scope.message = 'Error: Invalid user or password'; });
和我们交换的authintercepter:
angular.module('myApp.authInterceptor', ['myApp.localStorage']).factory('authInterceptor', [ '$rootScope', '$q', 'localStorage', function ($rootScope, $q, localStorage) { return { request: function (config) { config.headers = config.headers || {}; config.headers.Authorization = 'Bearer ' + localStorage.retrieve('sessionToken'); return config; }, response: function (response) { if (response.status === 401) { } return response || $q.when(response); } }; }]);
您可以在本文中找到除AmplifyJS之外的所有内容:
http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-
token/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)