Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api 如何使用Identity Server 4(JWT)进行基于角色的Web API授权_Asp.net Web Api_Asp.net Core_Jwt_Identityserver4 - Fatal编程技术网

Asp.net web api 如何使用Identity Server 4(JWT)进行基于角色的Web API授权

Asp.net web api 如何使用Identity Server 4(JWT)进行基于角色的Web API授权,asp.net-web-api,asp.net-core,jwt,identityserver4,Asp.net Web Api,Asp.net Core,Jwt,Identityserver4,这对我来说都是新鲜事,我仍在努力克服它。我已经设置了一个IDP(Identity Server 4),我能够配置一个客户端来对其进行身份验证(Angular 6应用程序),并进一步对API进行身份验证(Asp.Net Core 2.0)。一切似乎都很好 以下是IDP中的客户端定义: new Client { ClientId = "ZooClient", ClientName = "Zoo Client",

这对我来说都是新鲜事,我仍在努力克服它。我已经设置了一个IDP(Identity Server 4),我能够配置一个客户端来对其进行身份验证(Angular 6应用程序),并进一步对API进行身份验证(Asp.Net Core 2.0)。一切似乎都很好

以下是IDP中的客户端定义:

new Client
            {
                ClientId = "ZooClient",
                ClientName = "Zoo Client",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
                RequireConsent = true,

                RedirectUris           = { "http://localhost:4200/home" },
                PostLogoutRedirectUris = { "http://localhost:4200/home" },
                AllowedCorsOrigins = { "http://localhost:4200" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Phone,
                    IdentityServerConstants.StandardScopes.Address,
                    "roles",
                    "ZooWebAPI"
                }
            }
我请求客户端中的以下作用域: “openid配置文件电子邮件角色ZooWebAPI”

WebAPI的设置如下:

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvcCore()
            .AddJsonFormatters()
            .AddAuthorization();

        services.AddCors();
        services.AddDistributedMemoryCache();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44317";
                options.RequireHttpsMetadata = false;
                options.ApiName = "ZooWebAPI";    
            });


    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(policy =>
        {
            policy.WithOrigins("http://localhost:4200");
            policy.AllowAnyHeader();
            policy.AllowAnyMethod();
            policy.AllowCredentials();
            policy.WithExposedHeaders("WWW-Authenticate");
        });

        app.UseAuthentication();
        app.UseMvc();
    }
通过使用[Authorize],我成功地保护了API:

[Route("api/[controller]")]
    [Authorize]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public ActionResult Get()
        {
            return new JsonResult(User.Claims.Select(
                c => new { c.Type, c.Value }));
        }
    }
一切正常,若客户端未经身份验证,则浏览器转到IDP,需要身份验证,使用访问令牌重定向回,然后访问令牌用于成功进行的API调用

如果我查看用户对象中的声明,我可以看到一些信息,但我没有任何用户信息。我可以看到范围等,但没有角色等。从我所读到的内容来看,这是意料之中的,API不应该关心用户在调用什么,但我如何根据角色限制API调用呢?或者这会完全违反规范吗

IDP有一个userinfo端点,它返回所有用户信息,我认为这将在WebAPI中使用,但从一些阅读来看,它的目的似乎是只从客户端调用该端点

无论如何,我想根据特定用户的角色限制Web API调用。有人有什么建议、意见吗?另外,我想知道是什么用户在打电话,我会怎么做

JWT示例:


谢谢

从您的信息中,我可以了解到以下几点

您正在通过外部提供程序登录:Windows身份验证。 您正在定义一些作用域,以将某些内容传递给表示访问特定资源的令牌

您提到的用户对象是从访问令牌填充的用户类。由于默认情况下访问令牌不包括用户配置文件声明,因此用户对象上没有这些声明。这与直接使用Windows身份验证不同,Windows身份验证根据用户原则提供用户名

您需要采取其他操作,根据用户登录提供授权。 您可以在以下几点添加授权逻辑:

您可以在Identityserver配置中定义的自定义作用域上定义声明。这是不可取的,因为它是固定的登录方法,而不是用户登录

您可以使用claimtransformation(参见下面的链接)。这允许您将声明添加到方法开始时可用的声明列表中。这有一个缺点(对某些人来说是肯定的),即这些额外的声明不会添加到访问令牌本身,只有在后端对令牌进行评估时,才会在代码处理请求之前添加这些声明

如何检索这些索赔取决于您的业务需求

如果需要用户信息,则必须调用Identityserver的userinfo端点以至少了解用户名。这就是该端点的目的。基于此,您可以使用自己的逻辑来确定该用户的“角色”

例如,我们创建了一个单独的服务,可以根据用户和accesstoken中包含的作用域配置和返回“角色”声明