因此,当用户登录时,我调用Login函数。该函数调用UserService.GetByEmail,它执行一个GET HTTP请求,从数据库中获取user,并在登录时键入电子邮件的用户返回user作为响应。之后,我用if(user!==null&&user.password==password){part进行身份验证。然而,当我查看控制台输出时,我确实有一个用户变量的Object,但我没有user.password与密码进行比较。我如何将响应中的用户密码放入user.password
(function () {
'use strict';
angular
.module('app')
.factory('AuthenticationService', AuthenticationService);
AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService'];
function AuthenticationService($http, $cookieStore, $rootScope, $timeout, UserService) {
var service = {};
service.Login = Login;
service.SetCredentials = SetCredentials;
service.ClearCredentials = ClearCredentials;
return service;
function Login(email, password, callback) {
$http.post('/user/authenticate', { username: username, password: password })
.success(function (response) {
callback(response);
});
}
然后这是我的UserController在后端的一部分。
@RequestMapping(value = "/user/authenticate", method = RequestMethod.POST)
public ResponseEntity<Void> authenticateUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
}
我不确定我应该如何在后端进行身份验证。要做到这一点,需要采取哪些步骤?
您不应该以任何形式向客户端发送密码。如果您使用的是SpringSecurity,则需要调用服务器上的登录处理程序。
你应该考虑使用类似JWT的东西(点击此处阅读更多https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java)或者,如果出于某种原因确实需要使用基于表单的安全性,可以使用此代码块登录到服务器。
this.login = function (username, password, rememberMe) {
if (rememberMe === undefined) rememberMe = false;
return $http.post(
'/j_spring_security_check',
$.param({
j_username: username,
j_password: password,
j_remember: rememberMe
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
}
}
).then(_.bind(function (response) {
if (response.data.success === true) {
//something to happen on login
}
return $q.reject(response);
}, this));
};
this.logout = function () {
$http.get('/j_spring_security_logout').then(_.bind(function () {
//something to happen on logout
}, this));
};
有几件事:
- 这不可能是所有涉及的代码:不清楚UserService对象或AuthenticationService工厂函数是什么
- 此外,人们预计你无论如何都不会有密码可供比较(这有点安全漏洞)
相反,如果HTTP状态代码为200(或其他2xx代码,取决于后端),则应认为身份验证成功。通常,这意味着如果您输入promise的then()
子句,则登录必须成功,因为4xx代码将被映射到故障并通过catch()
报告。