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三個(gè)配置方法:
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//添加后門
auth.authenticationProvider(backdoorAuthenticationProvider);
//自定義AuthenticationProvider實(shí)例加入AuthenticationManager
auth.userDetailsService(backendSysUserDetailsServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
auth.authenticationProvider(backendSysUserAuthenticationProvider);
}
AuthenticationManagerBuilder用來配置全局的認(rèn)證相關(guān)的信息,其實(shí)就是AuthenticationProvider和UserDetailsService乒省,前者是認(rèn)證服務(wù)提供者衔峰,后者是認(rèn)證用戶(及其權(quán)限)。
@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 自定義參數(shù)名稱,與login.html中的參數(shù)對應(yīng)
.usernameParameter("myusername").passwordParameter("mypassword")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
//鑒權(quán)
.and()
.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(backendSysRoleSecurityMetadataSourceImpl);
object.setAccessDecisionManager(backendSysRoleAccessDecisionManagerImpl);
return object;
}
});
}
HttpSecurity 具體的權(quán)限控制規(guī)則配置熙兔。一個(gè)這個(gè)配置相當(dāng)于xml配置中的一個(gè)標(biāo)簽弛说。
各種具體的認(rèn)證機(jī)制的相關(guān)配置挽懦,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 全局請求忽略規(guī)則配置(比如說靜態(tài)文件圃伶,比如說注冊頁面)、全局HttpFirewall配置、是否debug配置窒朋、全局SecurityFilterChain配置搀罢、privilegeEvaluator、expressionHandler侥猩、securityInterceptor榔至。