五.认证结果处理
一.认证成功处理
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)
…