Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow custom extra fields for KeycloakToken #9

Merged
merged 3 commits into from
Feb 2, 2024

Conversation

fMeow
Copy link
Contributor

@fMeow fMeow commented Feb 1, 2024

The should fix #7 and furthurmore provides ability to define custom jwt scopes/fields.

The previous version hard coded first_name, last_name, email and etc into KeycloakToken. But these tokens can actually be turned off, especially when configured with external identity services.
image

This PR add a generic parameter named Extra and passes it all the way through into KeycloakToken. Also, ProfileAndEmail is provided as the default Extra generic type, to meet the needs of most keycloak user that sticks with default usage (username/email/password authentication and never border to turned off profile or email scope).

I bump the version in Cargo.toml to 0.5.0, since this commit introduces some breaking API changes. There is no more token.full_name but token.extra.profile.preferred_username when Extra is set to ProfileAndEmail, which is the default generic type.

Here is an example to define and use custom jwt extra scopes:

// my tailored jwt scopes/fileds
#[derive(Deserialize, Clone)]
struct MyExtra {
    pub email: String,
    pub preferred_username: String,
    pub foo: String
}

pub async fn protected(Extension(token): Extension<KeycloakToken<String, MyExtra>>) -> Response {
    (StatusCode::OK,format!("Hello {}", token.extra.foo)).into_response()
}

let router = Router::new().route("/protected", get(protected)).layer(
        KeycloakAuthLayer::<String, MyExtra>::builder()
            .instance(instance)
            .passthrough_mode(PassthroughMode::Block)
            .persist_raw_claims(false)
            .expected_audiences(vec![])
            .required_roles(vec![])
            .build(),
);

@fMeow fMeow changed the title feat: allow custom extra field for KeycloakToken feat: allow custom extra fields for KeycloakToken Feb 1, 2024
@lpotthast
Copy link
Owner

Thanks for all the changes! Will look over them this afternoon.

@lpotthast
Copy link
Owner

Looks good!

@lpotthast lpotthast merged commit d696eac into lpotthast:main Feb 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature request] Support for service accounts
2 participants