Sneijky
Sneijky

Reputation: 11

Spring security baisc authentication only validating first request

I'm using spring basic authentication with a custom authentication provider:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomAuthenticationProvider authProvider;

@Override
protected void configure(
        AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic();
}

And

    @Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    if (customauth()) { // use the credentials
        // and authenticate against the third-party system
        {
            return new UsernamePasswordAuthenticationToken(
                    name, password, new ArrayList<>());
        }
    } else {
        return null;
    }

}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(
            UsernamePasswordAuthenticationToken.class
    );
}

To test this I'm using postman with the following tests:

invalid credentials -> 401 unauthorized

correct credentials -> 200 OK

invalid credentials -> 200 OK

My problem is that the last request should return 401 unauthorized and every following request after a successful login is 200 OK even with a wrong token and without token.

Thanks in advance.

Upvotes: 0

Views: 437

Answers (2)

chubock
chubock

Reputation: 844

When you logged in successfully, Spring Security will create an Authentication object and will put it in SecurityContext in your HTTP session. As far as you have a valid session with a valid Authentication object at the server, Spring Security won't authenticate your request again and will use the Authentication object saved in your session.

Upvotes: 1

dur
dur

Reputation: 16992

This is a Spring Security feature, see SEC-53:

Check the SecurityContextHolder for an authenticated Authentication and reuse it in that case, do not call the authentication manager again.

If you like to reauthenticate, you could

  • use no session at all
  • logout before reauthenticate

In both cases Spring Security will not find an authenticated user saved in the session and will use the new username and password for authentication.

Upvotes: 0

Related Questions