gpt4 book ai didi

ajax - 如何在Grails和AngularJS上使用Spring Security进行Ajax登录

转载 作者:行者123 更新时间:2023-12-02 13:51:19 25 4
gpt4 key购买 nike

我正在尝试创建将Ajax请求发送到服务器以进行登录的用户表单。

我来自Angular的POST函数如下所示:

$http({
method: 'POST',
url: '/j_spring_security_check',
data: {j_username: credentials.username, j_password: credentials.password},
params: {ajax: true}
})
.then(function (data) {
$rootScope.authenticated = false;
callback && callback();
},
function (error) {
$log.error("Error in login! " + JSON.stringify(error));
$rootScope.authenticated = false;
callback && callback();
});

application.yml中,我获得了Spring Security的此配置:
grails:
plugin:
springsecurity:
userLookup:
userDomainClassName: xxx.LoginUser
rejectIfNoRule: true
fii:
rejectPublicInvocations: false
controllerAnnotations:
staticRules:
[...]

当我调用函数并将请求发送到服务器时,会发生问题。 Spring Security不接受mu j_usernamej_password,并且始终返回状态为 200和错误文本 {"error":"Sorry, we were not able to find a user with that username and password."}的响应

聚苯乙烯
我正在将Spring Security插件用于Grails(3.0.4) http://grails-plugins.github.io/grails-spring-security-core/guide/index.html

最佳答案

所以这就是问题所在。 Spring Security插件仅接受带有数据作为查询字符串的POST请求,当我们通过Angular的$http调用在POST请求中传递某些数据时,它将在请求有效内容正文中发送数据,这会破坏登录,您会收到未找到用户的消息。

因此,第一种方法是使用usernamepasswordparams作为$http传递:

$http({
method: 'POST',
url: '/j_spring_security_check',
params: {j_username: credentials.username, j_password: credentials.password, ajax: true}
})

上面的方法可以正常工作,但是问题在于用户名和密码将在查询字符串中发送,因此任何人都可以在浏览器控制台中轻松读取,因为它不 protected 。另外,由于将其作为查询字符串参数进行传递,因此密码将以各种级别记录,例如Tomcat的localhost日志或Nginx日志。

要解决此问题,请更改您的代码,如下所示:
var data = 'j_username=' + credentials.username + '&j_password=' + credentials.password;

$http({
method: 'POST',
url: '@/j_spring_security_check',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})

因此,我们在这里要做的是将凭据作为发布数据发送,并以编程方式更改 Content-Type,以便Angular可以将其作为发布数据而不是JSON发送。

注意:另一个建议:Grails的 request属性 request.xhr不会告诉您通过Angular发出的请求是AJAX请求,因为Angular不会发送任何请求 header 来使其像Grails的AJAX一样工作。因此,添加以下代码:
var myApp = angular.module('myApp', []);             // Or whatever your app name is

myApp.run(['$http', function ($http) {
$http.defaults.headers.common['x-requested-with'] = 'XMLHttpRequest';
}]);

现在,您不必在Angular ajax: true调用中传递 $http

关于ajax - 如何在Grails和AngularJS上使用Spring Security进行Ajax登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com