lpotthast / axum-keycloak-auth

Protect axum routes with a JWT emitted by Keycloak.
https://crates.io/crates/axum-keycloak-auth
Apache License 2.0
34 stars 13 forks source link

Allow to configure where the auth token will be passed #23

Closed Tockra closed 3 months ago

Tockra commented 3 months ago

Description

When using the WebSocket implementation in JavaScript, it can be challenging to add an Authorization header. For more context, see solution 3 by kaqqao on Stack Overflow.

This pull request introduces a way to configure the middleware, allowing you to specify where the JWT token should be expected. The token can be placed in the HEADER (default), QUERY PARAM, or BOTH (this solution first checks the header and if there is no token, it then checks the query param).

Changes

This enhancement provides flexibility in managing WebSocket authentication, making it easier to adapt to different client implementations and security requirements.

lpotthast commented 3 months ago

Thanks for the PR! Making the library more agnostic to the source of the token is a really good thing. I think I will merge this as is, and do a few changes to it.

I would like for the users to be able to present a configurable list of TokenExtractor implementations. The enum-approach is a bit limited. For example, having the Both variant implies that there will be no easy way of adding an additional source to it. Even when naming it ´HeaderOrQuery´, we would still enforce a specific extraction order and run into permutation problems.

One question: The serde_querystring lib allows to parse the query string in two ways. You chose the DuplicateQS approach, retaining duplicate keys. Would you think its desirable to have that? Should the lib test all tokens until it finds a valid one if multiple tokens are provided in the query params? I mean, duplicate keys are generally allowed and a user could expect this to work. Although I think it is unlikely that this will ever be used.. I think we can support it.

lpotthast commented 3 months ago

@Tockra Hey Tim, main now has theTokenExtractor trait and two implementations for it: AuthHeaderTokenExtractor and QueryParamTokenExtractor. It was actually possible to save some clones when changing the implementation. Even on the header-extraction side. A few pieces of code were moved around. Hope merging into your project-branch is not a problem. The crate doc shows how configuration in the KeycloakAuthLayer can be done. There is certainly room for improvement and additional features here: Allowing all extractors to retrieve a token and retry validation if the previous one failed to be verified, allowing extractors to extract multiple keys, ... But thats for another day.