Authenticating users using python-keycloak

Is there an example or does someone have an outline on how to authenticate a user using python-keycloak? How are tokens involved? In other words how to “log-in” a user?

As I understand personally, In Keycloak you always authenticate on a SSO client, even the admin console has its own client to authenticate (admin-console client in realm master)

In any SDK it will be the same way to anthenticate like using curl or a web browser. Concerning the python SDK, I guess you are using maybe marcospereirampj/python-keycloak. In their example in the README.md, here is how to authenticate your users

Usually, you will need to initialize an object that with all the configuration:

# Configure client
keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
                                 client_id="example_client",
                                 realm_name="example_realm",
                                 client_secret_key="secret")

You will need to create your own client (OpenID Connect) with a client’s secret in the realm of your choice or use an existing one.

Then, you can request a JWT Token that contains all the authorizations of your user from the client

# Get Access Token With Code
access_token = keycloak_openid.token(
    grant_type='authorization_code',
    code='the_code_you_get_from_auth_url_callback',
    redirect_uri="your_call_back_url")


# Get Token
token = keycloak_openid.token("user", "password")
token = keycloak_openid.token("user", "password", totp="012345")

You can perform a simple authentication via username and password for example to start. Once your user is authenticated, he or she is redirected to the redirect_uri.

To troubleshoot you can use curl to request a token for example. Just remember thtat the JWT token you get is the representation of your authenticated user. Inside you can add other information using mappers like group, role, email, …

I hope my response help you, and if I said something wrong, feel free to correct me

1 Like

So “logging in” is simply a matter of obtaining a JWT token using the correct user and password?

Exactly, By default you can perform username and password authentication but you can create a custom authentication flow

1 Like