简体   繁体   English

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

[英]How to do Role-based Web API Authorization using Identity Server 4 (JWT)

This is all new to me and I'm still trying to wrap my head around it. 这对我来说是全新的,我仍在努力解决。 I've got an IDP (Identity Server 4) set up, and I was able to configure a client to authenticate to it (Angular 6 App), and further more to authenticate to an API (Asp.Net Core 2.0). 我已经设置了IDP(Identity Server 4),并且能够配置客户端以对其进行身份验证(Angular 6 App),并且还可以配置客户端以进行API身份验证(Asp.Net Core 2.0)。 It all seems to work fine. 一切似乎都正常。

Here's the client definition in the IDP: 这是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"
                }
            }

I'm requesting the following scopes in the client: 'openid profile email roles ZooWebAPI' 我在客户端请求以下范围:'openid个人资料电子邮件角色ZooWebAPI'

The WebAPI is set up as such: 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();
    }

By using [Authorize] I was successfully able to secure the API: 通过使用[授权],我成功地保护了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 }));
        }
    }

Everything works fine, if client is not authenticated, browser goes to IDP, requires authentication, redirects back with access token, access token is then used for API calls that are successfully made. 一切正常,如果客户端未通过身份验证,浏览器将转到IDP,需要身份验证,使用访问令牌重定向回去,然后将访问令牌用于成功进行的API调用。

If I look at the Claims in the User object, I can see some information, but I don't have any user information. 如果查看User对象中的Claims,可以看到一些信息,但没有任何用户信息。 I can see the scopes, and etc, but no roles for example. 我可以看到范围等,但是没有角色。 From what I read, that is to be expected, and the API should not care about what user is calling it, but how would I go by restricting API calls based on roles? 从我所读的内容中可以预料到,API不应该在乎用户正在调用什么,但是如何通过基于角色的API调用来限制我呢? Or would that be completely against specs? 还是完全违反规格?

The IDP has an userinfo end point that returns all the user information, and I thought that would be used in the WebAPI, but again, from some reading, it looks like the intention is for that end point to be called from the client only. IDP有一个userinfo端点,该端点返回所有用户信息,我认为可以在WebAPI中使用它,但是再次从阅读中可以看出,它的意图是仅从客户端调用该端点。

Anyway, I would like to restrict Web API calls based on the roles for a specific user. 无论如何,我想基于特定用户的角色来限制Web API调用。 Does anyone have any suggestions, comments? 有人有任何建议,意见吗? Also, I would like to know what user is making the call, how would I go by doing that? 另外,我想知道是什么用户在拨打电话,我该怎么办?

JWT example: JWT示例:

在此处输入图片说明

Thanks 谢谢

From what I can learn from your information, I can tell the following. 从我可以从您的信息中学到的东西,我可以告诉以下内容。

You are logging in through an external provider: Windows Authentication. 您正在通过外部提供程序登录:Windows身份验证。 You are defining some scopes to pass something to the token that indicates access to specific resources. 您正在定义一些范围,以将某些内容传递给令牌,以指示对特定资源的访问。

The User object you speak of, is the User class that gets filled in from the access token. 您所说的User对象是从访问令牌中填充的User类。 Since the access token by default doesn't include user profile claims, you don't have them on the User object. 由于访问令牌默认情况下不包括用户个人资料声明,因此您不会在User对象上使用它们。 This is different from using Windows Authentication directly where the username is provided on the User Principle. 这与直接使用Windows身份验证(在用户原则上提供用户名)不同。

You need to take additional action to provide authorization based on the user logging in. There a couple of points where you can add authorization logic: 您需要采取其他措施来基于用户登录提供授权。您可以在以下几点添加授权逻辑:

You could define claims on the custom scopes you define in the configuration of Identityserver. 您可以根据在Identityserver的配置中定义的自定义范围来定义声明。 This is not desirable IMHO because it's fixed to the login method and not the user logging in. 恕我直言,这是不可取的,因为它是固定于登录方法而不是用户登录的。

You could use ClaimsTransformation ( see links below). 您可以使用ClaimsTransformation(请参见下面的链接)。 This allows you to add claims to the list of claims availible at the start of your methods. 这使您可以将声明添加到方法开始时可用的声明列表中。 This has the drawback ( for some people an positive) that those extra claims are not added to the access token itself, it's only on your back-end where the token is evaluated that these claims will be added before the request is handled by your code. 这有一个缺点(对某些人来说是肯定的),这些额外的声明不会被添加到访问令牌本身中,只有在评估令牌的后端,才可以在您的代码处理请求之前添加这些声明。 。

How you retrieve those claims is up to your bussiness requirements. 您如何检索这些声明取决于您的业务需求。

If you need to have the user information, you have to call the userinfo endpoint of Identityserver to know the username at least. 如果需要用户信息,则必须调用Identityserver的userinfo端点至少知道用户名。 That is what that endpoint is intended for. 这就是该端点的目的。 Based on that you can then use your own logic to determine the 'Roles' this user has. 基于此,您可以使用自己的逻辑来确定该用户拥有的“角色”。

For instance we created an separate service that can configure and return 'Roles' claims based upon the user and the scopes included in the accesstoken. 例如,我们创建了一个单独的服务,可以根据用户和访问令牌中包含的范围来配置和返回“角色”声明。

UseClaimsTransformation .NET Core UseClaimsTransformation .NET Core

UseClaimsTransformation .NET Full framework UseClaimsTransformation .NET完整框架

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 身份服务器 4 中基于角色的授权与 .Net 核心 Web API - Role based authorization in identity server 4 with .Net core web API ASP.NET Web API中基于角色的授权-如何在主体上设置角色? - Role-based authorization in ASP.NET Web API - how to set roles on the principal? 如何从另一个应用程序调用基于角色的授权Web API? - How do I call my role-based authorized web API from another app? .Net核心Web API-基于角色的授权(允许特定域,而无需询问JWT) - .Net core web api - Role based authorization (Allow specific domains without asking JWT) 如何为asp.net mvc 4 web api做基于角色的授权 - How to do role based authorization for asp.net mvc 4 web api 是否有任何资源将基本身份验证与基于角色的授权结合使用? - Is there any resources where basic authentication is used with role-based authorization? DNN API基于角色的授权 - DNN API Role based authorization 使用不带身份的承载/ Jwt授权 - Using Bearer/Jwt authorization without Identity 使用Identity Server的ASP.net WEP API中的资源授权 - Resource Authorization in ASP.net WEP API using Identity Server 如何使用Web API 2 + AspNet Identity 2扩展IdentityRole - How do I extend IdentityRole using Web API 2 + AspNet Identity 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM