The easiest way to add Keycloak authentication to an app is oauth2-proxy. oauth2-proxy stands in front of your application like a reverse proxy and it'll handle all the OAuth2 bits for you. oauth2-proxy will then generate the sign-in URL to Keycloak (/realms/{realm-name}/protocol/openid-connect/auth
) with the appropriate parameters to start an OAuth2 sign in process and set it to redirect back to the application page, Keycloak will display sign-in page, then after the user completed their sign in, it'll redirect back to the application, at which point oauth2-proxy will check the JWT token are valid, set a cookie, and then pass along the username, access token, and ID token to the server as HTTP headers to the proxied request.
When using a oauth2-proxy kind of approach, neither your Svelte frontend app or FastAPI app needs to know anything about OIDC/OAuth2, they don't even need access to the client secret, which reduces the chance of your application leaking those secrets. The application may need to be able to decode a JWT token to read Access token and ID token (which contains the auth claims), but if all you need is just a Keycloak validated username/email, then your FastAPI app can just read the HTTP headers with Header()
to get the username. Decoding JWT without signature verification (because we assume that oauth2-proxy already validated the signature) is pretty simple to implement with just standard library, it's basically just a couple string manipulation, base64, and json parsing.
Alternatively, you can implement OAuth2 flow directly in your application. Direct integration may be necessary if the application needs to do things that are more complicated than just basic authentication and authorisation with the JWT tokens or if you want finer control over the auth process. Keycloak supports OAuth2 via OIDC, so you can use any OIDC library like pyoidc or with a Keycloak specific integration like fastapi-keycloak-middleware. Implementing OAuth2 without OIDC is also possible but it will be much more involved. Keycloak, OIDC, and OAuth2 all has a lot of configuration involved to support various different use cases and security requirements, you'll need to look into these configurations in more detail to figure out which suits your requirement.
Implementing all this without using an OIDC and/or OAuth2 libraries is possible, but I wouldn't really recommend them. You'll just end up reading a lot of boring OAuth2 and OIDC specs.