当验证码输入正常,但用户名或密码输入错误时,可以看到控制台里有错误信息,但页面上除了链接后面加了个 ?error外,什么提示都没有

这篇来处理一下springsecurity认证授权的异常

查源码

SecurityConfig.kt里配置 HttpSecurity 的地方,有一个 formLogin的配置

点进去可以看到 formLogin里面还有这么多属性

@SecurityMarker
class FormLoginDsl {
    var loginPage: String? = null
    var authenticationSuccessHandler: AuthenticationSuccessHandler? = null
    var authenticationFailureHandler: AuthenticationFailureHandler? = null
    var failureUrl: String? = null
    var loginProcessingUrl: String? = null
    var permitAll: Boolean? = null
    var authenticationDetailsSource: AuthenticationDetailsSource<HttpServletRequest, *>? = null
    var usernameParameter: String? = null
    var passwordParameter: String? = null

    private var defaultSuccessUrlOption: Pair<String, Boolean>? = null

根据属性名可知

  • authenticationSuccessHandler 是认证成功的操作逻辑
  • authenticationFailureHandler 是认证失败的操作逻辑

AuthenticationFailureHandler是一个接口,并有如下这些已经实现的类

打开 AbstractAuthenticationProcessingFilter 可以看到springsecurity默认给的failureHandler其实是 SimpleUrlAuthenticationFailureHandler

打开 SimpleUrlAuthenticationFailureHandler可以看到出异常的话,会跳转或重定向到一个 defaultFailureUrl的地址上

往上翻,能看到这个defaultFailureUrl参数是通过构造方法传进来的

SimpleUrlAuthenticationFailureHandler 的构造方法又在 AbstractAuthenticationFilterConfigurer里被调用并传了一个 authenticationFailureUrl

failureUrl()在当前类里被调用,并将 loginUrl的值拼接上了 ?error 传入了

所以SimpleUrlAuthenticationFailureHandler里的 defaultFailureUrl就来自于在SecurityConfig.kt里配置的loginUrl了。 所以这里也没必要再重新在SecurityConfig.kt里配置一遍

回到SimpleUrlAuthenticationFailureHandler里,当出现异常时,会调用一个saveException()方法用来处理异常信息的响应

如果是跳转,就会将异常放进 request 里返回,如果是重定向,就会放进 session里返回

SimpleUrlAuthenticationFailureHandler 里默认的跳转方式是重定向 private boolean forwardToDestination = false;

所以异常信息就被放在了 session 里,键是 WebAttributes.AUTHENTICATION_EXCEPTION ,也就是 SPRING_SECURITY_LAST_EXCEPTION

看到这就知道怎么在页面上取异常信息了

登录页

<form th:action="@{/loginpost}" method="POST">
    <fieldset>
        <legend>登录</legend>
        <!-- 从session中获取异常信息 -->
        <p th:text="${#ctx.session.SPRING_SECURITY_LAST_EXCEPTION?.message}" style="color:red;"></p>
        <ul>
            <li th:each="msg : ${#ctx.session.loginpost_errors}" th:text="${msg}"></li>
        </ul>
        <label for="username">用户名</label><br>
        <input type="text" name="username" id="username" placeholder="用户名"> <br>
        <label for="password">密码</label><br>
        <input type="password" name="password" id="password" placeholder="密码"> <br>
        <label for="code">验证码</label><br>
        <input type="text" name="code" id="code" placeholder="验证码"> <img th:src="@{/captcha}" alt="Captcha" id="captchaImg" onclick="updateCaptcha()"><br>
        <button type="submit">登录</button>
    </fieldset>
</form>

看一下效果

异常信息是英文的,springsecurity框架里给提供了国际化

所以只需要修改一下浏览器的请求接收语言为中文就行了

以firefox为例,设置位置在

总结

  • springsecurity默认提供了SimpleUrlAuthenticationFailureHandler的异常处理方式,我们只需稍加利用它定的规则就行了
  • spring框架对国际化支持的很好,不过要浏览器进行配合