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

Spring Security:403アクセス拒否ページのカスタマイズ

Spring Securityでは、許可されていないユーザーが保護されたページにアクセスしようとすると、デフォルトの「http 403 access denied」が表示されます。

spring-security-403-default

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

1. Spring Securityの構成

構成を確認します。「alex」が/adminページにアクセスしようとすると、403を超えるアクセス拒否ページが表示されます。

Spring-Security.xml

  
    
    
  

  
    
      
        
        
      
    
  

2. ソリューション– 403ページのカスタマイズ

2.1 Create a new 403 page.

403.jsp



    

HTTP Status 403 - Access is denied

${msg}

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

Spring-Security.xml

    
        
        
    

2.3 In a controller class, add a mapping for “/403” url :

HelloController.java

package com.example.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.example.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

さらに、カスタムAccessDeniedHandlerを作成して、URLを/403マッピングに渡す前にいくつかのビジネスロジックを実行できます。

MyAccessDeniedHandler.java

package com.example.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

    
        
        
    

    
        
    

完了しました。

4. Demo

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

4.1 If using error-page, url will be displayed like this :

spring-security-403-example1

4.2 If using custom access denied handler ref, url will be displayed like this :

spring-security-403-example2

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

ダウンロード–spring-security-403-access-denied.zip(26 KB)