Bearer-only authentication with Keycloak on Flask app with React frontend

by fspasovski   Last Updated July 13, 2019 01:26 AM

I am trying to develop a React front-end application that will work with a Flask backend and use Keycloak for authentication. The idea is that the backend application should only validate the token and not redirect any unauthenticated requests, so it will work in a bearer-only mode.

client_secrets.json:

{
  "web": {
    "auth_uri": "https://login.local/auth/realms/master/protocol/openid-connect/auth",
    "client_id": "myapp",
    "issuer": "https://login.local/auth/realms/master",
    "client_secret": "secret_from_keycloak",
    "redirect_uris": [
      "http://192.168.117.2:5010/*"
    ],
    "userinfo_uri": "https://login.local/auth/realms/master/protocol/openid-connect/userinfo",
    "token_uri": "https://login.local/auth/realms/master/protocol/openid-connect/token",
    "token_introspection_uri": "https://login.local/auth/realms/master/protocol/openid-connect/token/introspect",
    "bearer_only": "true"
  }
}

app.py:

app.config.update({
    'SECRET_KEY': 'my_secret',
    'TESTING': True,
    'DEBUG': True,
    'OIDC_CLIENT_SECRETS': 'client_secrets.json',
    'OIDC_ID_TOKEN_COOKIE_SECURE': False,
    'OIDC_REQUIRE_VERIFIED_EMAIL': False,
    'OIDC_USER_INFO_ENABLED': True,
    'OIDC_VALID_ISSUERS': ['https://login.local/auth/realms/master'],
    'OIDC_OPENID_REALM': 'http://192.168.117.2:5010/oidc_callback',
    'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post',
    'OIDC_TOKEN_TYPE_HINT': 'access_token',
})

oidc = OpenIDConnect(app)

React configuration:

        const keycloak = Keycloak({
            "clientId": "myapp",
            "realm": "master",
            "url": "https://login.local/auth",
            "credentials": {
                "secret": "secret_from_keycloak"
            },
        });

        keycloak.init({onLoad: 'login-required'}).success(authenticated => {
            this.setState({keycloak: keycloak, authenticated: authenticated}
                , () => {
                    this.fetchData();
                })
        });

With the following configuration when the user accesses the React application, it is redirected to the Keycloak login page, but after that Flask also tries to redirect to the login page yet again, resulting in an error.



Answers 1


This is accomplishing what you want. However, it introduces another step in the middle which is an api gateway (Kong). Check out the two parts and you will be able to create a client that interacts with your api secured by Keycloak.

Secure apis with Kong and Keycloak part 2

Felipe Gusmao
Felipe Gusmao
July 13, 2019 01:24 AM

Related Questions





How to start keycloak 2.0 on 8080 port?

Updated November 28, 2017 04:26 AM