Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Keycloak with Flask REST API Service

I am trying to implement the Keycloak to my Flask Rest Service but it always gives below error.

{"error": "invalid_token", "error_description": "Token required but invalid"}

client_secrets.json

    {
    "web": {
        "issuer": "http://localhost:18080/auth/realms/Dev-Auth",
        "auth_uri": "http://localhost:18080/auth/realms/Dev-Auth/protocol/openid-connect/auth",
        "client_id": "flask_api",
        "client_secret": "0bff8456-9be2-4f82-884e-c7f9bea65bd1",
        "redirect_uris": [
            "http://localhost:5001/*"
        ],
        "userinfo_uri": "http://localhost:18080/auth/realms/Dev-Auth/protocol/openid-connect/userinfo",
        "token_uri": "http://localhost:18080/auth/realms/Dev-Auth/protocol/openid-connect/token",
        "token_introspection_uri": "http://localhost:18080/auth/realms/Dev-Auth/protocol/openid-connect/token/introspect",
        "bearer_only": "true"
    } 
}

run.py

    import json
    import logging

    from flask import Flask, g, jsonify
    from flask_oidc import OpenIDConnect
    import requests

    app = Flask(__name__)

    app.config.update({
        'SECRET_KEY': 'TESTING-ANURAG',
        'TESTING': True,
        'DEBUG': True,
        'OIDC_CLIENT_SECRETS': 'client_secrets.json',
        'OIDC_OPENID_REALM': 'Dev-Auth',
        'OIDC_INTROSPECTION_AUTH_METHOD': 'bearer',
        'OIDC-SCOPES': ['openid']
    })


    oidc = OpenIDConnect(app)

@app.route('/api', methods=['GET'])
@oidc.accept_token(require_token=True, scopes_required=['openid'])
def hello_api():
    """OAuth 2.0 protected API endpoint accessible via AccessToken"""

    return json.dumps({'hello': 'Welcome %s' % g.oidc_token_info['sub']})


if __name__ == '__main__':

enter image description here

Anyone has an idea, if anything is wrong here.

like image 285
Anurag Choudhary Avatar asked Nov 08 '22 05:11

Anurag Choudhary


1 Answers

I had the same issue and I (finally \o/) made it work. Try the following:

'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post'
'OIDC_TOKEN_TYPE_HINT': 'access_token'

Also remove the list of required scopes to avoid any possible error there:

@oidc.accept_token(require_token=True)
like image 50
dafero Avatar answered Nov 14 '22 19:11

dafero