--------------------------------------------------------------------------------------------------------
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
// パスワードエンコーダーBean
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// 認証するユーザーの情報をデータベースからロードする
String userSql="select user_Id,password, 1 as ENABLED from Account where user_Id=?";// Oracleにboolean型がない
String roleSql="select user_Id,ACCOUNT_GROUP as ROLE from Account where user_Id=?";
AuthenticationManagerBuilder authBuilder=http.getSharedObject(AuthenticationManagerBuilder.class);
authBuilder.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(userSql)
.authoritiesByUsernameQuery(roleSql)
.passwordEncoder(passwordEncoder());
// バージョンログ
String springSecurityVersion = SpringSecurityCoreVersion.getVersion();
System.out.println("Spring Security Version: " + springSecurityVersion);
// ログインページ設定
http.authorizeHttpRequests(
authz -> authz.requestMatchers("/css/**").permitAll()
.requestMatchers("/js/**").permitAll()
.requestMatchers("/login2").permitAll()
.requestMatchers("/admin/").permitAll()
.requestMatchers("/signup").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN") // admin権限しかアクセスできない。
.anyRequest().authenticated() // 上記URL以外は認証が必要
);
// ログイン処理
http.formLogin(login -> login //HttpSecurity
.loginProcessingUrl("/login2") // ログイン処理Path
.loginPage("/login2")
.failureUrl("/login2") // ログイン認証失敗時の遷移先
.usernameParameter("userId")
.passwordParameter("password")
.defaultSuccessUrl("/home",true)
.permitAll());
// ログアウト処理
http.logout(logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login2")
// セッション無効化
.deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll());
// CRFS対策を無効
http.csrf(csrf -> csrf.disable());
return http.build();
}
}