目錄
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}
}