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 添加自定義聲明)
主站蜘蛛池模板: 主题班会网 - 安全教育主题班会,各类主题班会PPT模板 | 板框压滤机-隔膜压滤机配件生产厂家-陕西华星佳洋装备制造有限公司 | 安全阀_弹簧式安全阀_美标安全阀_工业冷冻安全阀厂家-中国·阿司米阀门有限公司 | SMC-ASCO-CKD气缸-FESTO-MAC电磁阀-上海天筹自动化设备官网 | 直齿驱动-新型回转驱动和回转支承解决方案提供商-不二传动 | 餐饮小吃技术培训-火锅串串香培训「何小胖培训」_成都点石成金[官网] | 送料机_高速冲床送料机_NC伺服滚轮送料机厂家-东莞市久谐自动化设备有限公司 | 发电机组|柴油发电机组-批发,上柴,玉柴,潍柴,康明斯柴油发电机厂家直销 | 防水套管厂家-柔性防水套管-不锈钢|刚性防水套管-天翔管道 | 网站建设-高端品牌网站设计制作一站式定制_杭州APP/微信小程序开发运营-鼎易科技 | 示波器高压差分探头-国产电流探头厂家-南京桑润斯电子科技有限公司 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 智能门锁电机_智能门锁离合器_智能门锁电机厂家-温州劲力智能科技有限公司 | 北京租车牌|京牌指标租赁|小客车指标出租 | 断桥铝破碎机_铝合金破碎机_废铁金属破碎机-河南鑫世昌机械制造有限公司 | 细石混凝土泵_厂家_价格-烟台九达机械有限公司 | 动库网动库商城-体育用品专卖店:羽毛球,乒乓球拍,网球,户外装备,运动鞋,运动包,运动服饰专卖店-正品运动品网上商城动库商城网 - 动库商城 | 实验室pH计|电导率仪|溶解氧测定仪|离子浓度计|多参数水质分析仪|pH电极-上海般特仪器有限公司 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 吉祥新世纪铝塑板_生产铝塑板厂家_铝塑板生产厂家_临沂市兴达铝塑装饰材料有限公司 | 杭州高温泵_热水泵_高温油泵|昆山奥兰克泵业制造有限公司 | 烘箱-工业烘箱-工业电炉-实验室干燥箱 - 苏州华洁烘箱制造有限公司 | 九爱图纸|机械CAD图纸下载交流中心 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | TPE_TPE热塑性弹性体_TPE原料价格_TPE材料厂家-惠州市中塑王塑胶制品公司- 中塑王塑胶制品有限公司 | 原子吸收设备-国产分光光度计-光谱分光光度计-上海光谱仪器有限公司 | 视频教程导航网_视频教程之家_视频教程大全_最新视频教程分享发布平台 | 聚合氯化铝厂家-聚合氯化铝铁价格-河南洁康环保科技 | 四川成都干燥设备_回转筒干燥机_脉冲除尘器_输送设备_热风炉_成都川工星科机电设备有限公司 | 风化石头制砂机_方解石制砂机_瓷砖石子制砂机_华盛铭厂家 | 广州番禺搬家公司_天河黄埔搬家公司_企业工厂搬迁_日式搬家_广州搬家公司_厚道搬迁搬家公司 | 接地电阻测试仪[厂家直销]_电缆故障测试仪[精准定位]_耐压测试仪-武汉南电至诚电力设备 | 丙烷/液氧/液氮气化器,丙烷/液氧/液氮汽化器-无锡舍勒能源科技有限公司 | 家德利门业,家居安全门,别墅大门 - 安徽家德利门业有限公司 | 酒水灌装机-白酒灌装机-酒精果酒酱油醋灌装设备_青州惠联灌装机械 | 天津货架厂_穿梭车货架_重型仓储货架_阁楼货架定制-天津钢力仓储货架生产厂家_天津钢力智能仓储装备 | 手术室净化厂家-成都做医院净化工程的公司-四川华锐-15年特殊科室建设经验 | 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 济南网站建设|济南建网站|济南网站建设公司【济南腾飞网络】【荐】 | 精密钢管,冷拔精密无缝钢管,精密钢管厂,精密钢管制造厂家,精密钢管生产厂家,山东精密钢管厂家 | 塑料检查井_双扣聚氯乙烯增强管_双壁波纹管-河南中盈塑料制品有限公司 |