Spring Security的配置类要继承WebSecurityConfigurerAdapter。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//我代表代码
}
@Override
public void configure(HttpSecurity http) throws Exception {
//我代表代码
}
@Override
public void configure(WebSecurity web) throws Exception {
//我代表代码
}
}
配置类可以@Override三个配置方法:
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//添加后门
auth.authenticationProvider(backdoorAuthenticationProvider);
//自定义AuthenticationProvider实例加入AuthenticationManager
auth.userDetailsService(backendSysUserDetailsServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
auth.authenticationProvider(backendSysUserAuthenticationProvider);
}
AuthenticationManagerBuilder用来配置全局的认证相关的信息,其实就是AuthenticationProvider和UserDetailsService,前者是认证服务提供者,后者是认证用户(及其权限)。
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/",
"/index",
"/error"
).permitAll()
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/user")
//TODO 自定义参数名称,与login.html中的参数对应
.usernameParameter("myusername").passwordParameter("mypassword")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
//鉴权
.and()
.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(backendSysRoleSecurityMetadataSourceImpl);
object.setAccessDecisionManager(backendSysRoleAccessDecisionManagerImpl);
return object;
}
});
}
HttpSecurity 具体的权限控制规则配置。一个这个配置相当于xml配置中的一个标签。
各种具体的认证机制的相关配置,OpenIDLoginConfigurer、AnonymousConfigurer、FormLoginConfigurer、HttpBasicConfigurer
LogoutConfigurer
RequestMatcherConfigurer:spring mvc style、ant style、regex style
HeadersConfigurer:
CorsConfigurer、CsrfConfigurer
SessionManagementConfigurer:
PortMapperConfigurer:
JeeConfigurer:
X509Configurer:
RememberMeConfigurer:
ExpressionUrlAuthorizationConfigurer:
RequestCacheConfigurer:
ExceptionHandlingConfigurer:
SecurityContextConfigurer:
ServletApiConfigurer:
ChannelSecurityConfigurer:
此模块的authenticationProvider和userDetailsService;
SecurityFilterChain控制。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/js/**");
}
WebSecurity 全局请求忽略规则配置(比如说静态文件,比如说注册页面)、全局HttpFirewall配置、是否debug配置、全局SecurityFilterChain配置、privilegeEvaluator、expressionHandler、securityInterceptor。
网友评论