【问题标题】:Azure AD Authentication Token not authorizedAzure AD 身份验证令牌未授权
【发布时间】:2021-03-04 13:21:22
【问题描述】:

我创建了一个 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']
}

【问题讨论】:

  • 请问您是如何获得令牌的?
  • 我使用 MSAL,这是我的代码 const { instance, accounts } = useMsal(); 配置:msalConfig = { auth: { clientId: "clientId", authority: "sts.windows.net/APITenantId", tenantId: "API TenantId" , redirectUri: "localhost:3000", client_Secret: "ClientSecret" }, Cashe: { CasheLocation: "sessionStorage", storeAuthStateInCookkie: false }, } export const loginRequest = { scope: ['api://clientId/Read'] }
  • 对不起我是初学者:(
  • 我可以知道代码范围内的 clientId 值是否:['api://clientId/Read'] 与服务器端相同:options.Audience = Configuration["AzureAd:ClientId"]; ?
  • 是一样的

标签: azure azure-active-directory


【解决方案1】:

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

在 Azure AD 中注册服务

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

  2. 选择新注册

  3. 注册申请页面出现时,输入您的申请注册信息:

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

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

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

注册客户端

  1. 导航到面向开发人员的 Microsoft 标识平台App registrations 页面。
  2. 选择新注册
  3. 注册应用程序页面出现时,输入您的应用程序的注册信息:
    • 名称部分,输入一个有意义的应用名称,该名称将显示给应用用户,例如ProfileSPA
    • 支持的帐户类型更改为仅限此组织目录中的帐户
    • 选择注册以创建应用程序。
  4. 在应用Overview页面,找到Application (client) 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

【讨论】:

  • 替换startup.cs后,即使没有token也可以访问API。
  • @StillANoob 你在控制器上添加[Authorize]了吗?
猜你喜欢
  • 2019-10-14
  • 2018-11-08
  • 2020-01-12
  • 1970-01-01
  • 2017-05-06
  • 2020-04-23
  • 1970-01-01
  • 2019-11-16
  • 2018-05-19
相关资源
最近更新 更多