目录
Spingsecurity异常拦截处理
认证异常拦截
java
/*
自定义认证异常处理器类
*/
@Component
public class MyAuthenticationExceptionHandler implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
ResponseResult responseResult = new
ResponseResult(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.value(), "认证失败!");
response.getWriter().append(JSON.toJSONString(responseResult));
}
}
第一次测试,测试登陆失败返回结果

权限异常拦截
java
/**
* 自定义权限拒绝异常处理器
*/
@Component
public class MyAccessDenyHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
ResponseResult responseResult = new
ResponseResult(403, "权限拒绝,没有访问权限!");
response.getWriter().append(JSON.toJSONString(responseResult));
}
}
第二次,权限不足返回结果

注册异常拦截器
java
@Configuration
//启用security的注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationExceptionHandler myAuthenticationExceptionHandler;
@Autowired
private MyAccessDenyHandler myAccessDenyHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置自定义异常处理器(认证异常、权限拒绝异常)
http.exceptionHandling()
.authenticationEntryPoint(myAuthenticationExceptionHandler)
.accessDeniedHandler(myAccessDenyHandler);
}
相关权限注解
java
@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_ 之后和数据库表中的角色名字比对
设置跨域访问
java
@Configuration
public class MyCorsFilter implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //路径
.allowedOrigins("*") //域名
.allowedMethods("*") //方法 get/post/put/delete
.allowedHeaders("*") //请求头
.allowCredentials(true) ; //cookie 是否允许携带cookie
}
}