使用Ajax使用Spring Security登录 [英] Login with Spring security using Ajax

查看:83
本文介绍了使用Ajax使用Spring Security登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring Security在基于Ajax的登录系统上工作,并且运行良好,直到遇到另一个需要配置authentication-success-handler的要求,以便在用户通过身份验证后可以进行一些后处理春季安全性.

I am trying to work on Ajax based login system using Spring Security and it was working fine, till I got with another requirement where I need to configure authentication-success-handler, so as I can do some post processing once user is authenticated by Spring security.

以前我没有使用<form-login/>来显示登录"页面.我的登录"部分是下拉列表,并且是整个应用程序通用的标题部分.

Earlier I was not using <form-login/> for showing Login page.My Login section is a drop down and part of header section which is common for entire application.

这就是我尝试配置Spring安全性的方式

This is how I am trying to configure Spring security

<http pattern="/customer/**" auto-config="true" use-expressions="true" authentication-manager-ref="customerAuthenticationManager">
<!--<http pattern="/customer/**" auto-config="true" use-expressions="true">-->
<intercept-url pattern="/customer/logon.html*" access="permitAll" />
<intercept-url pattern="/customer/denied.html" access="permitAll"/>
<intercept-url pattern="/customer" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/*.html" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/*/*.html" access="hasRole('AUTH_CUSTOMER')" />

<form-login login-processing-url="/customer/logon.html" login-page="/shop/home.html" 
authentication-success-handler-ref="webshopAuthenticationSuccessHandler" />

<logout invalidate-session="true" 
   logout-success-url="/customer/home.html" 
    logout-url="/customer/j_spring_security_logout" />
 <access-denied-handler error-page="/customer/denied.html"/>
    </http>

通过这些配置,每当我使用正确的凭据单击登录按钮时,都会收到HTTP 302错误

With these configuration, when ever I am clicking on login button with correct credentials, i am getting HTTP 302 error

http://localhost:8080/shop/customer/logon.html 302 found

不确定我到底在做什么错吗?

Not sure what exactly I am doing wrong?

<form id="login" method="post" accept-charset="UTF-8">
    <input id="userName" type="text" name="userName" size="30" />
    <button type="submit" class="btn">Login</button>
</form>

Ajax代码

 var data = $(this).serializeObject();
  $.ajax({
  'type': 'POST',
  'url': "<c:url value="/customer/logon.html"/>",
   'contentType': 'application/json',
    'data': JSON.stringify(data),
     'dataType': 'json',
....
}}:

登录部分

 Authentication authenticationToken = new UsernamePasswordAuthenticationToken(customer.getUserName(), customer.getPassword());
   try {
       Authentication authentication = customerAuthenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
           } catch (AuthenticationException ex) {

            resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
   }

有输入吗?经过我的所有努力,我仍然得到302,并且具有上述配置,即使我的logon.html控制器也没有被调用.

Any inputs? With all my efforts, I am still getting 302 and with above configuration, even my logon.html controller is not getting called.

我的主要问题是何时使用

My main issue is when I am enabling Spring security using

<form-login login-processing-url="/customer/logon.html" login-page="/shop/home.html" 
    authentication-success-handler-ref="webshopAuthenticationSuccessHandler" />

我从logon.html获取302,甚至没有触发logon.html控制器(将调试器放置在其上)

I am getting 302 from logon.html and even logon.html Controller is not being triggered (placed debugger on it)

推荐答案

首先,您不需要控制器,Spring Security会为您处理所有这一切.因此放下控制器.

First you don't need a controller, spring security handles all this for you. So drop the controller.

当前问题归因于您基于JSON的帖子.这由处理登录的普通过滤器处理,但没有看到j_usernamej_password字段,因此将重定向(302)到登录页面(在您的情况下为/shop/home.html),要求输入领域.

The current problem is due to your JSON based post. This is handled by the normal filter which handles login, but it doesn't see a j_username and j_password field and as such will redirect (the 302) to the login page (in your case /shop/home.html) asking for those fields.

基本上,您是以JSON形式发布数据,而只是将其发布为Ajaxified表单即可.这样,您就可以编写一个简单的AuthenticationSuccessHandler,当一切正常时,该AuthenticationSuccessHandler仅返回401或200状态代码(甚至是正文).

Basically you are posting the data as JSON whereas it simply should be just an ajaxified form post. This allows you to write a simple AuthenticationSuccessHandler which simply returns a 401 or a 200 status-code (and maybe a body) when things are ok.

更改ajax提交到这样的东西应该可以使事情工作.

Changing your ajax submit to something like this should make things work.

var data = $(this).serializeObject();
$.ajax({
    'type': $(this).action,
    'url': $(this).target,
    'data': data
}):

这应该创建一个ajax表单发布.可能是因为您需要在周围的方法中调用preventDefault()才能停止表单的实际发布.

This should create a ajax form post. Might be that you need a call to preventDefault() in the surrounding method to stop the form from actual posting.

这篇关于使用Ajax使用Spring Security登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆