目錄
WebSecurityConfigurerAdapter 類是個適配器, 在配置SecurityConfig時需要我們自己寫個配置類去繼承這個適配器,根據需求重寫適配器的方法.
@Configuration
@EnableWebSecurity
public class WebSecurityConfigextends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.failureForwardUrl("/login?error")
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/index")
.permitAll()
.and()
.httpBasic()
.disable();
}
}
程序說明一
Security的認證策略, 每個模塊配置使用and結尾。
- authorizeRequests()配置路徑攔截,表明路徑訪問所對應的權限,角色,認證信息。
- formLogin()對應表單認證相關的配置
- logout()對應了註銷相關的配置
- httpBasic()可以配置basic登錄
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
程序說明二
這段 配置是認證信息,
AuthenticationManagerBuilder 類是AuthenticationManager的建造者, 我們只需要向這個類中, 配置用戶信息, 就能生成對應的AuthenticationManager, 這個類也提過,是用戶身份的管理者, 是認證的入口, 因此,我們需要通過這個配置,想security提供真實的用戶身份。 如果我們是使用UserDetailsService來配置用戶身份的話, 這段配置改爲如下:
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(dbUserDetailsService);
}
dbUserDetailsService就是你自己寫的類, 這個類的作用就是去獲取用戶信息,比如從數據庫中獲取。 這樣的話,AuthenticationManager在認證用戶身份信息的時候,就回從中獲取用戶身份,和從http中拿的用戶身份做對比。