Spring security
1.認證Authentication,確認用戶可以訪問當前系統
重寫protect void configure(AuthenticationManagerBuilder auth){
1. auth.inMemoryAuthentication()
.withUser(“ss”).password(“ss”).roles(“ROLE_ADMIN”);//內存中的用戶
2. auth.jdbcAuthentication().dataSource(dataSource) //jdbc中的用戶
(Spring security中默認了數據庫的結構,可以自定義查詢用戶和權限的sql語句)
3. auth.userDetaisService(customUserService) //通用的用戶,見下:
}
通用的用戶:數據訪問不僅僅是內存或jdbc,還可能是非關係型數據庫,或JPA,需要自定義實現UserDetailService接口
//自定義類CustomUserService實現UserDetailsService接口
public class CustomUserService implements UserDetailsService{
@Autowired
SysUserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String name){
//SysUser是系統的用戶領域類對象
SysUser user = userRepository.findbyUsername(name);
List<GrantedAuthority> authoritys = new ArrayList<GrantedAuthority>();
authoritys.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
//User來自於spring security框架
return new User(user.getUsername(),user.getPassword(),authoritys);
}
}
//註冊這個實現類
@Bean
UserDetaisService customUserService(){
return new CustomUserService();
}
2.授權Authorization,確認用戶在當前系統下所擁有的功能權限
重寫protected void configure(HttpSecurity http)
請求攔截路徑匹配器:
autMatchers:使用ant風格的路徑匹配
regexMatchers:正則表達式匹配路徑
anyRequest:匹配所有的請求路徑
匹配請求路徑後,進行安全處理,Spring security提供了安全處理方法:
access(String)spring el表達式爲true時可訪問;
denyAll()用戶不能訪問;
permitAll()用戶可以任意訪問
authenticated()用戶登錄後可以訪問
… …
如:@Override
protected void configure(HttpSecurity http){
http.authorizeRequests() //開始請求權限配置
.autMatchers("/admin/**").hasRole("ROLE_ADMIN")
.autMatchers("/user/**").hasAnyRole("ROLE_ADMIN","ROLE_USER")
.anyRequest().authenticted();//其餘所有用戶都需要認證後(登陸後)纔可以訪問
}
定製登錄行爲:
@Override
protected void configure(HttpSecurity http){
http.fromLogin() //定製登錄操作
.loginPage("/login")
.defaultSuccessUrl("/index")
.failureUrl("/login?error")
.permitAll()
.and()
.rememberMe() //開啓cookie存儲用戶信息
.tokenValiditySeconds(1209600)
.key("myKey")
.and()
.logout()
.logoutUrl("/custome-logout")
.logoutSuccessUrl("/logout-success")
.permitAll();
}