Spring Security 中的异常主要分为两大类:一类是认证异常,另一类是授权相关的异常
说的通俗点:
一个是你去买票,你要提供身份证信息,才能买(也就是认证),一个是买到了票,你根据你的座位入座,否则不能入座(也就是权限)
对应到浏览器报的错误: 前者是401(未授权),后者是403(被拒绝)
代码我们去实现的话,思路就很明了了,我们只需要实现两个类,一个去捕获登陆时发生的错误,一个去捕获 权限认证时发生的错误,再把两个类加到 登陆配置类 里面就好了。
登陆异常捕获类
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//todo your business
HashMap<String, String> map = new HashMap<>(2);
map.put("uri", request.getRequestURI());
map.put("msg", "认证失败");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();
}
}
权限异常捕获类
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
//todo your business
HashMap<String, String> map = new HashMap<>(2);
map.put("uri", request.getRequestURI());
map.put("msg", "认证失败");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();
}
}
登陆配置类添加
.exceptionHandling().accessDeniedHandler(new SimpleAccessDeniedHandler()).authenticationEntryPoint(new SimpleAuthenticationEntryPoint())
.and()
项目启动,输入url,
http://localhost:8081/process?username=Felordcn&password=123456&login_type=0
可以看到
文章相关代码转载来自 https://www.felord.cn/categories/spring-security/ ,感谢大佬的分享哈