3

I'm trying to implement custom AuthenticationEntryPoint in Spring Boot 2 in my configure method of WebSecurityConfig.

I've seen a lot of examples like this:

@Component
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {

private final Logger log = LoggerFactory.getLogger(Http401UnauthorizedEntryPoint.class);

/**
 * Always returns a 401 error code to the client.
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
        ServletException {

    log.debug("Pre-authenticated entry point called. Rejecting access");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}

But I always obtain a 403 instead of 401.

How can I do this in Spring boot 2?

Leonardo Benitez
  • 31
  • 1
  • 1
  • 5

3 Answers3

5

Have a look at my answer here: https://stackoverflow.com/a/52986942/3437868 and here: https://stackoverflow.com/a/52986779/3437868

In short: As of Spring Boot 2 class Http401AuthenticationEntryPoint has been removed (see Spring Boot Issue 10725).

Instead of Http401AuthenticationEntryPoint use HttpStatusEntryPoint with HttpStatus.UNAUTHORIZED:

http.exceptionHandling()
    .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
Tai Truong
  • 668
  • 1
  • 8
  • 11
1

I'm using Spring boot 1.5,maybe it's not suitable for this case,but i still hope this could help you.

After you created your Http401UnauthorizedEntryPoint bean, you should configure it into Spring Security.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable()
                .csrf().disable()

                // look here,bro
                .exceptionHandling()
                .authenticationEntryPoint(new Http401AuthenticationEntryPoint(""))
        ;
    }

Then the entry point should work.

In fact, Spring has already offered you lots of entry point beans.Just like "Http401AuthenticationEntryPoint" that also can solve this case instant of creating a bean by yourself.

AokoQin
  • 159
  • 4
0

You create a class extends WebSecurityConfigurerAdapter. Then you autowired Http401UnauthorizedEntryPoint class which you implement from AuthenticationEntryPoint. You can refer below:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private Http401UnauthorizedEntryPoint authenticationEntryPoint;

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


    }
}
Dung Phan
  • 681
  • 8
  • 15