久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權(quán)不起作用

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

問(wèn)題描述

限時(shí)送ChatGPT賬號(hào)..

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

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"

我解碼了令牌,解碼器也拋出了無(wú)效簽名錯(cuò)誤.以下是我用于配置和令牌授權(quán)的代碼的重要部分:

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 服務(wù)器:

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 應(yīng)用中用來(lái)進(jìn)行身份驗(yàn)證的代碼:

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;
  }
}

當(dāng)從端點(diǎn)返回令牌時(shí),我會(huì)向我的 Web API 服務(wù)器上的有效端點(diǎn)發(fā)送請(qǐng)求.

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

重要提示:我在 Web API 和 Angular 應(yīng)用程序中使用相同的 AppId,因?yàn)?AzureAd v2.0 端點(diǎn)需要它.

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

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

推薦答案

在評(píng)論中經(jīng)過(guò)不那么簡(jiǎn)短的討論后,問(wèn)題得到了解決.

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

討論的要點(diǎn):

  • 訪問(wèn)令牌包含一個(gè) aud 聲明,其值為 https://graph.microsoft.com,這意味著該令牌適用于 Microsoft Graph API,不是他們的 API
  • 需要在 https://apps.dev.microsoft.com/,之后應(yīng)用需要使用類似于 api://25f66106-edd6-4724-ae6f-3a204cfd9f63/access_as_userscope 請(qǐng)求訪問(wèn)令牌李>
  • 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

因此,請(qǐng)確保 aud 聲明包含 API 的客戶端 ID 或應(yīng)用 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 請(qǐng)求訪問(wèn)令牌時(shí),請(qǐng)確保指定正確的范圍.

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

此外,如果您使用的是 v1 端點(diǎn),請(qǐng)確保使用 ADAL,而不是 MSAL.在 v1 中,您還必須使用 resource 而不是范圍,它的值必須設(shè)置為 API 的客戶端 ID 或應(yīng)用 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.

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

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

相關(guān)文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進(jìn)行身份驗(yàn)證并跨請(qǐng)求保留自定義聲明)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護(hù)進(jìn)程或服務(wù)器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問(wèn)令牌和刷新令牌) - IT屋-程序員軟件開(kāi)發(fā)技
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調(diào)用時(shí) Azure KeyVault Active Directory AcquireTokenAsync 超時(shí))
Getting access token using email address and app password from oauth2/token(使用電子郵件地址和應(yīng)用程序密碼從 oauth2/token 獲取訪問(wèn)令牌)
New Azure AD application doesn#39;t work until updated through management portal(新的 Azure AD 應(yīng)用程序在通過(guò)管理門(mén)戶更新之前無(wú)法運(yùn)行)
Adding Custom Claims to AspNetCore Azure Authenticated Application(向 AspNetCore Azure Authenticated Application 添加自定義聲明)
主站蜘蛛池模板: 久久国产成人 | 97色在线观看免费视频 | 国产精品伦理一区 | 成人在线国产 | 国产精品国产a级 | www.一区二区三区 | 久久久久国产 | www在线视频| 日韩视频国产 | 91九色麻豆| 日韩伦理一区二区 | 久久最新精品 | 日韩成人免费视频 | 中文字幕第90页 | 久久久久久久久久久高潮一区二区 | 91xx在线观看 | 久久久久久99 | 成人免费视频7777777 | 做a视频| 一级做a爰片性色毛片 | 日韩一区二区三区在线视频 | 精品中文字幕在线观看 | 亚洲自拍一区在线观看 | 在线免费观看日本 | 久久另类 | 日韩二区 | 区一区二区三在线观看 | 免费一级做a爰片久久毛片潮喷 | 国产自产21区 | 国产综合久久久久久鬼色 | 一区二区福利视频 | 狠狠骚 | 国产精品成人一区二区 | 欧美久久一级特黄毛片 | 亚洲一区成人 | 亚洲欧洲视频 | av毛片在线免费观看 | 91精品国产91久久久久久密臀 | 三级在线观看 | 国产主播第一页 | 久久久久免费精品国产小说色大师 |