SpringSecurity WebSecurityConfigurerAdapter類使用
- 目錄
-
-
- 程式說明一
- 程式說明二
-
目錄
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中拿的使用者身份做對比。