简体   繁体   English

使用Azure ActiveDir oAuth2.0 JWT令牌Microsoft Graph的Asp-Net-Core WebApi身份验证

[英]Asp-Net-Core WebApi Authentication using Azure ActiveDir oAuth2.0 JWT Token Microsoft Graph

I am emulating a SPA (single page application) by adapting this .net core asp-net-core template ( https://github.com/TrilonIO/aspnetcore-Vue-starter/blob/master/content/Vue2Spa.sln ) 我通过调整此.net核心asp-net-core模板( https://github.com/TrilonIO/aspnetcore-Vue-starter/blob/master/content/Vue2Spa.sln )来模拟SPA(单页应用程序)

I am able to authenticate the user using MSAL for microsoft graph. 我可以使用MSAL for Microsoft graph验证用户身份。

How can I use that same token I used for Microsoft graph for my API (same project, no CORS necessary). 如何使用与用于Microsoft图形的API相同的令牌(相同的项目,无需CORS)。

Everything I try fails. 我尝试的一切都失败了。

What should StartUp look like? StartUp应该是什么样? I don't want any cookie authentication, i have the AccessToken ready to pass as a JWT token.? 我不需要任何cookie身份验证,我已经准备好将AccessToken作为JWT令牌传递。

I'd like to use [Authorize] in my API controllers. 我想在我的API控制器中使用[授权]。

SPA --> Gets Token (it's based off my clientId etc), pass token 'Bearer eyJ0eXAiO....' with AJAX calls to my api controllers. SPA->获取令牌(基于我的clientId等),将令牌'Bearer eyJ0eXAiO ....'与AJAX调用一起传递给我的api控制器。

You will not be able to use the token that was acquired for Microsoft Graph API, to call your API. 您将无法使用为Microsoft Graph API获取的令牌来调用您的API。

Token that you acquire is valid for a specific resource, which can be identified by the aud claim value (ie audience). 您获取的令牌对特定资源有效,可以通过aud声明值(即受众)来标识。 You can read more about aud claim and how it specifies the intended recipient for the token here - Microsoft identity platform access tokens 您可以在此处阅读有关aud声明及其如何指定令牌的预期收件人的更多信息-Microsoft Identity Platform访问令牌

If you decode your current bearer token using https://jwt.ms or https://jwt.io you will see that your token for Microsoft Graph API will have an audience like https://graph.microsoft.com so it's not really meant for your application. 如果使用https://jwt.mshttps://jwt.io解码当前的承载令牌,您将看到Microsoft Graph API的令牌将具有https://graph.microsoft.com之类的受众,因此不会确实对您的应用程序有意义。

You will need to acquire a token explicitly for your api. 您将需要为您的api明确获取令牌。

You can find detailed code samples here Microsoft Identity Platform Code Samples (v2.0 endpoint) for Single Page Applications. 您可以在此处找到用于单页应用程序的Microsoft身份平台代码示例(v2.0端点)的详细代码示例。 Take a look at this one for SPA calling it's own api - JavaScript Single Page Application with an ASP.NET backend, using msal.js . 看一下用于SPA的这个程序,它使用msal.js调用自己的api-具有ASP.NET后端的JavaScript单页应用程序 This one uses clientid itself for scope. 这个使用clientid本身作为作用域。

Here is another one which (not SPA), but shows how to define your custom api scopes and then use them from client in case of API and client applications being separate - Calling an ASP.NET Core Web API from a WPF application using Azure AD V2 . 这是另一个(不是SPA),但显示了如何定义自定义api范围,然后在API和客户端应用程序分开的情况下从客户端使用它们- 使用Azure AD从WPF应用程序调用ASP.NET Core Web API V2 You can do that from Expose an API section under your app registration in Azure Portal. 您可以通过在Azure门户中的应用程序注册下的“ Expose an API部分中执行此操作。

I don't know much about MSAL in comparison to ADAL, but I believe one difference is the Azure endpoint. 与ADAL相比,我对MSAL的了解不多,但我相信其中之一是Azure终结点。 It is now changed to version 2 instead. 现在将其更改为版本2。 As recommended by Microsoft, when authenticating users against Azure AD, the suggested approach is to use oauth 2.0 implicit flow. 根据Microsoft的建议,当根据Azure AD对用户进行身份验证时,建议的方法是使用oauth 2.0隐式流。 More info can be found here . 更多信息可以在这里找到。

Your steps in acquiring token for Microsoft Graph involve a bit of time configuring. 获取Microsoft Graph令牌的步骤涉及一些时间配置。 You should register both of your front end and the API in the Azure app registration Within the front-end app, you enable implicit flow, you give it some permissions to interact with graph api. 您应该在Azure应用程序注册中同时注册您的前端和API。在前端应用程序中,启用隐式流,并为它提供一些与graph api交互的权限。 This is required in order to use your existing token to acquire another token for Microsoft Graph. 为了使用您现有的令牌来获取Microsoft Graph的另一个令牌,这是必需的。 (And you can do the same thing for any other APIs, eg. CRM API, Sharepoint API) (并且您可以对其他任何API执行相同的操作,例如CRM API,Sharepoint API)

Once you have this configured, all you need to do is to do another post request(you must include the JWT token you retrieved earlier in the request header) to https://graph.microsoft.com to acquire the token. 配置完成后,您要做的就是向https://graph.microsoft.com发出另一个发布请求(您必须在请求标头中包含之前检索的JWT令牌)以获取该令牌。 Depending on how you grant permissions to front-end, the token can be used within a given scope that you set in the app registration. 根据您授予前端权限的方式,可以在您在应用程序注册中设置的给定范围内使用令牌。

You maybe wondering why use implicit flow? 您可能想知道为什么要使用隐式流? It's because every time your front-end app sends requests to the backend API, the JWT token that you retrieved at signed in can be used to authenticate against your API. 这是因为每次您的前端应用程序向后端API发送请求时,您在登录时检索到的JWT令牌都可以用于根据您的API进行身份验证。 This way, only your front end can make calls to the api. 这样,只有您的前端才能调用api。

I was able to do it using the ID token that I created with the MSAL library. 我能够使用通过MSAL库创建的ID令牌来做到这一点。

Javascript : return myMSALObj.loginPopup(requestObj).then(function (loginResponse) { loginResponse.Token}); Javascript :返回myMSALObj.loginPopup(requestObj).then(function(loginResponse){loginResponse.Token});

You can then take that token and pass it to the API. 然后,您可以获取该令牌并将其传递给API。

in StartUp.cs 在StartUp.cs中

       public void ConfigureServices(IServiceCollection services)
       {
       services.AddAuthentication(options =>
       {
       options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
       options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
       }).AddJwtBearer(options =>
       {
       options.Authority = "https://sts.windows.net/tenantId/v2.0";
       options.Audience = clientId;
       options.TokenValidationParameters.ValidateLifetime = true;
       });

       services.AddAuthorization();

       // Add framework services.
       services.AddMvc()
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
       }```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET核心网站使用JWT令牌进行WebApi身份验证 - ASP.NET Core Website to WebApi authentication using JWT token 使用Microsoft Graph令牌通过Jwt Bearer令牌保护ASP.NET Core Web API - Using Microsoft Graph token to secure ASP.NET Core Web API with Jwt Bearer tokens 服务结构无状态服务Asp.Net Core- Oauth2.0承载令牌错误 - Service Fabric Stateless Services Asp.Net Core- Oauth2.0 Bearer Token Error 使用Microsoft System.IdentityModel.Tokens.Jwt在Asp.net WebApi中实现JWT身份验证 - Implementing JWT authentication in Asp.net WebApi using Microsoft System.IdentityModel.Tokens.Jwt 在asp.net core webapi中认证为jwt token时Securite静态文件无法生效 - Securite the static files could not take effect when authentication is jwt token in asp.net core webapi ASP.NET Core 中的 Jwt 令牌身份验证 - Jwt token authentication in ASP.NET Core 如何使用 Microsoft 身份平台身份验证在 ASP.NET Core Web 应用程序中获取 JWT 令牌? - How do I get hold of a JWT token in an ASP.NET Core Web App using Microsoft identity platform authentication? 在ASP.NET WebForms中将OAuth与令牌一起使用Azure身份验证不是MVC - Azure Authentication using OAuth with token in ASP.NET WebForms NOT MVC ASP.NET 核心 WebAPI Cookie + JWT 身份验证 - ASP.NET Core WebAPI Cookie + JWT Authentication AuthorizeAttribute与.NET Core 2.0中的JWT令牌 - 身份验证 - AuthorizeAttribute with JWT Token- Authentication in .NET Core 2.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM