简体   繁体   English

使用Spring Security和Ajax登录信息处理无效的用户/密码

[英]Handling invalid user/password using spring security and ajax login

I am using spring security login+ ajax login. 我正在使用Spring Security登录+ Ajax登录。 If a user provides wrong credential i need to show a message saying "invalid user/password" 如果用户提供的凭据错误,我需要显示一条消息,指出“无效的用户名/密码”

This is the ajax login jquery code. 这是ajax登录jquery代码。

$(document).ready(function(){
$('#login_btn').click(function(){
    //alert("aaa"+validateLoginForm());
    if(validateLoginForm()){

        sprpst = 'j_username='+$('#j_username').val()+'&j_password='+$('#j_password').val();
        $.post('j_spring_security_check',sprpst,function(data1) {

            window.location.reload();

        }); 
        $.blockUI({ message : '<h1><img src="images/busy.gif" /> Loading...</h1>' });
    }
});
});

This is the spring security login 这是春季安全登录

<form-login login-page="/login" default-target-url="/deals" authentication-failure-url="/deals?login_error=1"/>

Any help will be appreciated. 任何帮助将不胜感激。

Thanks :) 谢谢 :)

You need: 你需要:

  1. Provide a custom AuthenticationEntryPoint (that can use default LoginUrlAuthenticationEntryPoint as a base class). 提供一个自定义AuthenticationEntryPoint(可以使用默认的LoginUrlAuthenticationEntryPoint作为基类)。 In AuthenticationEntryPoint.commence(...) method check that this is AJAX call and return 403 code instead of redirecting to login page. AuthenticationEntryPoint.commence(...)方法中,检查这是否为AJAX调用,并返回403代码而不是重定向到登录页面。
  2. Set up your custom AuthenticationEntryPoint in Spring Security conf. 在Spring Security conf中设置您的自定义AuthenticationEntryPoint。
  3. Check the code of AJAX response. 检查AJAX响应的代码。 If it contains 403 then show corresponding error message about wrong credentials. 如果包含403,则显示有关错误凭证的相应错误消息。

The code of a custom authentication entry point may looks like: 自定义身份验证入口点的代码如下所示:

public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String header = request.getHeader("X-Requested-With");
        if (StringUtils.hasText(header) && header.equals("XMLHttpRequest") && authException != null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            super.commence(request, response, authException);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM