3
votes

I have a Spring OAuth 2 server based on Spring Boot 1.5 (Spring Security v4) which generates customized tokens and a few resource servers who communicate with this authorization server, making use of /oauth/check_token endpoint by configuration of RemoteTokenServices. All the logic related to storing/retrieving tokens on Authorization server side is done with JdbcTokenStore.

I am building a new Spring Boot 2 application which is build with Spring webflux module and trying to implement client_credentials flow with existing Authorization Server using Spring Security 5.1.1. I found that support for resource servers was added in 5.1.0.RC1 (https://spring.io/blog/2018/08/21/spring-security-5-1-0-rc1-released#oauth2-resource-servers) and updated in 5.1.0.RC2 (https://spring.io/blog/2018/09/10/spring-security-5-1-0-rc2-released#oauth2-resource-server) but looks like it's only possible to configure it with JWT support.

I might be messing up with concepts here but looking for more info and a way to configure all these components together.

1

1 Answers

7
votes

I'm in same situation as you.I solve that problem in next way, maybe it can help you:

spring-boot-starter-parent.version: 2.1.1

spring-cloud-dependencies.version: Greenwich.R1

Security configuration:

@EnableWebFluxSecurity
public class SecurityConfig {

    @Autowired
    private ReactiveAuthenticationManager manager; //custom implementation

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http
                .authorizeExchange()
                .pathMatchers("/role").hasRole("ADMIN")
                .pathMatchers("/test").access(new HasScope("server")) //custom implementation
                .anyExchange().authenticated()
                .and()
                .httpBasic().disable()
                .oauth2ResourceServer()
                    .jwt()
                    .authenticationManager(manager)
                .and().and()
                .build();
    }
}

ReactiveAuthorizationManager (HasScope) implementation: Helper which allow search for scopes in authentication object

public class HasScope implements ReactiveAuthorizationManager<AuthorizationContext> {

    public HasScope(String...scopes) {
        this.scopes = Arrays.asList(scopes);
    }

    private final Collection<String> scopes;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext object) {
        return authentication
                .flatMap(it -> {
                    OAuth2Authentication auth = (OAuth2Authentication) it;
                    Set<String> requestScopes = auth.getOAuth2Request().getScope();
                    boolean allow = requestScopes.containsAll(scopes);
                    return Mono.just(new AuthorizationDecision(allow));
                });
    }
}

ReactiveAuthenticationManager implementation:

That is the main component in configuration which create OAuth2Authentication. There is a problem with response for wrong access_token, it returns only status code without body response.

@Component
public class ReactiveAuthenticationManagerImpl implements ReactiveAuthenticationManager {

    private final ResourceServerProperties sso;
    private final WebClient.Builder webClient;
    private final ObjectMapper objectMapper;
    private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor();

    public ReactiveAuthenticationManagerImpl(ResourceServerProperties sso,
            @Qualifier("loadBalancedWebClient") WebClient.Builder webClient, ObjectMapper objectMapper) {
        this.sso = sso;
        this.webClient = webClient;
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        return Mono.just(authentication)
                .cast(BearerTokenAuthenticationToken.class)
                .flatMap(it -> getMap(it.getToken()))
                .flatMap(result -> Mono.just(extractAuthentication(result)));
    }

    private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
        Object principal = getPrincipal(map);
        OAuth2Request request = getRequest(map);
        List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        token.setDetails(map);
        return new OAuth2Authentication(request, token);
    }

    private Object getPrincipal(Map<String, Object> map) {
        if (map.containsKey("principal")) {
            try {
                //that is the case for user authentication
                return objectMapper.convertValue(map.get("principal"), UserPrincipal.class);
            } catch (IllegalArgumentException ex) {
                //that is the case for client authentication
                return objectMapper.convertValue(map.get("principal"), String.class);
            }
        }
        return null;
    }

    @SuppressWarnings({"unchecked"})
    private OAuth2Request getRequest(Map<String, Object> map) {
        Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");

        String clientId = (String) request.get("clientId");
        Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ?
                (Collection<String>) request.get("scope") : Collections.emptySet());

        return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope),
                null, null, null, null);
    }

    private Mono<Map<String, Object>> getMap(String accessToken) {
        String uri = sso.getUserInfoUri();
        return webClient.build().get()
                .uri(uri)
                .accept(MediaType.APPLICATION_JSON)
                .header("Authorization", "Bearer " + accessToken)
                .exchange()
                .flatMap(it -> it.bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {}))
                .onErrorMap(InvalidTokenException.class, mapper -> new InvalidTokenException("Invalid token: " + accessToken));
    }