Spring boot - return 403 Forbidden instead of redirect to login page

11,110

This is a community Answer:

Problem:

Forbidden urls were returning the login page content (instead of a 403 status code).

I Had this code:

...
http.authorizeRequests().antMatchers("/uri/**").hasAuthority("SOME_ROLE");

Changed with Tong's suggestion:

...
http.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
http.authorizeRequests().antMatchers("/uri/**").hasAuthority("SOME_ROLE");
Share:
11,110
alexanoid
Author by

alexanoid

Updated on June 22, 2022

Comments

  • alexanoid
    alexanoid almost 2 years

    In Spring Boot web application I have a following security configuration:

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off   
        http
            .headers().frameOptions().disable()
            .and()
                .antMatcher("/**").authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .antMatchers("/actuator/**").hasAuthority(Authority.Type.ROLE_ADMIN.getName())
                .antMatchers("/login/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .loginProcessingUrl("/login")
                    .failureUrl("/login?error").permitAll()
            .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout")
            .and()
                .csrf().csrfTokenRepository(csrfTokenRepository())
            .and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        // @formatter:on
    }
    

    Right now, when I'm trying to access for example following url: /api/v1.0/user it redirects me to /api/login page.

    How to configure this in order to return 403 Forbidden instead of redirect to login page ?