spring security 是一個用於權限驗證和資源權限管理的庫。簡單地記錄一下,spring security 集成到 spring boot
專案中的過程。
WebSecurityConfiguration#
主要是一個WebSecurityConfiguration
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(getUserDetailsService())
.passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
});
}
- 繼承
WebSecurityConfigurerAdapter
,然後重寫這個configure
方法,
可以設置使用者的來源: userDetailsService(UserDetailsService uds)
,UserDetailsService
決定了使用者怎麼來的。
比如:通過使用者名稱從資料庫查詢
@Bean
public UserDetailsService getUserDetailsService(){
return username -> {
SysUser user = userRepository.getSysUserByUsername(username);
if (user != null){
return user;
}else {
throw new UsernameNotFoundException("no such user name.");
}
};
}
- 可以設定密碼的驗證機制
.passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
});
可以設置密碼的加密和匹配方式
對請求進行權限控制#
提供了如 csrf 等功能,
- csrf
- antMatchers
- formLogin
- logout
等,對這些可以進一步設置
- disable() 如 csrf
- permitAll() 不需要權限
- authenticated() 需要權限
等。
例子:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.and()
.authorizeRequests()
.antMatchers("/api/*")
.authenticated()
.antMatchers("/")
.authenticated()
.and()
.formLogin()
.loginPage("/login/page")
.defaultSuccessUrl("/out")
.loginProcessingUrl("/login")
.failureUrl("/e")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/out")
.permitAll();
CsrfFilter csrfFilter = new CsrfFilter();
http.addFilterAfter(csrfFilter,CsrfFilter.class);
}