How to get token after login into keycloak with python-keycloak

Viewed 6450

I am using flask to build app and keycloak for authorization.

from flask import Flask, session, request
from keycloak import KeycloakOpenID

app = Flask(__name__)
app.secret_key = 's_k'


keycloak_open_id =  KeycloakOpenID(server_url="http://localhost:8080/auth/",
                        client_id="Centrum",
                        realm_name="myrealm",
                        client_secret_key="c_k")

def login_required(func):
    @wraps(func)
    def decorated(*args, **kwargs):

    // validate token

        return func('2', *args, **kwargs)
    return decorated


@app.route('/login')
def login():
    url = keycloak_open_id.auth_url('http://localhost:5555/auth')

    # how to get a token and assign it to session['token']?

    return redirect(url, code=302)

@app.route('/home')
@login_required
def home():
    return 'Base URL!'

When I am logged in and can go to /home, but without token the application always needs to go through keycloak's method. Is there any other posibility to get token other than making own login form and pass login and password into keycloak_open_id.token(login, password) method?

1 Answers

Seems that you're looking for grant_type=password oauth flow, you can check keycloak's doc how to do it.

Basically:

curl \
  -d "client_id=myclient" \
  -d "client_secret=40cc097b-2a57-4c17-b36a-8fdf3fc2d578" \
  -d "username=user" \
  -d "password=password" \
  -d "grant_type=password" \
  "http://localhost:8080/auth/realms/master/protocol/openid-connect/token"
Related