c# - .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();”,延迟会是多少?会是性能问题吗?
解决方案
在这种情况下,您可以直接使用required-claims
APIM 策略中的 来验证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
在范围内,如果存在,则令牌有效。
推荐阅读
- python - 我需要一个模块在我的系统上不起作用的解决方案
- python - 从图像分割中保存单个片段
- html - 如何在树结构的 html 文件中提供图像/徽标文件的路径
- c# - VS2017和VS2019的主要Activity区别
- javascript - 链接/切换类时如何防止“跳跃”?
- javascript - 结合两个对单个 json 响应执行检查的期望语句
- python - 如何在不使用 glob 的情况下将文件的递归列表输出到文本文件(python3.4)
- javascript - 如何为常量变量赋值(不在声明中)?
- python - Pycharm - 摆脱灰色水平波浪线
- raku - 检查字符串或文件的语法