devtiwa devtiwa - 1 month ago 9
reST (reStructuredText) Question

Authenticate a Springboot Application against another application using Basic Auth

How can I authenticate a Spring Boot application against a third party application?

According to the examples for implementing basic auth using spring security, the user and password are validated but I want to validate against a 200 response from another service.
Here's how the user can be authenticated:
User sends credentials with Basic Auth to access my SpringBoot REST service -> The SpringBoot service makes a GET request with basic auth header to a third party service -> receives a 200 OK and authenticate the end user to access all URLs on my REST service.

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthenticationEntryPoint authEntryPoint;

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

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}

}

Answer Source

You have to implement your own AuthenticationProvider. For example:

public class ThirdPartyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication auth) thows AuthenticationException {
        // call third party site with auth.getPrincipal() and auth.getCredentials() (those are username and password)
        // Throw AuthenticationException if response is not 200
        return new UsernamePasswordAuthenticationToken(...);
    }

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

After that you can override the configure(AuthenticationManagerBuilder) method in your SpringSecurityConfig:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // authProvider = instance of ThirdPartyAuthenticationProvider
    auth.authenticationProvider(authProvider); 
}