pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用

ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
本文介紹了ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在嘗試使用 ASP.NET Core 2.0 創(chuàng)建一個 Web API 服務器,該服務器使用 azure ad v2 端點令牌授權.我還有一個 Angular 2 應用程序,在其中進行 office365 登錄.我從那里得到一個令牌,然后向 Web API 服務器中的授權操作發(fā)送一個簡單的請求.但是我的令牌沒有通過授權檢查,我收到 401 Unauthorized 響應.提供的描述是:

I am trying to create a Web API server using ASP.NET Core 2.0 which uses azure ad v2 endpoint token authorization. I also have an Angular 2 app where the office365 login happens. I get a token from there and then send a simple request to an authorized action in the Web API server. However my token doesn't pass the authorization checks and I get a 401 Unauthorized response. The description provided is:

Bearer error="invalid_token", error_description="找不到簽名密鑰"

Bearer error="invalid_token", error_description="The signature key was not found"

我解碼了令牌,解碼器也拋出了無效簽名錯誤.以下是我用于配置和令牌授權的代碼的重要部分:

I decoded the token and the decoder throws an invalid signature error as well. Here are the important parts of my code I use for configuration and token authorization:

Web API 服務器:

appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "my-registered-app-client-id",
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

AzureAdAuthenticationBuilderExtensions.cs

public static class AzureAdServiceCollectionExtensions
{
    public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder)
        => builder.AddAzureAdBearer(_ => { });

    public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
    {
        builder.Services.Configure(configureOptions);
        builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();
        builder.AddJwtBearer();
        return builder;
    }

    private class ConfigureAzureOptions: IConfigureNamedOptions<JwtBearerOptions>
    {
        private readonly AzureAdOptions _azureOptions;

        public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
        {
            _azureOptions = azureOptions.Value;
        }

        public void Configure(string name, JwtBearerOptions options)
        {
            options.Audience = _azureOptions.ClientId;
            options.Authority = $"{_azureOptions.Instance}common/v2.0";

            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
            };
        }

        public void Configure(JwtBearerOptions options)
        {
            Configure(Options.DefaultName, options);
        }
    }
}

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.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

        services.AddMvc();
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAllOrigins",
             builder =>
             {
                 builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
             });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("AllowAllOrigins");

        app.UseAuthentication();
        app.UseMvc();
    }
}

下面是我在 Angular2 應用中用來進行身份驗證的代碼:

import { Injectable } from '@angular/core';
import { Headers } from '@angular/http';
import * as hello from 'hellojs/dist/hello.all.js';

import * as MicrosoftGraph from "@microsoft/microsoft-graph-types";
import * as MicrosoftGraphClient from "@microsoft/microsoft-graph-client";
import { Configs } from "../../../shared/configs"

@Injectable()
export class HttpService {
  url = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${Configs.appId}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read&state=12345`;

  getAccessToken() {
    const msft = hello('msft').getAuthResponse();
    const accessToken = msft.access_token;
    return accessToken;
  }


  getClient(): MicrosoftGraphClient.Client
  {
    var client = MicrosoftGraphClient.Client.init({
      authProvider: (done) => {
          done(null, this.getAccessToken()); //first parameter takes an error if you can't get an access token
      },
      defaultVersion: 'v2.0'
    });
    return client;
  }
}

當從端點返回令牌時,我會向我的 Web API 服務器上的有效端點發(fā)送請求.

When a token is returned from the endpoint I send a request to a valid endpoint on my Web API server.

重要提示:我在 Web API 和 Angular 應用程序中使用相同的 AppId,因為 AzureAd v2.0 端點需要它.

我的意思是,我認為我做的一切都是照本宣科,但顯然缺少一些東西.如果有人能告訴我我在配置中做錯了什么,我將不勝感激!

My point is that I think I'm doing everything by the book but there is obviously something missing. If anyone could tell me what I did wrong in my configuration, I'd be immeasurably grateful!

解碼令牌的aud屬性為:

aud property of decoded token is:

https://graph.microsoft.com

推薦答案

在評論中經過不那么簡短的討論后,問題得到了解決.

After a not-so-short discussion in the comments the issue was resolved.

討論的要點:

  • 訪問令牌包含一個 aud 聲明,其值為 https://graph.microsoft.com,這意味著該令牌適用于 Microsoft Graph API,不是他們的 API
  • 需要在 https://apps.dev.microsoft.com/,之后應用需要使用類似于 api://25f66106-edd6-4724-ae6f-3a204cfd9f63/access_as_userscope 請求訪問令牌李>
  • The access token contained an aud claim with the value of https://graph.microsoft.com, which means the token is meant for the Microsoft Graph API, not their API
  • A Web API needed to be registered at https://apps.dev.microsoft.com/, after which the app needed to ask for an access token using a scope similar to: api://25f66106-edd6-4724-ae6f-3a204cfd9f63/access_as_user

因此,請確保 aud 聲明包含 API 的客戶端 ID 或應用 ID URI.這意味著它適用于您的 API.

So make sure that the aud claim contains the client ID or app ID URI for your API. That means it is meant for your API.

令牌還需要包含必要的范圍.

The token also needs to contain the necessary scopes.

從 AAD 請求訪問令牌時,請確保指定正確的范圍.

When asking for an access token from AAD, make sure you specify the correct scopes.

此外,如果您使用的是 v1 端點,請確保使用 ADAL,而不是 MSAL.在 v1 中,您還必須使用 resource 而不是范圍,它的值必須設置為 API 的客戶端 ID 或應用 ID URI.

Also, if you are using the v1 endpoints, make sure to use ADAL, not MSAL. In v1 also instead of scope, you have to use resource, which must have a value set to either the client ID or app ID URI of the API.

這篇關于ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發(fā)技
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
Getting access token using email address and app password from oauth2/token(使用電子郵件地址和應用程序密碼從 oauth2/token 獲取訪問令牌)
New Azure AD application doesn#39;t work until updated through management portal(新的 Azure AD 應用程序在通過管理門戶更新之前無法運行)
Adding Custom Claims to AspNetCore Azure Authenticated Application(向 AspNetCore Azure Authenticated Application 添加自定義聲明)
主站蜘蛛池模板: 南京租车,南京汽车租赁,南京包车,南京会议租车-南京七熹租车 | 软文发布平台 - 云软媒网络软文直编发布营销推广平台 | 基业箱_环网柜_配电柜厂家_开关柜厂家_开关断路器-东莞基业电气设备有限公司 | 北京百度网站优化|北京网站建设公司-百谷网络科技 | 淄博不锈钢无缝管,淄博不锈钢管-鑫门物资有限公司 | 船用锚链|专业锚链生产厂家|安徽亚太锚链制造有限公司 | 广东西屋电气有限公司-广东西屋电气有限公司 | 成都LED显示屏丨室内户外全彩led屏厂家方案报价_四川诺显科技 | 【黄页88网】-B2B电子商务平台,b2b平台免费发布信息网 | 球磨机,节能球磨机价格,水泥球磨机厂家,粉煤灰球磨机-吉宏机械制造有限公司 | 电镀整流器_微弧氧化电源_高频电解电源_微弧氧化设备厂家_深圳开瑞节能 | 课件导航网_ppt课件_课件模板_课件下载_最新课件资源分享发布平台 | elisa试剂盒价格-酶联免疫试剂盒-猪elisa试剂盒-上海恒远生物科技有限公司 | 经济师考试_2025中级经济师报名时间_报名入口_考试时间_华课网校经济师培训网站 | 传递窗_超净|洁净工作台_高效过滤器-传递窗厂家广州梓净公司 | 超声波_清洗机_超声波清洗机专业生产厂家-深圳市好顺超声设备有限公司 | 电动葫芦|手拉葫芦|环链电动葫芦|微型电动葫芦-北京市凌鹰起重机械有限公司 | 采暖炉_取暖炉_生物质颗粒锅炉_颗粒壁炉_厂家加盟批发_烟台蓝澳采暖设备有限公司 | 无机纤维喷涂棉-喷涂棉施工工程-山东华泉建筑工程有限公司▲ | 常州翔天实验仪器厂-恒温振荡器-台式恒温振荡器-微量血液离心机 恒温恒湿箱(药品/保健品/食品/半导体/细菌)-兰贝石(北京)科技有限公司 | 捷码低代码平台 - 3D数字孪生_大数据可视化开发平台「免费体验」 | 「钾冰晶石」氟铝酸钾_冰晶石_氟铝酸钠「价格用途」-亚铝氟化物厂家 | 防水接头-电缆防水接头-金属-电缆密封接头-不锈钢电缆接头 | 高精度-恒温冷水机-螺杆式冰水机-蒸发冷冷水机-北京蓝海神骏科技有限公司 | 液压升降平台_剪叉式液压/导轨式升降机_传菜机定做「宁波日腾升降机厂家」 | 济南画室培训-美术高考培训-山东艺霖艺术培训画室 | 高低温万能试验机_拉力试验机_拉伸试验机-馥勒仪器科技(上海)有限公司 | 铸铝门厂家,别墅大门庭院大门,别墅铸铝门铜门[十大品牌厂家]军强门业 | 锂电混合机-新能源混合机-正极材料混料机-高镍,三元材料混料机-负极,包覆混合机-贝尔专业混合混料搅拌机械系统设备厂家 | 英国公司注册-新加坡公司注册-香港公司开户-离岸公司账户-杭州商标注册-杭州优创企业 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 隔爆型防爆端子分线箱_防爆空气开关箱|依客思 | 空压机商城|空气压缩机|空压机配件-压缩机网旗下商城 | 自动部分收集器,进口无油隔膜真空泵,SPME固相微萃取头-上海楚定分析仪器有限公司 | 顶空进样器-吹扫捕集仪-热脱附仪-二次热解吸仪-北京华盛谱信仪器 | 宏源科技-房地产售楼系统|线上开盘系统|售楼管理系统|线上开盘软件 | 高柔性拖链电缆-聚氨酯卷筒电缆-柔性屏蔽电缆厂家-玖泰电缆 | 管家婆-管家婆软件-管家婆辉煌-管家婆进销存-管家婆工贸ERP | 洛阳永磁工业大吊扇研发生产-工厂通风降温解决方案提供商-中实洛阳环境科技有限公司 | 5nd音乐网|最新流行歌曲|MP3歌曲免费下载|好听的歌|音乐下载 免费听mp3音乐 | 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 |