Vishrut Dixit
Vishrut Dixit

Reputation: 71

Spring Boot Security 403 redirect

I'm using Spring Boot Security to authenticate users with LDAP for an app. By default, this configuration redirects unauthorized users to the login page. I would like to tweak this configuration to achieve two things:

  1. Redirect unauthenticated users trying to access the single page application (at "/") to login. This already works with default behavior.
  2. For api calls ("/api/v1/..."), I want to return a 403 error message instead of redirecting.

How would I do this? I've seen some other questions that have given me hints but I still haven't been able to figure it out.

The top answer on this post seems relevant, but he links to an XML-method of doing this. I want to do it with Java. Spring Security - need 403 error, not redirect

Any help would be much appreciated!

Here is my current setup:

WebSecurityConfig.java

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

    http
        .authorizeRequests()
        .antMatchers("/css/**").permitAll()
        .anyRequest().authenticated();
    http
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/", true)
            .permitAll()
            .and()
        .httpBasic()
            .and()
        .csrf().disable()
        .logout()
            .logoutSuccessUrl("/login");

}

Upvotes: 2

Views: 4985

Answers (1)

Vishrut Dixit
Vishrut Dixit

Reputation: 71

Found a solution that seems to work (so far, least)

@Bean
public AuthenticationEntryPoint delegatingEntryPoint() {
    final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> map = new LinkedHashMap();
    map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint("/login"));
    map.put(new AntPathRequestMatcher("/api_v1/**"), new Http403ForbiddenEntryPoint());

    final DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(map);
    entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));

    return entryPoint;
}

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

    //delegates based on url (api vs root)
    http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint());

    http
        .authorizeRequests()
        .antMatchers("/css/**").permitAll()
        .anyRequest().authenticated();
    http
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/", true)
            .permitAll()
            .and()
        .httpBasic()
            .and()
        .csrf().disable()
        .logout()
            .logoutSuccessUrl("/login");
}

Hopefully this helps someone down the road. I know it took me a long time to find answer. :)

Upvotes: 2

Related Questions