not able to protect the python flask rest api service using keycloak

1.1k Views Asked by At

I have keycloak server running in docker (192.168.99.100:8080) and python flask-oidc flask application running locally ( localhost:5000) i am not able to access the protected Rest Api even after getting the access_token. has anyone tried this code. if so please help me regarding this. thank you

this is my keycloak client using docker jboss/keycloak image

this is my newuser under the new realm

below is my flask-application

app.py

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

secret_key = os.urandom(24).hex()  
print(secret_key)  
logging.basicConfig(level=logging.DEBUG)  

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"]="client_secrets.json"  
app.config["OIDC_COOKIE_SECURE"]=False  
app.config["OIDC_SCOPES"]=["openid","email","profile"]
app.config["SECRET_KEY"]=secret_key  
app.config["TESTING"]=True  
app.config["DEBUG"] = True  
app.config["OIDC_ID_TOKEN_COOKIE_SECURE"]=False  
app.config["OIDC_REQUIRED_VERIFIED_EMAIL"]=False  
app.config["OIDC_INTROSPECTION_AUTH_METHOD"]='client_secret_post'  
app.config["OIDC_USER_INFO_ENABLED"]=True  

oidc = OpenIDConnect(app)  
@app.route('/')
def hello_world():
if oidc.user_loggedin:
    return ('Hello, %s, <a href="/private">See private</a> '
            '<a href="/logout">Log out</a>') % \
           oidc.user_getfield('preferred_username')
else:
    return 'Welcome anonymous, <a href="/private">Log in</a>'

client_secrets.json

{
"web": {
    "issuer": "http://192.168.99.100:8080/auth/realms/kariga",
    "auth_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/auth",
    "client_id": "flask-app",
    "client_secret": "eb11741d-3cb5-4457-8ff5-0202c6d6b250",
    "redirect_uris": [
        "http://localhost:5000/"
    ],
    "userinfo_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/userinfo", 
    "token_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/token",
    "token_introspection_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/token/introspect"
}
}

when i launch the flask-app in web browser
i click on the Log in link
next it prompts for the user details (user created under my new realm)
it takes a couple of seconds then it redirects me to an error page
http://localhost:5000/oidc_callback?state=eyJjc3JmX3Rva2VuIjogIkZZbEpqb3ZHblZoUkhEbmJsdXhEVW
that says

httplib2.socks.HTTPError

httplib2.socks.HTTPError: (504, b'Gateway Timeout')

and also it is redirecting to /oidc_callback which is not mentioned anywhere
any help would be appreciated

1

There are 1 best solutions below

0
On BEST ANSWER

the problem is occuring because keycloak server which is running in docker(192.168.99.100)
is not able to hit the flask application server which is running locally(localhost)

better to run both as services in docker by creating a docker-compose file