ch4mpy / spring-addons

Ease spring OAuth2 resource-servers configuration and testing
Apache License 2.0
552 stars 89 forks source link

[No bug] Migrating from MockKeycloakAuth #111

Closed cvetan closed 1 year ago

cvetan commented 1 year ago

I am starting new project with Spring Boot 3, and I've implemented oauth2 resource server, now I in the process of mocking user for tests. Before adapters were deprecated I've used @WithMockKeycloakAuth, but now that is deprecated as well, I concluded @WithMockJwtAuth is logical successor, however I find some dificulties and stuff missing from old version, specifically I am not sure how to mock resource access(client roles).

old configuration

@WithMockKeycloakAuth(
        authorities = {"ROLE_ACCOUNTANT"},
        id = @IdTokenClaims(sub = "0fb8fe66-d834-45af-aab1-ea94e25a87c5"),
        oidc = @OidcStandardClaims(
                givenName = "John",
                familyName = "Doe",
                email = "accountant@example.com",
                emailVerified = true,
                preferredUsername = "accountant"),
        accessToken = @KeycloakAccessToken(
                resourceAccess = @KeycloakResourceAccess(
                        resourceId = "example-client",
                        access = @KeycloakAccess(roles = {"ACCOUNTANT"})
                )
        )
)

new configuration (not complete)

@WithMockJwtAuth(
        authorities = {"ROLE_USER"},
        claims = @OpenIdClaims(
                sub = "cffc69af-2864-4287-860a-c07850dcf9fd",
                givenName = "John",
                familyName = "Doe",
                email = "john.doe@example.com",
                emailVerified = true,
                preferredUsername = "john.doe"
        )
)

I am sorry I am starting this discussion here, but I do not find any good place for it, I think your library deserves at least slack channel, because it is really good :) . Thanks in advance.

ch4mpy commented 1 year ago

It is important to understand that, with test annotations, you don't mock a token later decoded, validated and converted into an Authentication instance. What you define are properties of this Authentication itself.

In the case of @WithMockJwtAuth, the attributes you define are used to instantiate a JwtAuthenticationToken, constructor of which expects already converted authorities (with case and prefix transformation already applied).

So, unless you use realm_access or resource_access claims for something else than building Spring authorities, just provide the already mapped authorities (with case transformation and prefix applied) into the authorities property of the annotation.

If you need this Keycloak private claims for something else than authorities, then just use otherClaims as illustrated for instance there