Spring Security --SecurityConfig的详细配置
一、SecurityConfig在之前的文章中,我们从底层源码的层面了解到,要接管Spring Security的配置,就必须继承WebSecurityConfigurerAdapter,并加上@EnableWebSecurity注解。一个比较完整的SecurityConfig配置如下:@Configuration//开启判断用户对某个控制层的方法是否具有访问权限的功能@EnableGlobalM
·
一、SecurityConfig
在之前的文章中,我们从底层源码的层面了解到,要接管Spring Security的配置,就必须继承WebSecurityConfigurerAdapter,并加上@EnableWebSecurity注解。
一个比较完整的SecurityConfig配置如下:
@Configuration
//开启判断用户对某个控制层的方法是否具有访问权限的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//注入自定义的UserDetailService
@Autowired
@Lazy
private UserDetailsServiceImpl userDetailsServiceImpl;
@Autowired
private StringRedisTemplate stringRedisTemplate;
//替换默认AuthenticationManager中的UserDetailService,使用数据库用户认证方式登录
//1. 一旦通过 configure 方法自定义 AuthenticationManager实现 就回将工厂中自动配置AuthenticationManager 进行覆盖
//2. 一旦通过 configure 方法自定义 AuthenticationManager实现 需要在实现中指定认证数据源对象 UserDetailService 实例
//3. 一旦通过 configure 方法自定义 AuthenticationManager实现 这种方式创建AuthenticationManager对象工厂内部本地一个 AuthenticationManager 对象 不允许在其他自定义组件中进行注入
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsServiceImpl);
}
/**
* BCryptPasswordEncoder相关知识:
* 用户表的密码通常使用MD5等不可逆算法加密后存储,为防止彩虹表破解更会先使用一个特定的字符串(如域名)加密,然后再使用一个随机的salt(盐值)加密。
* 特定字符串是程序代码中固定的,salt是每个密码单独随机,一般给用户表加一个字段单独存储,比较麻烦。
* BCrypt算法将salt随机并混入最终加密后的密码,验证时也无需单独提供之前的salt,从而无需单独处理salt问题。
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//将自定义AuthenticationManager在工厂中进行暴露,可以在任何位置注入
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
//HttpSecurity配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors(withDefaults())
// 禁用 CSRF
.csrf().disable()
.authorizeRequests()
// 指定的接口直接放行
// swagger
.antMatchers(SecurityConstants.SWAGGER_WHITELIST).permitAll()
.antMatchers(SecurityConstants.H2_CONSOLE).permitAll()
.antMatchers(HttpMethod.POST, SecurityConstants.SYSTEM_WHITELIST).permitAll()
// 其他的接口都需要认证后才能请求
.anyRequest().authenticated()
.and()
//添加自定义Filter
.addFilter(new JwtAuthorizationFilter(authenticationManager(), stringRedisTemplate))
// 不需要session(不创建会话)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 授权异常处理
.exceptionHandling()
// json提示用户没有登录不需要用户跳转到登录页面去
.authenticationEntryPoint(new JwtAuthenticationEntryPoint())
// 权限拦截器,提示用户没有当前权限
.accessDeniedHandler(new JwtAccessDeniedHandler());
// 防止H2 web 页面的Frame 被拦截
http.headers().frameOptions().disable();
}
/**
* Cors配置优化
**/
@Bean
CorsConfigurationSource corsConfigurationSource() {
org.springframework.web.cors.CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(singletonList("*"));
// configuration.setAllowedOriginPatterns(singletonList("*"));
configuration.setAllowedHeaders(singletonList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "OPTIONS"));
configuration.setExposedHeaders(singletonList(SecurityConstants.TOKEN_HEADER));
configuration.setAllowCredentials(false);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
二、详细讲解
而WebSecurityConfigurerAdapter 有三个重要的configure 可以覆写,一个与验证相关的AuthenticationManagerBuilder,另外两个是与Web 相关的HttpSecurity 和WebSecurity。
- AuthenticationManagerBuilder : 用来
配置全局的验证资讯
,也就是AuthenticationProvider 和UserDetailsService。 - WebSecurity : 用来
配置全局忽略的规则,如静态资源、是否Debug、全局的HttpFirewall、SpringFilterChain 配置
、privilegeEvaluator、expressionHandler、securityInterceptor,启动HTTPS等 - HttpSecurity : 用来
配置各种具体的验证机制规则
,如OpenIDLoginConfigurer、AnonymousConfigurer、FormLoginConfigurer、HttpBasicConfigurer 等。
更多推荐
所有评论(0)