CustomJwtAuthenticationToken.java

package com.tdmconsult.ete.configuration;

import com.google.common.collect.ImmutableList;
import java.io.Serial;
import java.util.Collection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

public class CustomJwtAuthenticationToken extends JwtAuthenticationToken {

    @Serial
    private static final long serialVersionUID = 1L;

    public record CustomUserPrincipal(
            String id,                // Der "sub" Claim aus Keycloak
            String username,          // "preferred_username"
            String email,             // "email"
            String firstName,         // "given_name"
            String lastName,           // "family_name"
            ImmutableList<GrantedAuthority> authorities) {

        public boolean hasAuthority(final String authority) {
            return authorities.stream().anyMatch(a -> StringUtils.equals(a.getAuthority(), authority));
        }
    }

    private final transient CustomUserPrincipal customUserPrincipal;

    public CustomJwtAuthenticationToken(
            final Jwt jwt,
            final Collection<GrantedAuthority> authorities,
            final CustomUserPrincipal principal) {
        super(jwt, authorities);
        this.customUserPrincipal = principal;
    }

    // supports @AuthenticationPrincipal
    @Override
    public Object getPrincipal() {
        return this.customUserPrincipal;
    }
}