Securing a Flask web app and restful api

Dear all,

I have configured Keycloak for user authentication on my web application which uses a Flask server (and gunicorn for production). Accessing the web app through the browser works normally, however I have the following issue.

With the same flask server, I have set up some restful APIs that I also want to secure. These APIs are supposed to be accessed by machines, and therefore I need a way to provide credentials or a token of some sort to the APIs, when I want to access them.

I am looking for a simple solution to this problem, not necessarily the best possible practice. For example, I saw that I could provide Authorization credentials in my HTTP requests to the API, but that didn’t work; the API just returned a HTML document about redirection.

I would be extremely grateful if someone could support me with this. Thank you!

You’re on the right track. You can create a “confidential” or “bearer-only” Client in Keycloak for your Flask API server. Docs on setting that up are here Server Administration Guide which is probably the same place you did it for your web application’s “public” Client. Then you can use the access token you receive in the Authorization: Bearer {token} header you send with an HTTP request to your API server. A gist that has a sample Flask API application that is protected with OIDC is here Simple python example using flask, flask_oidc and keycloak · GitHub and it shows you how to configure it using the information from the Client you set up, and how to protect your endpoints.