Search code examples
javaspring-securityoauth-2.0spring-oauth2

Public API access with OAuth 2.0


As a Resource Owner, I am able to get a response from a Protected Resource Server (here: Service) using the Resource Owner Password Credentials grant type (aka password) via org.springframework.security.oauth2.client.OAuth2RestTemplate.

 Resource Owner
 (e.g. a Users with a browser)
   +   ^
(1)|   |(6)
   |   |
   |   |    (2)
   v   |    credentials
 +-+---+--+         +--------+
 |        +--------->        |
 | Client |         | OAuth2 |
 |        <---------+ Server |
 +-+---^--+ (3)     |        |
   |   |    token   +--------+
(4)|   |(5)
   |   |
 +-v---+---+
 |         |
 | Service |
 |         |
 +---------+

However, this Protected Resource Server also provides a public API that I want to access, even without a user login. I think this is a common use case, but seems to be not provided by the OAuth2RestTemplate since the AccessTokenProvicerChain checks for an AnonymousAuthenticationToken:

if (auth instanceof AnonymousAuthenticationToken) {
    if (!resource.isClientOnly()) {
        throw new InsufficientAuthenticationException(
                "Authentication is required to obtain an access token (anonymous not allowed)");
    }
}

Of course, I can exceptionally use a regular RestTemplate to access the public API, but is this the usual way to do it?


Solution

  • We decided for another approach. Anyway, you can create a JWT for an "anonymous" session by disabling the anonymous Spring Security Session.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable();
    }
    

    Then, authis not an instance of AnonymousAuthenticationToken anymore, but null.