SpringSecurity | ログイン済の場合はログイン画面から別の画面にリダイレクトさせる
2022.06.06ログイン済のユーザーがログイン画面(“/login”)を表示すると、再度ログインが可能な状態になります今回はログイン済のユーザーについては”/home”にリダイレクトさせるような実装を行ってみます
ここに書いてあるのは、あくまでサンプルです
関連記事も合わせて確認していただければと思います
また今回のコードは以下のgithubにあげています
https://github.com/jirentaicho/laravel-new-SecurityConfiguration
独自のフィルターを作成する
public class RedirectLoginUserFilter extends OncePerRequestFilter {
private final String TARGET_PATH = "/login";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("RedirectLoginUserFilterのdoFilterが呼ばれました");
// 認証済でない場合は処理を抜ける
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null){
filterChain.doFilter(request,response);
return;
}
AntPathRequestMatcher antPathRequestMatcher =
new AntPathRequestMatcher(TARGET_PATH, HttpMethod.GET.name());
// "/login"かつGETでない場合は処理を抜ける
if(!antPathRequestMatcher.matches(request)){
filterChain.doFilter(request,response);
return;
}
// リダイレクトする
response.sendRedirect("/home");
return;
}
}
- OncePerRequestFilterを継承してFilterとして機能するようにしています
- この場合doFilterInternalの実装が必要になります
- 認証オブジェクトを取得して、取得できなければ未ログインとして判定します
- SecurityContextHolder.getContext().getAuthentication()で認証オブジェクトを取得します
- AntPathRequestMatcherを使ってリクエストの情報をチェックします
- /loginでGETの場合にリダイレクトさせるので、それ以外は処理を抜けます
- ログイン済で”/login”にGETでアクセスした場合、response.sendRedirectで”/home”にリダイレクトさせます
次に独自に作成したFilterをHttpSecurityにて設定します
HttpSecurityの設定
コードは関連記事のWebSecurityConfigurerAdapterが非推奨になってたを利用しています
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers(header -> {
header.frameOptions().disable();
});
http.authorizeHttpRequests(authorize -> {
authorize.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
});
http.formLogin(form -> {
form.defaultSuccessUrl("/home");
});
// 追加
http.addFilterAfter(new RedirectLoginUserFilter(),UsernamePasswordAuthenticationFilter.class);
return http.build();
}
- addFilterでUsernamePasswordAuthenticationFilterの後にRedirectLoginUserFilterを登録します
- UsernamePasswordAuthenticationFilterは関連記事の
これでログイン後に”/login”にアクセスしても”/home”にリダイレクトされています
SecurityFilterChainにも登録されていることがわかります