Spring Security
Spring Security是作爲過濾器控制權限的,在web.xml中配置過濾器。
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
定義security配置
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
//使用and()添加新的配置選項
//登錄頁設置爲允許所有用戶訪問
.and().formLogin().loginPage("/login").permitAll()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
配置類需要@EnableWebSecurity、@EnableGlobalMethodSecurity、@EnableGlobalAuthentication中的一個標註。
access(“hasRole(‘ADMIN’)”) =access(“ROLE_ADMIN”)
configure()函數的配置對應XML爲:
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-page="/" default-target-url="/" authentication-failure-url="/? login=error" />
<logout logout-success-url="/" />
</http>
環境初始化
1.單獨使用spring security,需要將MySecurityConfig傳入並構造初始化Security環境的實例。該類自動將應用中的每個url註冊到SpringSecurityFilterChain,並且加載Security的配置。
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(MySecurityConfig.class);
}
}
2.如果項目中使用了Spring,則項目中存在初始化Web環境的類,這時將Spring Security註冊到已經存在的ApplicationContext中。
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
這個類將應用中的url註冊到SpringSecurityFilterChain。然後需要將MySecurityConfig加載到已經存在的程序上下文中。
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { MySpringSecurityConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Security中的類
Authentication
Authentication接口表示用戶認證信息,用戶登錄認證之前相關信息會封裝爲一個Authentication具體實現類的對象,登錄認證後會生成一個包含用戶權限的Authentication對象,並保存在SecurityContextHolder的Context中。
//獲得用戶名
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username=((UserDetails) principal).getUsername();
AuthenticationManager
AuthenticationManager是一個用來處理認證(Authentication)請求的接口。在其中只定義了一個方法authenticate(),該方法只接收一個代表認證請求的Authentication對象作爲參數,如果認證成功,則會返回一個封裝了當前用戶權限等信息的Authentication對象進行返回。
AuthenticationManager的默認實現是ProviderManager,但是它不直接自己處理認證請求,而是委託給其所配置的AuthenticationProvider列表,然後會依次使用每一個AuthenticationProvider進行認證,如果有一個AuthenticationProvider認證後的結果不爲null,則表示該AuthenticationProvider已經認證成功,之後的AuthenticationProvider將不再繼續認證。如果所有的AuthenticationProvider的認證結果都爲null,則表示認證失敗,將拋出一個ProviderNotFoundException。
<authentication-manager>
//user-service-ref指定關聯哪個AuthenticationProvider,默認爲DaoAuthenticationProvider
<authentication-provider user-service-ref="">
</authentication-provider>
</authentication-manager>
默認情況下,認證成功後ProviderManager將清除返回的Authentication中的憑證信息(密碼等),因此無法直接將Authentication緩存用於以後的登錄認證。一種辦法是設置ProviderManager的eraseCredentialsAfterAuthentication屬性爲false。