Identityserver4 从访问令牌获取用户信息-“;“禁止”;

Identityserver4 从访问令牌获取用户信息-“;“禁止”;,identityserver4,openid-connect,Identityserver4,Openid Connect,我想获取访问令牌的声明,但在尝试获取UserInfo时,响应返回一个错误“禁止”。 这是为什么?我该如何修复它? userinfo端点是 下面的代码一旦工作就会被重构。字段response1包含错误消息 var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync(Settings.AuthorityUrl); if (disco.IsError) {

我想获取访问令牌的声明,但在尝试获取UserInfo时,响应返回一个错误“禁止”。 这是为什么?我该如何修复它? userinfo端点是 下面的代码一旦工作就会被重构。字段response1包含错误消息

    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync(Settings.AuthorityUrl);
    if (disco.IsError)
    {
        throw new Exception(disco.Error);
    }
    var tokenRequest = new ClientCredentialsTokenRequest
    {
        Address = Settings.AuthorityUrl + "connect/token",
        ClientId = Settings.ClientId,
        ClientSecret = "secret",
        Scope = "SIR"
    };

    var response = await client.RequestClientCredentialsTokenAsync(tokenRequest);
    var token = response.AccessToken;
    var response1 = await client.GetUserInfoAsync(new UserInfoRequest
    {
        Address = disco.UserInfoEndpoint,
        Token = token
    });

    if (response1.IsError) throw new Exception(response1.Error);

    var claims = response1.Claims;
在我的IDP中,我的配置文件是

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;
using System.Security.Claims;

namespace QuickstartIdentityServer
{
    public class Config
    {
        // scopes define the resources in your system
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Address()
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("SIR", "Service Inspection Report")
            };
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            var baseUri = "http://localhost:53200/";
            // client credentials client
            return new List<Client>
            {

                // OpenID Connect hybrid flow and client credentials client (MVC)
                new Client
                {
                    ClientId = "SIR",
                    ClientName = "SIR",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    RedirectUris = { $"{baseUri}signin-oidc" },
                    PostLogoutRedirectUris = { $"{baseUri}signout-callback-oidc" },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Address,
                        "SIR"
                    },
                    AllowOfflineAccess = true,
                    AlwaysIncludeUserClaimsInIdToken = true
                }
            };
        }

        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "alice",
                    Password = "password",

                    Claims = new List<Claim>
                    {
                        new Claim("name", "Alice"),
                        new Claim("website", "https://alice.com"),
                        new Claim("address", "1a The Street")
                    }
                },
                new TestUser
                {
                    SubjectId = "2",
                    Username = "bob",
                    Password = "password",

                    Claims = new List<Claim>
                    {
                        new Claim("name", "Bob"),
                        new Claim("website", "https://bob.com"),
                        new Claim("address", "2a The Street")
                    }
                }
            };
        }
    }
}
使用IdentityServer4;
使用IdentityServer4.Models;
使用IdentityServer 4.测试;
使用System.Collections.Generic;
使用System.Security.Claims;
命名空间QuickstartIdentityServer
{
公共类配置
{
//作用域定义系统中的资源
公共静态IEnumerable GetIdentityResources()
{
返回新列表
{
新标识资源.OpenId(),
新标识资源.Profile(),
新的IdentityResources.Address()标识
};
}
公共静态IEnumerable GetApiResources()
{
返回新列表
{
新资源(“SIR”,“服务检查报告”)
};
}
//客户端希望访问资源(也称为作用域)
公共静态IEnumerable GetClients()
{
var baseUri=”http://localhost:53200/";
//客户端凭据客户端
返回新列表
{
//OpenID连接混合流和客户端凭据客户端(MVC)
新客户
{
ClientId=“先生”,
ClientName=“先生”,
AllowedGrantTypes=GrantTypes.HybridAndClientCredentials,
客户秘密=
{
新密码(“Secret.Sha256())
},
重定向URI={$“{baseUri}符号oidc},
PostLogoutRedirectUris={$“{baseUri}签出回调oidc},
允许范围=
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Address,
“先生”
},
AllowOfflineAccess=true,
AlwaysIncludeUserClaimsInIdToken=真
}
};
}
公共静态列表GetUsers()
{
返回新列表
{
新测试用户
{
SubjectId=“1”,
Username=“alice”,
Password=“Password”,
索赔=新名单
{
新索赔(“名称”、“Alice”),
新索赔(“网站”https://alice.com"),
新索赔(“地址”,“街道1a”)
}
},
新测试用户
{
SubjectId=“2”,
Username=“bob”,
Password=“Password”,
索赔=新名单
{
新索赔(“姓名”、“鲍勃”),
新索赔(“网站”https://bob.com"),
新索赔(“地址”,“街道2a”)
}
}
};
}
}
}
而创业是

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(Settings.CertPath, Settings.Password))
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers());

        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                // register your IdentityServer with Google at https://console.developers.google.com
                // enable the Google+ API
                // set the redirect URI to http://localhost:port/signin-google
                options.ClientId = "copy client ID from Google here";
                options.ClientSecret = "copy client secret from Google here";
            })
            .AddOpenIdConnect("oidc", "OpenID Connect", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;

                options.Authority = "https://demo.identityserver.io/";
                options.ClientId = "implicit";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
}
公共类启动
{
//此方法由运行时调用。请使用此方法将服务添加到容器中。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
//使用内存存储、密钥、客户端和作用域配置identity server
services.AddIdentityServer()
.AddSigningCredential(新X509Certificate2(Settings.CertPath,Settings.Password))
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
services.AddAuthentication()
.AddGoogle(“谷歌”,选项=>
{
options.signnscheme=IdentityServerConstants.ExternalCookieAuthenticationScheme;
//在Google上注册您的IdentityServerhttps://console.developers.google.com
//启用Google+API
//将重定向URI设置为http://localhost:port/signin-谷歌
options.ClientId=“在此处从谷歌复制客户端ID”;
options.ClientSecret=“在此处从谷歌复制客户端机密”;
})
.AddOpenIdConnect(“oidc”,“OpenID连接”,选项=>
{
options.signnscheme=IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme=IdentityServerConstants.SignOutScheme;
选项。权限=”https://demo.identityserver.io/";
options.ClientId=“隐式”;
options.TokenValidationParameters=新的TokenValidationParameters
{
NameClaimType=“name”,
RoleClaimType=“角色”
};
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware();
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
您正在使用