使用SPA对Microsoft Graph进行身份验证,然后在Web API中使用令牌

问题描述:

我有一个通过使用 msal.js ,针对在应用程序注册门户中注册的应用程序.它成功检索到令牌,到目前为止一切正常.

I have an SPA that authenticates a user, by using msal.js, against an app registrered at the Application Registration Portal. It successfully retrieves a token and everything is fine so far.

然后我有一个ASP.NET Web API设置,该设置应使用SPA中的令牌代表用户向Microsoft Graph发出请求,这是我遇到的麻烦.

Then I have a ASP.NET Web API setup that should use the token from the SPA to make requests to Microsoft Graph on behalf of the user and this is where I run into trouble.

到目前为止,我已经在API上设置了OWIN中间件,该中间件应该在向图形发出请求之前先验证令牌,但是无论我尝试什么,它总是无效的.我已经尝试过UseOpenIdConnectAuthenticationUseOAuthBearerAuthenticationUseJwtBearerAuthentication,但仍然没有成功. SPA和API使用相同的客户端ID,并且颁发者设置为https://login.microsoftonline.com/common/v2.0.

So far I've set up a OWIN middleware on the API that should validate the token before making a request to the graph but no matter what I try it's always invalid. I've tried UseOpenIdConnectAuthentication, UseOAuthBearerAuthentication and UseJwtBearerAuthentication but still no success. The SPA and the API uses the same Client ID and the issuer is set to https://login.microsoftonline.com/common/v2.0.

我从MS阅读了很多SO问题和示例,但是似乎没有任何内容可以解决此特定设置.根据,我至少认为有可能吗?

I've read a lot of SO questions and samples from MS but nothing seems to address this specific setup. According to this I at least think it is possible?

这是我正在使用的nuget包:

Here is the nuget packages I'm using:

  <package id="Owin" version="1.0" targetFramework="net452" />
  <package id="Microsoft.Owin" version="3.1.0" targetFramework="net452" />
  <package id="Microsoft.Owin.Security" version="3.1.0" targetFramework="net452" />
  <package id="Microsoft.Owin.Security.Jwt" version="3.1.0" targetFramework="net452" />
  <package id="Microsoft.Owin.Security.OAuth" version="3.1.0" targetFramework="net452" />
  <package id="Microsoft.Owin.Security.OpenIdConnect" version="3.1.0" targetFramework="net452" />

我使用的软件包正确吗,甚至可以通过这种方式进行设置吗?很乐意就我做错的事情提出一些建议.

Am I using the correct packages, and is it even possible to set it up this way? Would love some pointers on what I'm doing wrong.

提前谢谢!

"OAuth 2代理流"正好解决了此问题. AAD V2应用程序模型此处.

This problem is precisely solved by the "OAuth 2 On-Behalf-Of flow". This is documented for the AAD V2 App Model here.

OAuth 2.0代理流程可满足以下用例: 应用程序调用服务/Web API,进而需要调用 另一个服务/Web API.想法是传播委派的用户 请求链中的身份和权限.为了 中间层服务向下游发出经过身份验证的请求 服务,它需要保护来自Azure Active的访问令牌 目录(Azure AD),代表用户.

The OAuth 2.0 On-Behalf-Of flow serves the use case where an application invokes a service/web API, which in turn needs to call another service/web API. The idea is to propagate the delegated user identity and permissions through the request chain. For the middle-tier service to make authenticated requests to the downstream service, it needs to secure an access token from Azure Active Directory (Azure AD), on behalf of the user.