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);
}