Oauth2 flow to issue tokens for registered users automatically

Viewed 31

I have an endpoint, which I want to protect using Oauth2 and spring boot. The users register on the website and after the successful payment, a token with specific expiry should be issued automatically and delivered to the user. The User can revoke the token in their panel and get a new token manually.

I don't want to use password grant type as it requires sending the username and password for each request. the authorization code grant type, requires the user to enter their credentials which doesn't fit my need for automatic generation of tokens after successful payment. I'm not sure if using client credentials grant type is a good idea for my need. I could use a new client for each new user. But this seems not right to me. But correct me if I'm wrong. any idea which oauth flow I should use?

1 Answers

You want to authenticate end-users with OAuth2? Use authorization-code (with PKCE).

In your statements, there seem to be a confusion between authorization-server (issues tokens) and resource-server (subscriptions are resources too in my opinion). Have a look at this article for OAuth2 refresher and spring resource-server security conf.

Also, it seems to be a one-to-one relation between access-token and payed subscription. This is probably a mistake: access-token should be short lived (like a few minutes). Are your subscriptions that short?

I see two options here:

  • have your authorization-server add a private claim with subscription status to JWT access-token (or introspection details) and check this claim value in spring-security expressions (@PreAuthorize("..."))
  • configure a custom authentication converter in spring security which calls a @Repository to read subscription status in database, based on identity contained in access-token

First solution is way more efficient (persisted subscription status is retrieved from DB only when a new access-token is issued) but requires your authorization-server to be flexible enough for you to add private claim with values from a web-service or a DB. I have a tutorial to do so in Keycloak. read it AFTER the article above.

Related