五.Spring Security-认证结果处理

五.认证结果处理

一.认证成功处理

1.1.解决方案

自定义类实现AuthenticationSuccessHandler接口复写 onAuthenticationSuccess方法,该方法其中一个参数是Authentication ,他里面封装了认证信息,用户信息UserDetails等,我们需要在这个方法中使用Response写出json数据即可

1.2.认证成功结果处理

1.定义AuthenticationSuccessHandler
定义类实现AuthenticationSuccessHandler接口复写onAuthenticationSuccess方法,实现自己的认证成功结果处理

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) 
throws IOException, ServletException {
        Map map = new HashMap<>();
        map.put("success",true);
        map.put("message","认证成功");
        response.getWriter().print(JSON.toJSONString(map));
        response.getWriter().flush();
        response.getWriter().close();
    }
}

2.导入JSON依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.50</version>
</dependency>

3.配置AuthenticationSuccessHandler
在SpringSecurity配置定义的AuthenticationSuccessHandler
http.formLogin()
//.successForwardUrl("/loginSuccess") // 设置登陆成功页
.successHandler(new MyAuthenticationSuccessHandler)

二.认证失败结果处理

2.1.解决方案

自定义登录失败的处理,需要实现AuthenticationFailureHandler接口,复写onAuthenticationFailure方法实现自己的认证失败结果处理

2.2.认证失败结果处理

1.定义处理器

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Map map = new HashMap<>();
        map.put("success",false);
        map.put("message","认证失败");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().print(JSON.toJSONString(map));
        response.getWriter().flush();
        response.getWriter().close();
    }
}

2.配置处理器
http.formLogin()
.failureHandler(new MyAuthenticationFailureHandler)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值