home wiki.fukuchiharuki.me
Menu

キーワード

  • Spring Boot
  • Spring Security

したいこと

特定のログインエラー時に画面遷移したい(ログイン画面には戻らずに)。

どうやって

認証失敗したときのハンドラを用意する

public class SecurityConfigAuthenticationFailureHandler 
  extends ExceptionMappingAuthenticationFailureHandler{

	public SecurityConfigAuthenticationFailureHandler() {
		this.setDefaultFailureUrl("/");
		this.setExceptionMappings(getFailureUrlMap());
	}
	
	private Map<String, String> getFailureUrlMap() {
		Map<String, String> map = new HashMap<>();
		map.put(CredentialsExpiredException.class.getName(), "/reset_password");
		return map;
	}

}
  • Mapは<String,String>
    • 例外のクラス名
    • リダイレクト先(コンテキストパスは補ってくれる)

ハンドラをセットする

http.formLogin()
  .loginPage("/")
  .failureHandler(new SecurityConfigAuthenticationFailureHandler())
  // あといろいろ

リダイレクト先を認証不要にする

http.authorizeRequests()
  // 認証不要
  .antMatchers(
      // ログイン
      "/",
      // パスワードリセット
      "/reset_password"
  )
  .permitAll()
  // あといろいろ

ノート

こうだよとバシッと書いてくれてる記事が見つからなくて少してこずった。

参考