Alan Gaytan
Alan Gaytan

Reputation: 910

How to validate a token from a OAuth server?

I created a Spring Boot application where I have the authorization and resource server, this is my main class:

@SpringBootApplication
@EnableResourceServer
@EnableAuthorizationServer
public class OauthServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(OauthServerApplication.class, args);
    }
}

And this is my application.yml:

security:
  user:
    name: guest
    password: guest123
  oauth2:
    client:
      client-id: trustedclient
      client-secret: trustedclient123
      authorized-grant-types: authorization_code,refresh_token,password
      scope: openid

To generate the access token I only execute this url (POST):

http://trustedclient:trustedclient123@localhost:8080/oauth/token?username=guest&password=guest123&grant_type=password

It returns:

{
  "access_token": "f2e722b7-3807-4a27-9281-5b28b7bd3d0d",
  "token_type": "bearer",
  "refresh_token": "f96d472c-8259-42e2-b939-4963dfeeb086",
  "scope": "openid"
}

Now I need to know how to validate if the token is correct, any help?

Upvotes: 5

Views: 18916

Answers (2)

Jose Martinez
Jose Martinez

Reputation: 11992

To validate the token I typically make a request for the /user using access token in the Authorization header.

In the Spring Oauth server I add the following endpoint.

@GetMapping("/user")
public Principal user(Principal user) {
    return user;
}

And this would be the request sent to it.

GET http://localhost:8443/v1/auth/user
Authorization: Bearer some-access-token

This has the added benefit of returning the user object, which is typically needed. So kill two birds with one stone.

Upvotes: 0

Ortomala Lokni
Ortomala Lokni

Reputation: 62466

You have multiple possibilities, you can:

1) Store the token in a TokenStore and open a secured validate token enpoint on the authorization server for the resource server.

2) If the authorization server and the resource server can share a DataSource, (in your case it's easy because both are in the same application). They can both use a JdbcTokenStore pointing to the same database and the resource server can directly check the validity of a token in this token store. See this tutorial : Spring REST API + OAuth2 + AngularJS

3) You can use signed JWT tokens with JwtTokenStore and JwtAccessTokenConverter. See this tutorial : Using JWT with Spring Security OAuth

Both of these tutorials are based on the following github repository : https://github.com/Baeldung/spring-security-oauth

Upvotes: 9

Related Questions