首页 > 解决方案 > .Net Core Web API 中使用 Identity Server 的授权

问题描述

我们有一个托管在 Azure App Service 上的 .Net Core Web API,我们有自己的身份服务器来生成访问令牌。我们已将 Web API 添加到 Azure API 管理,因此对 Web API 的所有请求都必须通过 API 管理。

为了保护 API 操作,我们将在所有请求中发送 Identity Server 生成的访问令牌。所以我们想要验证访问令牌,我们在 API 操作入站处理的 API 管理中添加了身份验证,如下所示,因为我们不希望未经授权的请求在 API 管理中停止而不打后端 API。

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
   <openid-config url="https://<our-identity-server-URL>/.well-known/openid-configuration" />
</validate-jwt>

它工作正常,所有没有访问令牌的请求都抛出 401 Unauthorized Response 并且所有具有有效访问令牌的请求都在访问 Web API。

现在我们想通过检查访问令牌中是否存在所需的范围来授权我们的请求。但是由于我们已经在 API 管理中进行了身份验证,我们不想在 Web API 代码中再次进行身份验证。所以我们只在 StartUp.cs 文件中编写了授权代码,如下所示,

public void ConfigureServices(IServiceCollection services)
{
       services.AddAuthentication("Bearer").AddJwtBearer("Bearer", config =>
       {
           config.Authority = "<our Identity Server URL>";
           config.TokenValidationParameters = new TokenValidationParameters()
           {
               ValidateAudience = false
           };
       });
       services.AddAuthorization(options =>
       {
           options.AddPolicy("ApiScope", policy =>
           {
              policy.RequireClaim("scope","Allow_BackEnd_Service");
           });
        });
       services.AddControllers();            
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseRouting();
     //app.UseAuthentication(); (It is working only if I add this line)
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

但是这段代码总是返回 401 Unauthorized Result。如果我添加“app.UseAuthentication();” 在 Startup.cs 类的配置方法中,它正在工作。但是我们不想在 Web API 中再次添加身份验证。

是否可以仅在 .net Core Web API 中进行授权?如果没有,如果我必须添加“app.UseAuthentication();”,延迟会是多少?会是性能问题吗?

标签: c#.net-coreazure-web-app-serviceasp.net-core-webapiazure-api-management

解决方案


在这种情况下,您可以直接使用required-claimsAPIM 策略中的 来验证scope令牌中的 。

样本:

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
   <openid-config url="https://<our-identity-server-URL>/.well-known/openid-configuration" />
   <required-claims>
    <claim name="scp" match="any" separator=" ">
    <value>Users.Read</value>
    </claim>
    </required-claims>
</validate-jwt>

然后,如果我解码的令牌中的范围如下所示,则策略将检查是否Users.Read在范围内,如果存在,则令牌有效。

在此处输入图像描述


推荐阅读