SpringBoot(Security) ログイン認証を試す 1.設定
WebSecurityConfigurerAdapterを継承したクラスで設定を行う
- 制限を適用しないリソースを設定
@Override
public void configure(WebSecurity web) throws Exception {// 制限を適用しないパスを設定
web.ignoring().antMatchers("/js/∗∗", "/css/∗∗");
}
- ログイン認証の設定
@Override
protected void configure(HttpSecurity http) throws Exception {// ログイン不要ページの設定
http.authorizeRequests()
.antMatchers("/loginform", "/error" ).permitAll() //permitAll() でログインしなくてもアクセスできるパスを設定(ログイン画面とか)
.antMatchers("/admin/**").hasAuthority("ROLE_ADMIN") //アドミン権限に許可
.antMatchers("/user/**").hasRole("USER") //ユーザ権限に許可、hasRoleは「ROLE_」を補完
.anyRequest().authenticated(); //その他はログインしないとアクセス不可
//ログイン処理の設定
http.formLogin()
.loginProcessingUrl("/login") //ログイン処理のパス
.loginPage("/loginform") //ログインページのパス
.failureUrl("/loginform") //ログイン失敗時の遷移先
.usernameParameter("email") //ログインのユーザーID
.passwordParameter("password") //ログインのパスワード
.defaultSuccessUrl("/", true); //ログイン成功後の遷移先(true:必ずTOP、false:ログイン前に指定していたページに遷移)
//ログアウト処理の設定
http.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")) // ログアウト処理のパス、logoutUrlはgetにしか適用されない
.logoutSuccessUrl("/login"); //ログアウト成功後のURL
.deleteCookies("JSESSIONID") // ログアウト時にクッキー削除
.invalidateHttpSession(true); // ログアウト時にセッション破棄http.sessionManagement().invalidSessionUrl("/loginform"); // セッション切れの場合の遷移先
}