Add claims in token from web api

风格不统一 提交于 2020-12-30 03:46:06

问题


I'm working on a project using IdentityServer4 and Identity and an API.

The API is protected with IDS4.

The API and IDS4 are on the same project, so I have 3 projects in my solutions: - A MVC web project that contains the IdentityServer and the API - An implementation of Identity that use MongoDB as database provider - A console application that simulate the client

My client authenticate with IDS4, get the access_token and then call the api with the token. This part is working fine.

Now i'm asked that when calling a specific action in my api I add some claims to the token.

I've searched on google but I can't found any solutions on how to do that, and I'm not sure it's a good idea. Can the API modifiy the received access token by adding some claims and then send back the token?

An alternative was to send another token as response but I can't find a way to sign my token with RS512.

Thanks in advance


回答1:


You can add extra claims using IProfileService

public class ProfileService : IProfileService
{
    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        string subject = context.Subject.Claims.ToList().Find(s => s.Type == "sub").Value;
        try
        {
            // Get Claims From Database, And Use Subject To Find The Related Claims, As A Subject Is An Unique Identity Of User
            //List<string> claimStringList = ......
            if (claimStringList == null)
            {
                return Task.FromResult(0);
            }
            else {
                List<Claim> claimList = new List<Claim>();
                for (int i = 0; i < claimStringList.Count; i++)
                {
                    claimList.Add(new Claim("role", claimStringList[i]));
                }
                context.IssuedClaims = claimList.Where(x => context.RequestedClaimTypes.Contains(x.Type));
                return Task.FromResult(0);
            }
        }
        catch
        {
            return Task.FromResult(0);
        }
    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        return Task.FromResult(0);
    }
}

Register service in the "Startup" file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()..Services.AddTransient<IProfileService, ProfileService>();
}


来源:https://stackoverflow.com/questions/53537592/add-claims-in-token-from-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!