Redirect при статусе 403

Я использую Spring Boot и Angular. Я хочу чтобы при возникновении ошибки 403 или forbiden меня перенаправляло на соответсвующую страницу. Ошибка 403 должна возникать, когда я использую аннотацию @Secured для контроллера:

 @Secured("ROLE_OWNER")

    @GetMapping(path = "my-restaurants")
    public String myRestaurants(Model model) {
        return "forward:/index.html";
    }

Для этого в классе конфигурации WebSecurityConfig, я прописал exceptionHandling().accessDeniedPage("/forbiden")

Код класса WebSecurityConfig:

package com.greatproject.dishonline.config;

//import com.greatproject.dishonline.entity.User;
import com.greatproject.dishonline.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 /*   @Autowired
    PasswordEncoder passwordEncoder;*/

    @Autowired
    private DataSource dataSource;


    @Autowired
    private MyUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // включаем защиту от CSRF атак
        http.csrf()
                .disable()
                // указываем правила запросов
                // по которым будет определятся доступ к ресурсам и остальным данным
                .authorizeRequests()
                .antMatchers("/", "/index.html", "/registration","/createUser","/sendEmail","/confirmRegistration",
                        "/goYandex",
                        "/login",
                        "/loginPage", "/**").
                permitAll()
                .anyRequest().authenticated();
                /*.permitAll()
                .and();*/

        http.formLogin().defaultSuccessUrl("/cabinet",true)
                // указываем страницу с формой логина
                .loginPage("/loginPage")
                // указываем action с формы логина
                .loginProcessingUrl("/login")
                // указываем URL при неудачном логине
                .failureUrl("/loginPage?error")
                // Указываем параметры логина и пароля с формы логина
                .usernameParameter("login")
                .passwordParameter("password")
                // даем доступ к форме логина всем
                .permitAll().and().
                logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").and().exceptionHandling().accessDeniedPage("/forbiden");

        http.logout()
                // разрешаем делать логаут всем
                .permitAll()
                // указываем URL логаута
                .logoutUrl("/logout")
                // указываем URL при удачном логауте
                .logoutSuccessUrl("/loginPage?logout")
                // делаем не валидной текущую сессию
                .invalidateHttpSession(true);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider
                = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        //return new
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

Но при такой конфигурации пользователь с ролью ROLE_USER спокойно получает доступ к my-restaraunts, хотя не должен, должна возникать ошибка и переадресация на страницу forbiden. Если убрать exceptionHandling().accessDeniedPage("/forbiden") из конфигурации то тогда возникает ошибка 403(что и должно происходить) Более того доступ к my-restaraunts разрешён для неавторизованных пользователей, хотя согласно моей конфигурации этого не должно быть, поскольку контроллер my-restaraunts не указан в: antMatchers("/", "/index.html", "/registration","/createUser","/sendEmail","/confirmRegistration", "/goYandex", "/login", "/loginPage", "/**")

Помогите пожалуйста разобраться с данной проблемой.


Ответы (0 шт):