開発者ドキュメント

Springセキュリティ:403アクセス拒否ページをカスタマイズする

Spring Securityでは、権限のないユーザが保護されたページにアクセスしようとすると、デフォルトの「

http 403 access denied

」が表示されます:



このチュートリアルでは、Spring Securityでアクセス拒否ページをカスタマイズする方法を説明します。

1.春のセキュリティ設定

“alex”が `/admin`ページにアクセスしようとすると、403のアクセス拒否ページが表示されます。

Spring-Security.xml

  <http auto-config="true">
    <access-denied-handler error-page="/403"/>
    <intercept-url pattern="/admin** ** " access="ROLE__ADMIN"/>
  </http>

  <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="alex" password="123456" authorities="ROLE__USER"/>
        <user name="mkyong" password="123456" authorities="ROLE__USER, ROLE__ADMIN"/>
      </user-service>
    </authentication-provider>
  </authentication-manager>

2.解決策 – 403ページをカスタマイズする

2.1新しい403ページを作成します。

403.jsp

<html>
<body>
    <h1>HTTP Status 403 - Access is denied</h1>
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-2836379775501347"
     data-ad-slot="8821506761"
     data-ad-format="auto"
     data-ad-region="mkyongregion"></ins>
<script>
(adsbygoogle = window.adsbygoogle ||[]).push({});
</script><h2>${msg}</h2>
</body>
</html>

2.2。上記のページを表示するには、次のような `error-page`を追加します:

Spring-Security.xml

    <http auto-config="true">
        <access-denied-handler error-page="/403"/>
        <intercept-url pattern="/admin** ** " access="ROLE__ADMIN"/>
    </http>

2.3コントローラークラスで、 “/403” URLのマッピングを追加します。

HelloController.java

package com.mkyong.web.controller;

import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

   //for 403 access denied page
    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public ModelAndView accesssDenied(Principal user) {

        ModelAndView model = new ModelAndView();

        if (user != null) {
            model.addObject("msg", "Hi " + user.getName()
            + ", you do not have permission to access this page!");
        } else {
            model.addObject("msg",
            "You do not have permission to access this page!");
        }

        model.setViewName("403");
        return model;

    }

}

完了しました。

注釈ユーザの場合は、この `.exceptionHandling()。accessDeniedPage(”/403 “)`を使用します。

SecurityConfig.java

package com.mkyong.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

     http.authorizeRequests()
        .antMatchers("/admin/** ** ").access("hasRole('ROLE__ADMIN')")
        .and().formLogin()
        .loginPage("/login").failureUrl("/login?error")
        .usernameParameter("username")
        .passwordParameter("password")
        .and().logout().logoutSuccessUrl("/login?logout")
        .and()
        .exceptionHandling().accessDeniedPage("/403")
    }
}

3. AccessDeniedHandler

さらに、URLを

/403`マッピングに渡す前にカスタムの

AccessDeniedHandler`を作成してビジネスロジックを実行することもできます。

MyAccessDeniedHandler.java

package com.mkyong.web.exception;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class MyAccessDeniedHandler implements AccessDeniedHandler {

    private String errorPage;

    public MyAccessDeniedHandler() {
    }

    public MyAccessDeniedHandler(String errorPage) {
        this.errorPage = errorPage;
    }

    public String getErrorPage() {
        return errorPage;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException)
                throws IOException, ServletException {

       //do some business logic, then redirect to errorPage url
        response.sendRedirect(errorPage);

    }

}

httpタグに `ref`を追加してください。

Spring-Security.xml

    <http auto-config="true">
        <access-denied-handler ref="my403"/>
        <intercept-url pattern="/admin** ** " access="ROLE__ADMIN"/>
    </http>

    <beans:bean id="my403"
        class="com.mkyong.web.exception.MyAccessDeniedHandler">
        <beans:property name="errorPage" value="403"/>
    </beans:bean>

完了しました。

4.デモ

“alex”が `/admin`ページにアクセスしようとすると、上記の403アクセス拒否ページがカスタマイズされます。

4.1 `error-page`を使うとurlは次のように表示されます:



4.2カスタムアクセス拒否ハンドラ `ref`を使用している場合、urlは次のように表示されます:



ソースコードをダウンロードする

ダウンロードする – リンク://wp-content/uploads/2011/08/spring-security-403-access-denied.zip[spring-security-403-access-denied.zip](26 KB)

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