如何添加自定义声明以访问IdentityServer4中的令牌? [英] How to add custom claims to access token in IdentityServer4?

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

问题描述

我正在使用 IdentityServer4 .

我想添加其他自定义声明来访问令牌,但是我无法执行此操作.我已经修改了Quickstart5,并按照Coemgen 下面的建议通过ProfileService添加了ASP.NET Identity Core和自定义声明.

I want to add other custom claims to access token but I'm unable to do this. I have modified Quickstart5 and added ASP.NET Identity Core and the custom claims via ProfileService as suggested by Coemgen below.

您可以在此处下载我的代码:[zip包] [3]. (它基于带有ASP.NET Identity Core的 Quickstart5 并通过ProfileService添加了声明).

You can download my code here: [zip package][3]. (It is based on: Quickstart5 with ASP.NET Identity Core and added claims via ProfileService).

问题:GetProfileDataAsync未执行.

Issue: GetProfileDataAsync does not executed.

推荐答案

您应该实现自己的ProfileService. 看看这篇帖子,当我实现了同样的帖子时,我也随之关注:

You should implement your own ProfileService. Have a look in this post which I followed when I implemented the same:

https://damienbod.com/2016/11/18/extending-identity-in-identityserver4-to-manage-users-in-asp-net-core/

这是我自己的实现方式的一个示例:

Here is an example of my own implementation:

public class ProfileService : IProfileService
{
    protected UserManager<ApplicationUser> _userManager;

    public ProfileService(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        //>Processing
        var user = await _userManager.GetUserAsync(context.Subject);

        var claims = new List<Claim>
        {
            new Claim("FullName", user.FullName),
        };

        context.IssuedClaims.AddRange(claims);
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        //>Processing
        var user = await _userManager.GetUserAsync(context.Subject);

        context.IsActive = (user != null) && user.IsActive;
    }
}

请不要忘记在Startup.cs中添加此行

Don't forget to add this line in your Startup.cs

services.AddTransient<IProfileService, ProfileService>();

这篇关于如何添加自定义声明以访问IdentityServer4中的令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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