Spring Securityでログイン後に別のページにリダイレクトする
1. 概要
Webアプリケーションの一般的な要件は、redirect different types of users to different pages after loginです。 この例としては、標準ユーザーを/homepage.htmlページにリダイレクトし、管理ユーザーを/console.htmlページにリダイレクトする場合があります。
この記事では、Spring Securityを使用してこのメカニズムを迅速かつ安全に実装する方法を示します。 この記事は、プロジェクトに必要なコアMVCのもののセットアップを扱うSpring MVC tutorialの上にも構築されています。
2. Springセキュリティ構成
Spring Securityは、認証が成功した後に何をするかを直接決定するコンポーネントであるAuthenticationSuccessHandlerを提供します。
これを@Configurationクラスで構成する方法を見てみましょう。
@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
.withUser("user1").password("{noop}user1Pass").roles("USER")
.and()
.withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
// @formatter:on
}
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new MySimpleUrlAuthenticationSuccessHandler();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(myAuthenticationSuccessHandler())
// ...
}
}
この構成で焦点を当てる部分は、the custom authentication success handler bean and using the successHandler() method to add the bean to the security configuration.の定義です。
残りの構成はかなり標準的なものです。単一の単純なhttp要素がすべてを保護し、/login*への認証されていないアクセスのみを許可し、標準のメモリ内認証プロバイダーが物事を単純に保ちます。
同等のxml構成:
3. カスタム認証成功ハンドラー
Springは、AuthenticationSuccessHandlerインターフェースに加えて、この戦略コンポーネント(AbstractAuthenticationTargetUrlRequestHandler)と単純な実装(SimpleUrlAuthenticationSuccessHandler)の適切なデフォルトも提供します。 通常、これらの実装はログイン後にURLを決定し、そのURLへのリダイレクトを実行します。
ある程度柔軟性はありますが、このターゲットURLを決定するメカニズムでは、プログラムで決定を行うことはできません。そのため、インターフェイスを実装し、成功ハンドラーのカスタム実装を提供します。 This implementation is going to determine the URL to redirect the user to after login based on the role of the user:
public class MySimpleUrlAuthenticationSuccessHandler
implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/homepage.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
戦略の中核であるdetermineTargetUrlは、単にユーザーのタイプ(権限によって決定される)とpicks the target URL based on this roleを調べます。
したがって、ROLE_ADMIN権限によって決定されるadmin userは、ログイン後にコンソールページにリダイレクトされ、ROLE_USERによって決定されるthe standard userはにリダイレクトされます。ホームページ。
4. 結論
いつものように、この記事で紹介されているコードはover on Githubで利用できます。 これはMavenベースのプロジェクトであるため、インポートしてそのまま実行するのは簡単です。