繁体   English   中英

使用Identity Server在.Net Core Web API中授权

[英]Authorization in .Net Core Web API using Identity Server

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

为了保护 API 操作,我们将在所有请求中发送由 Identity Server 生成的访问令牌。 所以我们想要验证访问令牌,我们在 API Management at API operation inbound processing 中添加了 Authentication 如下所示,因为我们不希望未经授权的请求在 API management 停止而不回击后端 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 未经授权的响应,所有具有有效访问令牌的请求都命中 Web API。

现在我们想通过检查访问令牌中是否存在所需的 Scope 来授权我们的请求。 但是由于我们已经在 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 class 的配置方法中,它正在运行。 但是我们不想在Web API中再次添加Authentication。

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

在这种情况下,您可以直接使用 APIM 策略中的required-claims来验证令牌中的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>

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

在此处输入图像描述

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM