SpringSecurity-4-AuthenticationFailureHandler接口(登录失败之后的处理逻辑)

本文演示当使用spring security登录失败之后,在浏览器的页面上显示一个json字符串,内容是{"status","666","message","帐号密码不匹配"}

阅读本文之前如果要想运行的话,则需要先了解之前的文章使用浏览器访问并登录,因为本文涉及到一些HTML页面,如果不需要运行,那么直接看本文就行

首先定义一个往前端输出字符串的类,具备往response写数据的功能,当登录成功之后,该类被调用,这样就是先了本文的功能,代码如下

public class TestLoginErrorHandler implements AuthenticationFailureHandler {
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out=response.getWriter();
        out.write("{\"status\",\"666\",\"message\",\"帐号密码不匹配\"}");
        out.close();
    }
}

通过前文可知我们应该实现WebSecurityConfigurerAdapter接口,代码如下


@Service
public class TestWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
                http
                .authorizeRequests()
                        .anyRequest()
                        .authenticated()
                        .and()
                .formLogin()
                        .loginPage("/TestLogin.html")
                        .loginProcessingUrl("/myLoginProcess")
                        .permitAll()
                         // 下面这行代码就是本篇文章新增的类,该类决定帐号密码输入错误之后如何处理
                        .failureHandler(new TestLoginErrorHandler())
                        .and()
                .csrf().disable();
    }
}

上一篇:登录成功后的处理逻辑
下一篇:模拟从数据库中获取用户信息

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值