ubeac / ubeac-api

Source of uBeac .NET Core packages
3 stars 2 forks source link

Customizable JWT Claims #166

Open ilhesam opened 1 year ago

ilhesam commented 1 year ago

Currently, The JWT claims are generating in JwtTokenService and these are not customizable for the end-developers. We should solve this issue with the Decorator pattern. So, we will have an interface for the JWT claim decorators and we will implement a manager to handle decoration:

public interface IUserJwtClaimsDecorator<TUser>
{
    IEnumerable<Claim> GetClaims(TUser user);
}

public class UserJwtClaimsManager<TUser>
{
    protected readonly IEnumerable<IUserJwtClaimsDecorator<TUser>> Decorators;

    public UserJwtClaimsManager(IEnumerable<IUserJwtClaimsDecorator<TUser>> decorators)
    {
        Decorators = decorators;
    }

    public IEnumerable<Claim> GetClaims()
    {
        var result = new List<Claim>();

        foreach (var decorator in Decorators)
        {
            var claims = decorator.GetClaims(user);

            result.AddRange(claims);
        }

        return result;
    }
}

Finally, we should implement a default decorator and we will use UserJwtClaimsManager in JwtTokenService

As a developer, I can implement IUserJwtClaimsDecorator and add my JWT claims.