開発者ドキュメント

Spring Securityでログインした後に別のページにリダイレクトする


1概要

Webアプリケーションの一般的な要件は、

ログイン後に

異なる種類のユーザーを異なるページにリダイレクトすることです。たとえば、標準ユーザーを

/homepage.html

ページに、管理ユーザーを

/console.html

ページにリダイレクトするとします。

この記事では、Spring Securityを使用してこのメ​​カニズムを迅速かつ安全に実装する方法を説明します。この記事はまた、リンクの上に構築されています:/spring-mvc-tutorial[Spring MVCチュートリアル]このプロジェクトに必要なコアMVCの設定について説明しています。


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())
           //...
    }
}

この構成の中心となるのは、カスタム認証成功ハンドラーBeanの定義と、そのBeanをセキュリティー構成に追加するための

successHandler()

メソッドの使用です。

その他の設定はかなり標準的なものです。すべてを保護し、

/login **

への認証されていないアクセスのみを許可する単一の単純な

http

要素、および物事を単純にするための標準のインメモリ認証プロバイダ

そして同等のxml設定:

<http use-expressions="true" >
    <intercept-url pattern="/login** " access="permitAll"/>
    <intercept-url pattern="/** ** " access="isAuthenticated()"/>

    <form-login login-page='/login.html'
      authentication-failure-url="/login.html?error=true"
      authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
    <logout/>
</http>

<beans:bean id="myAuthenticationSuccessHandler"
  class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>

<authentication-manager id="authenticationManager">
    <authentication-provider>
        <user-service>
            <user name="user1" password="{noop}user1Pass" authorities="ROLE__USER"/>
            <user name="admin1" password="{noop}admin1Pass" authorities="ROLE__ADMIN"/>
        </user-service>
    </authentication-provider>
</authentication-manager>


3カスタム認証成功ハンドラ


AuthenticationSuccessHandler

インターフェースの他に、Springはこの戦略コンポーネントの実用的なデフォルト –

AbstractAuthenticationTargetUrlRequestHandler

– と単純な実装 –

SimpleUrlAuthenticationSuccessHandler

も提供します。通常、これらの実装はログイン後にURLを決定し、そのURLへのリダイレクトを実行します。

やや柔軟性はありますが、このターゲットURLを決定するメカニズムでは、プログラムで決定することはできません。そのため、インターフェイスを実装し、成功ハンドラのカスタム実装を提供します。

この実装は、ユーザーの役割に基づいて、ログイン後にユーザーをリダイレクトするURLを決定します。

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

は、単純にユーザーのタイプ(権限によって決定される)を調べ、このロールに基づいてターゲットURLを選択します。

そのため、

ROLE

ADMIN

権限​​によって決定される

adminユーザー

はログイン後にコンソールページにリダイレクトされますが、



ROLE

USER

によって決定される 標準ユーザー** はホームページにリダイレクトされます。


4結論

いつものように、この記事で紹介されているコードはhttps://github.com/eugenp/tutorials/tree/master/spring-security-mvc-custom[over on Github]から入手できます。これはMavenベースのプロジェクトなので、そのままインポートして実行するのは簡単なはずです。

モバイルバージョンを終了