Azure AD 身份验证令牌未授权

时间:2021-03-03 04:07:33

标签: azure azure-active-directory

我创建了一个 API 并期待来自 Azure AD 的访问令牌:

services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();

            options.Filters.Add(new AuthorizeFilter(policy));

        }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Audience = Configuration["AzureAd:ClientId"];
                options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";

            });

然后我使用 MSAL 在 React 上创建了一个 SPA,但是当我登录时,我的 API 不接受从 MSAL 返回的访问令牌:

function RequestProfileData() {
   
    instance.acquireTokenSilent({
        ...loginRequest,
        account: accounts[0]
    }).then((response) => {
        debugger;
        const api = axios.create({
            baseURL: 'https://localhost:44312',
            headers: {
                authorization: `Bearer ${response.accessToken}`
            }
        });
        
        
        api.get('/WeatherForecast').then(result => {
            debugger;
            console.log(result.data)
        });
    
    })

我的 MSAL 配置是:

export const msalConfig = {
    auth: {
        clientId: "ClientId",
        authority: "https://sts.windows.net/TenantId/",
        tenantId: "TenantId",
        redirectUri: "http://localhost:3000/",
            "
    },
    cashe: {
        casheLocation: "sessionStorage",
        storeAuthStateInCookkie: false
    },
}

export const loginRequest = {
    scope: ['api://ClientId/Read']
}

1 个答案:

答案 0 :(得分:0)

关于问题,请参考以下步骤

在 Azure AD 中注册服务

  1. 导航到 Microsoft 开发人员标识平台 App registrations 页面。

  2. 选择新注册

  3. 当出现注册应用程序页面时,输入应用程序的注册信息:

    • 名称部分,输入将显示给应用用户的有意义的应用名称,例如 ProfileAPI
    • 支持的帐户类型更改为仅限个人 Microsoft 帐户
    • 选择注册以创建应用程序。
  4. 在应用概览页面上,找到应用(客户端)ID值并记录下来以备后用。您将需要它来配置此项目的配置文件。

  5. 选择公开 API 部分,然后:

    • 点击应用程序 ID URI 旁边的设置以生成此应用程序唯一的 URI(以 api://{clientId} 的形式)。
    • 选择添加范围
    • 输入以下参数
      • 对于范围名称,使用 access_as_user
      • 谁可以同意
      • 保留管理员和用户
      • 用户同意显示名称中输入Access ProfileAPI as a user
      • 用户同意说明中输入Accesses the ProfileAPI web API as a user
      • 保持状态启用
      • 选择添加范围

注册客户端

  1. 导航到面向开发人员的 Microsoft 标识平台 App registrations 页面。
  2. 选择新注册
  3. 当出现注册应用程序页面时,输入应用程序的注册信息:
    • 名称部分,输入将显示给应用用户的有意义的应用名称,例如 ProfileSPA
    • 支持的帐户类型更改为仅限此组织目录中的帐户
    • 选择注册以创建应用程序。
  4. 在应用概览页面上,找到应用(客户端)ID值并记录下来以备后用。您将需要它来为此项目配置配置文件。
  5. 从应用的概览页面,选择身份验证部分。
    • 点击添加平台按钮。
    • 选择右侧边栏上的单页应用程序
    • 添加重定向 URI,例如 http://localhost:3000
    • 点击配置
  6. 选择API 权限部分
    • 点击添加权限按钮,然后
    • 确保选择了我的 API 标签
    • 在 API 列表中,选择 ProfileAPI API 或您为 Web API 输入的名称
    • 委派权限部分,确保选中正确的权限:access_as_user。如有必要,请使用搜索框。
    • 选择添加权限按钮。

配置客户端应用

关于如何在react应用中配置Azure AD,请参考here

配置服务器应用

  1. 更新 appsetting.json
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
    "TenantId": "common",
    "Audience": "custom App ID URI for your web API"
  },
  // more lines
}
  1. 安装包 Microsoft.Identity.Web

  2. 更新 startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

            services.AddControllers();
        }

        // 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())
            {
                // Since IdentityModel version 5.2.1 (or since Microsoft.AspNetCore.Authentication.JwtBearer version 2.2.0),
                // PII hiding in log files is enabled by default for GDPR concerns.
                // For debugging/development purposes, one can enable additional detail in exceptions by setting IdentityModelEventSource.ShowPII to true.
                // Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

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

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

详情请参考herehere