【发布时间】:2013-11-30 07:49:23
【问题描述】:
所以我一直在玩 Grails 的 Spring Security,我玩得很开心,但我被困在关于通过 AJAX 登录的一件小事上。我有一个登录表单,通过 AJAX 发布到/j_spring_security_check 以便登录,它运行良好,但是当我直接进入登录页面 1)时,我对不同的响应感到困惑,2)当我被重定向时当我尝试访问安全页面时到登录页面。登录页面是/login/auth,我将auth.gsp 中的标准表单替换为AJAXified 表单。以下是两种情况:
- 我直接浏览到
/login/auth,当我这样做并使用 AJAX 登录时,我得到了标准 JSON 对象,也就是说,我得到了类似{"success":true,"username":"charles"}或{"error":"Sorry, we were not able to find a user with that username and password."}的东西 - 没有意外 - 一切都很好。 - 由于
/login/auth是“该”登录页面,当我浏览到我的应用程序中的另一个控制器/操作(如/users/list)并且我未通过身份验证时,我会按预期重定向到/login/auth。因此,当我输入伪造的凭据时,我会按预期返回{"error":"Sorry, we were not able to find a user with that username and password."},但是当我使用正确的凭据登录时,我会在响应正文中返回最初请求页面的实际 HTML。理想情况下,我想取回{"success":true,"username":"charles", referer:"/users/list"}之类的东西——这样我的登录表单就可以做很酷的动画内容,然后重定向到最初请求的 URL。我看到发生了什么事,在LoginController.groovy中的第 1 种情况ajaxSuccess()被调用(返回 JSON) - 但在这种情况下它没有被调用,我无法找出调用了什么所以我可以破解它来做我想做的事。
有没有更好的方法来做到这一点?或者有人可以指出我正确的方向吗?我将非常感谢任何帮助!
非常感谢!
:)
这是我的 AJAX 调用,如果它有帮助的话,虽然它非常标准:
<script>
$(document).ready(function(){
$("#submit").click(function(){
$("#response").html("Attempting login...");
var formdata = $('#loginForm').serialize();
$.ajax({
url: "/UserDemo/j_spring_security_check",
type: 'post',
data: formdata,
success: function(r){
if (r.success) {
$("#response").html("Success!");
} else if (r.error) {
$("#response").html(r.error);
}
}
});
});
});
【问题讨论】:
-
有趣的问题。我从来没有用spring security做过ajax登录。您使用的是什么版本(Grails 和插件)?尝试在您的配置中设置 successHandler.ajaxSuccessUrl,如下所述:grails-plugins.github.io/grails-spring-security-core/docs/…
-
可能覆盖成功处理程序以返回 json 响应会有所帮助
-
@チャルス リヅ 你找到解决方案了吗。我有同样的问题。
标签: ajax grails spring-security