【发布时间】:2016-05-25 16:00:33
【问题描述】:
您好,我在网上学习了一个教程。一切正常,但我会用秘密或 jwt 对 bas64 进行编码,但我不知道如何。你能帮帮我吗?
(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 = '';
}
}
})();
还有我的服务:
function run($rootScope, $http, $location, $localStorage) {
// keep user logged in after page refresh
if ($localStorage.currentUser) {
$http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser.token;
}
// redirect to login page if not logged in and trying to access a restricted page
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var publicPages = ['/login'];
var restrictedPage = publicPages.indexOf($location.path()) === -1;
if (restrictedPage && !$localStorage.currentUser) {
$location.path('/login');
}
});
}
和nodeJs:
function setupFakeBackend($httpBackend) {
var testUser = { username: 'test', password: 'test', firstName: 'Test', lastName: 'User' };
// fake authenticate api end point
$httpBackend.whenPOST('/api/authenticate').respond(function (method, url, data) {
// get parameters from post request
var params = angular.fromJson(data);
// check user credentials and return fake jwt token if valid
if (params.username === testUser.username && params.password === testUser.password) {
return [200, { token: 'fake-jwt-token' }, {}];
} else {
return [200, {}, {}];
}
});
$httpBackend.whenGET(/^\w+.*/).passThrough();
}
谢谢你的回答:)
【问题讨论】:
-
只是一个简单的问题,为什么要散列令牌?无论如何它应该已经是base64编码了。
-
另外,我建议将您的 JWT 存储在 cookie 中而不是本地存储中 - ... 将您的 JWT 存储在 Web 应用程序的 cookie 中,因为它们提供了额外的安全性,并且可以简单地防止CSRF 与现代 Web 框架。 HTML5 Web 存储易受 XSS 攻击,攻击面较大,攻击成功时会影响所有应用程序用户。 - stormpath.com/blog/…
-
谢谢!我以为它不是自动编码的。我是初学者,对不起。谢谢,我会在 cookie 上查看您的链接
标签: angularjs node.js authentication login jwt