首页 > 解决方案 > 针对 ProtectedWebWebi 的 Azure AD 身份验证

问题描述

我下载了守护程序应用程序的 Azure 示例,并在调试代码的末尾有一个不记名令牌。我坚持的事情是使用此令牌调用 Web API 进行身份验证。这是在 .NET Core 2.2 中

    public void ConfigureServices(IServiceCollection services)
    {
        // This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
        // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
        // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'
        // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

        services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration);

        services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
        {
            //options.TokenValidationParameters.RoleClaimType = "roles";
        });

        //// Creating policies that wraps the authorization requirements
        services.AddAuthorization(options =>
        {
            options.AddPolicy("AdminUsers", policy => policy.RequireRole("AdminUsers"));
        });

        services.AddControllers();
    }

    [HttpGet]
    [Authorize]
    public IActionResult Get()
    {
        return Ok(TodoStore.Values);
    }

我把角色拿出来,只是让每个人都可以使用,不确定我是否需要在此处放置组授权才能使其工作。我无法让它开箱即用。我正在考虑修改其中的一些以使其正常工作。我们只需要进行身份验证,然后根据他们所在的应用程序使用他们的电子邮件来获取角色。

提前致谢。

标签: azureasp.net-web-api.net-coreactive-directoryazure-active-directory

解决方案


请参阅此Microsoft 文档

对于守护程序应用程序,您调用的 Web API 需要预先批准。守护程序应用程序没有增量同意。(没有用户交互。)租户管理员需要事先同意应用程序和所有 API 权限。

并且有一个使用 Web Api 的守护程序应用程序的GitHub 示例,如果您尝试验证由守护程序应用程序调用的 API 中的应用程序角色,请阅读此文档


推荐阅读