解释
AuthenticationEntryPoint
简介
AuthenticationEntryPoint
是Spring Security Web
一个概念模型接口,顾名思义,他所建模的概念是:“认证入口点”。
它在用户请求处理过程中遇到认证异常时,被ExceptionTranslationFilter
用于开启特定认证方案(authentication schema
)的认证流程。
AccessDeniedHandler
AccessDeniedHandler仅适用于已通过身份验证的用户。未经身份验证的用户的默认行为是重定向到登录页面(或适用于正在使用的身份验证机制的任何内容)。
1、匿名用户访问某个接口时
/**
* @author yuguang
* @date 2020/10/14 13:08
* @desc 403 forbidden处理
* 用来解决匿名用户访问无权限资源时的异常
*/
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
String errorMsg = objectMapper.writeValueAsString(BaseResult.error("没有权限"));
out.write(errorMsg);
out.flush();
out.close();
}
}
2、已经授权但是没有访问权限
/**
* @author yuguang
* @date 2020/10/14 12:04
* @desc 403自定义返回json
* 用来解决认证过的用户访问无权限资源时的异常
*/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
String errorMsg = objectMapper.writeValueAsString(BaseResult.error("没有权限"));
out.write(errorMsg);
// out.write("{\"status\": \"error\", \"msg\":\"权限不足请联系管理员!!\"}");
out.flush();
out.close();
}
}
3、配置
@Resource
MyAccessDeniedHandler myAccessDeniedHandler;
@Resource
private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
@Override
public void configure(HttpSecurity http) throws Exception {
if (jwtProperties.getCsrfDisabled()) {
http = http.csrf().disable();
}
http.cors()//
.and().addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
//todo 无权限时的处理
.exceptionHandling()
.authenticationEntryPoint(myAuthenticationEntryPoint)
.accessDeniedHandler(myAccessDeniedHandler)....
4、测试
{
"httpCode": 403,
"reasonPhrase": null,
"data": null,
"extraData": null,
"message": "没有权限"
}