在Spring登录中显示错误消息 [英] Display error messages in Spring login

查看:88
本文介绍了在Spring登录中显示错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring安全性对用户进行身份验证.我创建了一个自定义身份验证提供程序,现在我想知道如何将错误消息从提供程序获取到表单中.这是我的自定义身份验证提供程序中的authenticate()方法:

I am using Spring security for authenticating users. I created a custom authentication provider and now I am wondering how I can get error messages from the provider into my form. This is the authenticate() method in my custom authentication provider:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UserProfile profile = userProfileService.findByEmail(authentication.getPrincipal().toString());

    if(profile == null){
        throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal()));
    }

    String suppliedPasswordHash = DigestUtils.shaHex(authentication.getCredentials().toString());

    if(!profile.getPasswordHash().equals(suppliedPasswordHash)){
        throw new BadCredentialsException("Invalid credentials");
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(profile, null, profile.getAuthorities());

    return token;
}

这是我的表格:

<form name='f' action="<c:url value='j_spring_security_check' />" method='POST'>
<div id="data-entry-form">

    <div class="form-entry">
        <label><spring:message code="login.form.label.email"/></label>
        <input type='text' name='j_username' value=''>
    </div>
    <div class="form-entry">
        <label><spring:message code="login.form.label.password"/></label>
        <input type='password' name='j_password'/>
    </div>
    <div class="form-entry">
        <input type="submit" value="Verzenden"/>
    </div>
</div>

如何将错误消息发送到表单中?从我按下登录按钮的那一刻起,Spring接管了工作,因此,我可以生成错误消息的唯一方法是authenticate()方法...

How would I get error messages into my form? From the moment I press the login button, Spring takes over, so the only method I could generate error messages in would be the authenticate() method...

推荐答案

最安全的3个步骤(我们不依赖LAST_EXCEPTION):

3 Steps of the safest way (we don't rely on the LAST_EXCEPTION):

  1. 为您的自定义身份验证提供程序配置错误页面(例如"login-error")

  1. Specify error page (for example "login-error") in configuration for your custom authentication provider

httpSecurity
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/img/**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.failureUrl("/login-error")
.and()
.logout().permitAll()

  • 为url/login-error创建控制器,该控制器返回带有以下代码的自定义登录页面(例如"login")的视图:

  • Create controller for url /login-error that returns view of your custom login page (for example "login") with the next code:

    @Controller
    public class LoginController {
    
        @GetMapping("/login-error")
        public String login(HttpServletRequest request, Model model) {
            HttpSession session = request.getSession(false);
            String errorMessage = null;
            if (session != null) {
                AuthenticationException ex = (AuthenticationException) session
                        .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
                if (ex != null) {
                    errorMessage = ex.getMessage();
                }
            }
            model.addAttribute("errorMessage", errorMessage);
            return "login";
        }
    }
    

  • 最终将错误消息获取到您的页面中(例如,ThymeLeaf标签):

  • Get the error message into your page finally (ThymeLeaf tags for example):

    <!--/*@thymesVar id="errorMessage" type="java.lang.String"*/-->
    <div class="alert" th:if="${errorMessage}" th:text="${errorMessage}"></div>
    

  • 这篇关于在Spring登录中显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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