springsecurity03--异常拦截处理(认证异常、权限异常)
目录
Spingsecurity异常拦截处理
认证异常拦截
权限异常拦截
注册异常拦截器
设置跨域访问
Spingsecurity异常拦截处理
认证异常拦截
/*自定义认证异常处理器类*/
@Component
public class MyAuthenticationExceptionHandler implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request,HttpServletResponse response,AuthenticationException authException) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");ResponseResult responseResult = newResponseResult(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.value(), "认证失败!");response.getWriter().append(JSON.toJSONString(responseResult));}
}
第一次测试,测试登陆失败返回结果
权限异常拦截
/*** 自定义权限拒绝异常处理器*/
@Component
public class MyAccessDenyHandler implements AccessDeniedHandler {@Overridepublic void handle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException accessDeniedException) throws IOException, ServletException {response.setContentType("application/json;charset=utf-8");ResponseResult responseResult = newResponseResult(403, "权限拒绝,没有访问权限!");response.getWriter().append(JSON.toJSONString(responseResult));}
}
第二次,权限不足返回结果
注册异常拦截器
@Configuration
//启用security的注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate MyAuthenticationExceptionHandler myAuthenticationExceptionHandler;@Autowiredprivate MyAccessDenyHandler myAccessDenyHandler;@Overrideprotected void configure(HttpSecurity http) throws Exception {//配置自定义异常处理器(认证异常、权限拒绝异常)http.exceptionHandling().authenticationEntryPoint(myAuthenticationExceptionHandler).accessDeniedHandler(myAccessDenyHandler);
}
相关权限注解
@PreAuthorize("hasAuthority('user:list')")
@PreAuthorize("hasAuthority('system:dept:list')")
@PreAuthorize("hasAnyAuthority('system:dept:list','system:test:list')")
@PreAuthorize("hasRole('CEO')")
@PreAuthorize("hasAnyRole('CEO')")
hasAuthority 和数据库表权限是等值比对
hasRole 添加ROLE_ 之后和数据库表中的角色名字比对
设置跨域访问
@Configuration
public class MyCorsFilter implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") //路径.allowedOrigins("*") //域名.allowedMethods("*") //方法 get/post/put/delete.allowedHeaders("*") //请求头.allowCredentials(true) ; //cookie 是否允许携带cookie}
}