从Web API添加令牌中的声明 [英] Add claims in token from web api

查看:83
本文介绍了从Web API添加令牌中的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IdentityServer4,Identity和API进行项目.

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

API受IDS4保护.

The API is protected with IDS4.

API和IDS4在同一个项目上,因此我的解决方案中有3个项目:-包含IdentityServer和AP​​I的MVC Web项目-使用MongoDB作为数据库提供程序的Identity的实现-一个模拟客户端的控制台应用程序

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

我的客户端通过IDS4进行身份验证,获取access_token,然后使用令牌调用api.这部分工作正常.

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

现在我被问到在我的api中调用特定操作时,我会向令牌添加一些声明.

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

我已经在Google上进行搜索,但找不到有关该操作的任何解决方案,而且我不确定这是个好主意.API是否可以通过添加一些声明然后发送回令牌来修改接收到的访问令牌?

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?

一种替代方法是发送另一个令牌作为响应,但是我找不到用RS512签名令牌的方法.

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

预先感谢

推荐答案

您可以使用 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>();
}

这篇关于从Web API添加令牌中的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆