Using one token for client and backend with KeyCloack

Viewed 38

I have a website - React application, as well as an admin panel website, also React application.

One node js application performs the roles of a backend for the site and the admin panel.

I want to use KeyCloack 19 as a single authorization service.

The client part of the admin panel should require authorization in the Moon Clock, the endpoints on the backend related to the admin panel should also be protected through KeyCloack.

I'm trying to figure out if I can use the same token for both the client side of the admin panel and the routes?

I'm also trying to figure out if I can implement this without adding code to my services.

Thanks!

1 Answers

You need to create several clients in Keycloak, one for each application you have.

  • The backend (nodejs) will not be used for login (no redirection to login pages), only as an application receiving tokens. So instead of the default 'confidential' type, you set a 'Bearer-only' type of client. You'll get a client_id to give to this nodejs app, and also a client_secret.
  • For the Angular application, no secret should either be stored on a front app, so you create 'public' types of clients. You'll get a client_id for each app, but not client secrets. And you MUST define the allowed redirect_url domains for theses apps (that's the security).

You'll log in to the SSO provider by reaching the angular public apps. Keycloak will then give you several tokens. An id Token, an access_token, and a refresh token to get a new access_token when the duration as expired.

When making ajax request from the angular applications to the backend you'll have to add this access token on the requests, and the backend will have to check the validity of this access token. Always check the token still has some time validity before sending it to the backend, and get a new one if not.

To make this system more precise you can also add at least one role in each client (like a role 'Access Foo'), and then remove the 'allow full scope' checkbox in each client (in the Scope tab). Then you associate the right application and role (like you need to have the role 'access Nodejs backend' for the backend client). Then, for example using groups, you give the users the right access (like having or not access to the nodejs backend). This way the access token generated by Keycloak, and given to the public angular applications will contain indications on the 'aud' key (audience). If you have access to the nodejs backend you'll find the nodejs backend client_id in the aud key (it's a list), else not. This way you can even manage several backends and now, from the front application, if you can use the access token to reach some or all of the backends. The backend should also check that the aud key of the token contains his client_id.

Related