How to get access token after login?

Hi

this may be a very simple question but I’m a little confused.

I develop a small website (run in localhost)
I have a Login button that redirects me to the keycloak login page in the following URL:
http://localhost:8080/auth/realms/local/protocol/openid-connect/auth?client_id=WebClient&response_mode=fragment&response_type=code&login=true&redirect_uri=https://localhost:5001/

Now, the user inserts its credentials and this works well and I get redirected back to my site as expected

I also created a client in keycloak that has accessType set to private and direct access grant and service accounts both enabled (found it in some article that i can’t find right now)

What I don’t understand is how to get the access token back from keycloak after the user successfully login?
does keycloak know how to return this parameter back to me (when it redirects to my website) OR do I need to send another request to keylock with the client id and client secret ?

thanks in advance

You need to exchange the code you get from the login with clientid and secrer from the login for a token. Search for “code flow oidc”.

Be careful what you are doing in relation to security. For most development languages there are libraries that take care of the oidc implementation

@HenkN thanks for the reply.

unfortunately, I couldn’t find a good .Net library to do this.

Why do we need to exchange the code we got from the login flow?
can’t I just send another request to keylock with the client id and secret?

The code exchange flow was designed for security reasons.

A good source for understanding what OpenID Connect / OAuth does:

For ASP.NET (Core 3.1, 5, 6) based clients (web applications or REST APIs) you don’t need any third party libraries, .NET ships with everything you need:
Securing .NET Microservices and Web Applications | Microsoft Docs

Even for standalone .NET applications there’s no need for third party libraries, but this one simplifies it:

2 Likes