DEV Community

JL
JL

Posted on

OAuth 2.0 - Auth Server: Keycloak

Keycloak is Open Source Identity and Access Management. It supports OpenID Connect and OAuth2 flows.

To run it
on Windows:
$ bin\kc.bat start-dev

After the server boots, open http://localhost:8080 in your web browser. The welcome page will indicate that the server is running.

To set up
Realm
First time use, you will need to create a new "Realm" (meaning a domain) for client, other than the "Master Realm".

Image description

User
If you do not connect to external for user DB, you can create some for your own

Image description

Client (app)

The client id (mine: client-sandbox) put in, will be used in the auth flow.

Image description

Image description

Don't forget to set a valid callback URL
http://localhost:8083/callback
Image description

Now here is the pair of client credential for the client app to use to do Auth flow

Image description

Using the auth server

1. Authorization Code Grant
Now the client is fully set up. Use postman or manually compose the URL for auth code request:

http://localhost:8080/realms/idprovidersanbox/protocol/openid-connect/auth?client_id=client-sandbox&response_type=code&scope=openid%20profile&redirect_uri=http://localhost:8083/callback&state=randomstatecodeblah

Image description

You will act as a client app user and try to log in:

Image description

The callback URL will be composed with the response from auth server:

http://localhost:8083/callback?state=randomstatecodeblah&session_state=7b4d2de4-d794-47bc-90cc-de9b5052031a&code=55365073-fba5-46ca-8482-8743081da0d0.7b4d2de4-d794-47bc-90cc-de9b5052031a.8c9478a7-6620-4ae8-a913-0033a8f87e55

I will use postman again to visualise the parameters:

Image description

2. Exchange for Access Token
Use postman to compose the URL to get access token, with the code you have obtained from previous auth code grant request:

http://localhost:8080/realms/idprovidersanbox/protocol/openid-connect/token

(note: do not use JSON format in the POST reuqest - keycloak does not support it. Use x-www-form-urlencoded)
grant_type:authorization_code
client_id:client-sandbox
client_secret:5aPfe4ODLDw2MuedkO5FRFkjbk1yERG0
code:55365073-fba5-46ca-8482-8743081da0d0.7b4d2de4-d794-47bc-90cc-de9b5052031a.8c9478a7-6620-4ae8-a913-0033a8f87e55
redirect_uri:http://localhost:8083/callback
scope:openid profile

Image description

Appendix

Note that in the the scope we specified in the request is "profile". The list of scopes that this token is allowed to access, can be pre-defined:

Image description

Default: means the scope will be granted for the token by default
Optional: means the scope will be granted for the token if requested

In addition, KeyCloak supports using external services for user DB. It has a Service Provider Interface standard:

Image description

, and all vendors need to do is to implement as jar to deploy to KeyCloak.

Image description

Top comments (0)