首页 > 解决方案 > MSAL 访问令牌通过 MicrosoftIdentityWebApi 身份验证获得未经授权

问题描述

我在下面设置了我的启动类:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();

        services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

我的 AzureAd appsettings.json 如下:

  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "2f0d9252-e207-4d7f-b4da-*******",
    "TenantId": "de1ef02c-7cfa-46b8-a02b-*******",
    "Audience": "2f0d9252-e207-4d7f-b4da-*******"
  }

现在我的控制器在下面:

    [HttpGet]
    public async Task<string> Get()
    {
        //To be put on appsettings.json
        string clientId = "2f0d9252-e207-4d7f-b4da-0cc618e77c93";
        string tenantId = "de1ef02c-7cfa-46b8-a02b-61ab78bc602b";

        var app = PublicClientApplicationBuilder.Create(clientId)
            .WithRedirectUri("http://localhost:5000")
            .WithTenantId(tenantId)
            .Build();

        string[] scopes = new string[] { };

        //Azure Login Success here
        var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

        //Azure service graph get success.
        string graphResult = await "https://graph.microsoft.com/beta/me"
            .WithOAuthBearerToken(result.AccessToken)
            .GetStringAsync();

        //I pass the AccessToken from the result. But I'm getting UnAuthorized.
        string authorizeResult = await "https://localhost:44328/weatherforecast/AuthorizeGet"
            .WithOAuthBearerToken(result.AccessToken)
            .GetStringAsync();

        return graphResult;
    }

    [Authorize]
    [HttpGet]
    public async Task<string> AuthorizeGet()
    {
        return "Authorize";
    }

Azure 登录将在此处成功。但是在我获得令牌并请求 AuthorizeGet Api 之后。它会给我未经授权的401。

我错过了什么配置?

下面是我的目录身份验证配置。

在此处输入图像描述

标签: azure.net-coreazure-active-directorymsal

解决方案


推荐阅读