1.Spring Security默认是禁用注解的,要想开启注解, 需要在继承WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled =true, securedEnabled =true)
/**
*prePostEnabled =true 开启@PreAuthorize注解过滤权限,
*例子:@PreAuthorize("@el.check('menu:list')")
*public ResponseEntity<Object> query(MenuQueryCriteria criteria) throws Exception
*例子中表示有查询菜单权限才可进入某方法
*/
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final TokenProvider tokenProvider;
private final CorsFilter corsFilter;
private final JwtAuthenticationEntryPoint authenticationErrorHandler;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final ApplicationContext applicationContext;
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
// 去除 ROLE_ 前缀
return new GrantedAuthorityDefaults("");
}
@Bean
public PasswordEncoder passwordEncoder() {
// 密码加密方式
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 搜寻匿名标记 url:@AnonymousAccess
Map<RequestMappingInfo,HandlerMethod> handlerMethodMap =applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
Set<String> anonymousUrls =new HashSet<>();
for (Map.Entry<RequestMappingInfo,HandlerMethod> infoEntry :handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod =infoEntry.getValue();
AnonymousAccess anonymousAccess =handlerMethod.getMethodAnnotation(AnonymousAccess.class);
if (null !=anonymousAccess) {
anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
}
}
httpSecurity
// 禁用CSRF
.csrf().disable()
.addFilterBefore(corsFilter,UsernamePasswordAuthenticationFilter.class)
// 授权异常
.exceptionHandling()
.authenticationEntryPoint(authenticationErrorHandler)
.accessDeniedHandler(jwtAccessDeniedHandler)
// 防止iframe 造成跨域
.and()
.headers()
.frameOptions()
.disable()
// 不创建会话
.and()
.sessionManagement()
//基础tokan,所以不需要session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 静态资源等等
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/webSocket/**"
).permitAll()
// swagger 文档
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/*/api-docs").permitAll()
// 文件
.antMatchers("/avatar/**").permitAll()
.antMatchers("/file/**").permitAll()
// 阿里巴巴druid
.antMatchers("/druid/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
// 自定义匿名访问所有url放行 : 允许匿名和带权限以及登录用户访问
.antMatchers(anonymousUrls.toArray(new String[0])).permitAll()
// 所有请求都需要认证
.anyRequest().authenticated()
.and().apply(securityConfigurerAdapter());
}
//如果实现类中没有复写configure(AuthenticationManagerBuilder auth),那就是默认调用auth。userDetailsService(UserDetailsService的实现类),如果写参数为org.springframework.security.core.userdetails.UserDetailsService的实现类
private TokenConfigurer securityConfigurerAdapter() {
return new TokenConfigurer(tokenProvider);
}
}