How to get access token after login?


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:

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: