Flask OIDC with Keycloak - Login isnt registered?

51 Views Asked by At

I have a site (currently local) from which I am trying to access the Keycloak service using Flask OIDC. When running the code below im am correctly redirected to the Keycloak Login page and can login. However, after being redirected back to the site, my login is not recognized. Adding @oidc.require_login to a route simply puts me into an infinite loop between my site and keycloak(which does recognize my login and does not have me login again). Using oidc.user_loggedin will also not work and tell me that I'm not authenticated.

from flask import Flask
from flask import render_template
import logging
from flask import url_for
from flask import redirect
from flask import request
from flask import jsonify
from flask import send_file
import os
import json
import requests
from flask_oidc import OpenIDConnect
import psycopg2
from flask import session

app = Flask(__name__)

app.config.update({
    'SECRET_KEY': 'VerySecret',
    'TESTING': True,
    'DEBUG': True,
    'OIDC_CLIENT_SECRETS': 'client_secrets.json',
    'OIDC_COOKIE_SECURE': False,
    'OIDC_USER_INFO_ENABLED': True,
    'OIDC_SCOPES': ['openid', 'email', 'profile']
})

oidc = OpenIDConnect(app)

@app.route('/loging')
def loging():
    return redirect(url_for('oidc_auth.login'))

@app.route('/test')
@oidc.require_login
def sitetest():
    return 'Hallo'


@app.route('/')
def start():
    if(oidc.user_loggedin==True):
        return render_template("login.html")
    else:
        nice = 'You are not logged in! ' + str(oidc.user_loggedin)
        return nice

Occasionally, I will also receive the error "Unauthorized mismatching_state: CSRF Warning! State not equal in request and response." The error message points out that the "session"-Cookie does not have a valid "SameSite"-Attribute, but I have not found any way to change or add it to ow what the exact problem is...

My client_secrets.json file reads:

{
    "web": {
        "issuer": "http://127.0.0.1:8080/realms/elrealm",
        "auth_uri": "http://127.0.0.1:8080/realms/elrealm/protocol/openid-connect/auth",
        "client_id": "elre",
        "client_secret": "NSIsn********************",
        "redirect_uris": ["http://127.0.0.1:5000/*"],
        "userinfo_uri": "http://127.0.0.1:8080/realms/elrealm/protocol/openid-connect/userinfo",
        "token_uri": "http://127.0.0.1:8080/realms/elrealm/protocol/openid-connect/token",
        "token_introspection_uri": "http://127.0.0.1:8080/realms/elrealm/protocol/openid-connect/token/introspect"
    }
}
0

There are 0 best solutions below