【问题标题】:ASP.NET Core custom authentication filter for Azure AD token validation用于 Azure AD 令牌验证的 ASP.NET Core 自定义身份验证筛选器
【发布时间】:2021-10-28 12:46:28
【问题描述】:

我目前正在处理一个需要使用 Azure AD 令牌的项目,该令牌运行良好。我在 Azure 门户中注册了我的应用程序并在我的项目中使用了客户端 ID,这与此代码(在 startup.cs 中)一起工作正常:

services.AddMicrosoftIdentityWebApiAuthentication(configuration, "AzureAd");

这些设置在appsettings.json:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "35234523452345",
    "ClientId": "25234523452345",
    "Audience": "api://25234523452345"
},

我只想标记一个 API 调用,但使用上面的代码,它将应用于所有 API。我可以使用将使用 Azure 令牌进行身份验证的自定义筛选器吗?

有人可以帮我提供代码示例吗?

【问题讨论】:

  • 你的意思是你有一个api项目,里面有几个api动作。您集成了 azure ad,但您只想将此身份验证应用于某些特定的 api 而不是所有的 api?如果是这样,我认为this document 可以帮助您。在操作上设置[RequiredScope(scopeRequiredByApi)]。
  • 如果我猜对了,你可以参考this answer查看示例代码。
  • 先生有进展吗?或者还有什么问题?如果您觉得我下面的帖子可以解决您的问题,您能否接受它作为结束此案的答案?感谢您提前回复:)

标签: c# asp.net-core azure-active-directory access-token


【解决方案1】:

一个 ASP.NET Core Web 应用程序,它对 Azure AD 用户进行身份验证并使用 OAuth 2.0 访问令牌调用 Web API。

在这里您可以找到有关 JwtBearer 的 ASP.NET Core 示例。此处 Azure AD 示例演示了 WebApp 调用 WebApi(也是 WebAPI 的承载,应用前端的 OIDC。

示例代码:https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

参考 SO 线程:Azure AD Authentication in ASP.NET Core 2.2

【讨论】:

  • 示例代码使用的是我正在使用的相同代码,但我的问题是如何编写客户令牌验证器
【解决方案2】:

我想你可以关注this document 为特定的api设置身份验证。

根据你所做的配置,你可以像这样管理你的 api 控制器

[Authorize]
    public class HelloController : Controller
    {
        public IActionResult Index()
        {
            HttpContext.ValidateAppRole("Tiny.Read");
            Student stu = new Student();
            stu.age = 18;
            return Json(stu) ;
        }
    }

以上验证了基于角色的api权限,如果你更喜欢使用delegate api权限,可以这样设置api

[ApiController]
    [Authorize]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        [RequiredScope("User.Read")]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

【讨论】:

    【解决方案3】:

    您是否查看过useWhen 机制,它允许您将一种身份验证应用于特定条件 - 例如路径 + 方法:

    app.UseWhen(
        ctx => ctx.Request.Path.StartsWithSegments(new PathString("/api/mypath")) &&
        ctx.Request.Method != "OPTIONS",
        api => api.UseAuthentication()
    );
    

    我的experimental .Net Core API 做到了这一点,可能会给你一些想法。我的目标是以相同的方式以不同的技术编写 API,并更密切地控制 OAuth/声明处理。

    在真正的 API 中,尽可能地保持代码简单当然是有意义的,当然对于任何真正的安全/加密都使用适当的库。

    【讨论】:

      【解决方案4】:

      我为我的问题找到了解决方案,我创建了一个验证 azure 令牌的方法,并将从用户声明中返回我的用户名

              public static async Task<string> ValidateAzureToken(string token, AppConfigurationList appConfigurations)
          {
              var tenantId = "Azure Tenant Id here";
              var audience = string.Format("api://{0}", "Azure Client Id here");
              var azureClientKey = "Azure Client secret Key here";
              var myIssuer = string.Format(CultureInfo.InvariantCulture, "https://sts.windows.net/{0}/", tenantId);
              var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(azureClientKey));
              var stsDiscoveryEndpoint = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/.well-known/openid-configuration", tenantId);
              var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
              var config = await configManager.GetConfigurationAsync();
      
              var tokenHandler = new JwtSecurityTokenHandler();
      
              var validationParameters = new TokenValidationParameters
              {
                  ValidateAudience = true,
                  ValidAudience = audience,
                  ValidateIssuer = true,
                  ValidIssuer = myIssuer,
                  IssuerSigningKeys = config.SigningKeys,
                  ValidateLifetime = false,
                  IssuerSigningKey = securityKey,
              };
              _ = (SecurityToken)new JwtSecurityToken();
              SecurityToken validatedToken;
              try
              {
                  var claims = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
                  return claims.Identity.Name.Split("@")[0];
              }
              catch (Exception e)
              {
                  throw new TGUnauthorizedException("unauthorized domain user", e);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2020-04-23
        • 2020-01-12
        • 2017-05-06
        • 2019-12-13
        • 2018-05-10
        • 1970-01-01
        • 2015-05-16
        • 1970-01-01
        • 2020-07-27
        相关资源
        最近更新 更多