@postya

Как создать кастомные страницы для Access Denied Page и Error Whitelabel Page в Spring Security?

В приложении есть Spring Security
если не авторизованный пользователь заходит на админскую страницу , то появляется стандартная страница "Access Denied ,status 403"
я хочу изменить эту страницу на свою кастомную. Также хочу изменить стандартную странцу Whitelabel Error Page на свою.
Как можно изменить эти стандартные страницы на свои?

Структура проекта, где лежат кастомные темплейты:

5e90a479f0f91295579251.jpeg

Конфигурация Spring Security:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").authenticated()
                .antMatchers("/**").permitAll()
        .and().exceptionHandling().accessDeniedPage("/handlers/access-denied.html");

    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(

                // статика
                "/css/**",
                "/js/**",
                "/fonts/**",
                "../libs/**",
                "/images/**"
        );
    }
}
  • Вопрос задан
  • 377 просмотров
Решения вопроса 1
azerphoenix
@azerphoenix Куратор тега Spring
Java Software Engineer
Здравствуйте!
Access denied (Forbidden) - 403 ошибка.
Создайте controller или controllerAdvice для http ошибок.

@Controller
public class HttpErrorController implements ErrorController {

    private final MessageSource messageSource;

    @Autowired
    public HttpErrorController(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @RequestMapping("/error")
    public String handleError(
            Locale locale,
            Model model,
            HttpServletRequest request,
            Exception ex
    ) {

        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {

            int statusCode = Integer.valueOf(status.toString());

            Map<String, String> metaData = new HashMap<>();

            // 403
            if (statusCode == HttpStatus.FORBIDDEN.value()) {

               // do somthing
            }

            // 404
            else if (statusCode == HttpStatus.NOT_FOUND.value()) {
                // do somthing
            }

            // 405
            else if (statusCode == HttpStatus.NOT_FOUND.value()) {
                // do somthing
            }

            // 500
            else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
               // do somthing
            }

        }


        return "templates/errors/httperrors";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

}


Чтобы отключить whitelibel page добавьте в properties
# Disable Whitelabel Error Page
server.error.whitelabel.enabled=false
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы