简体   繁体   English

在OpenId Connect(AAD)之后对用户进行身份验证,但无法找到访问令牌

[英]User is authenticated after OpenId Connect (AAD) but Unable to find access token

I am trying to find the access token from AAD after user is authenticated from OpenId Connect. 从OpenId Connect对用户进行身份验证后,我试图从AAD查找访问令牌。 It is a web application integrated with AAD OpenId Connect. 它是与AAD OpenId Connect集成的Web应用程序。 I need to get the access token to call another API that uses the same AAD. 我需要获取访问令牌才能调用使用相同AAD的另一个API。 Here's what I've tried: 这是我尝试过的:

  1. Clone this sample code. 克隆示例代码。
  2. In Startup.cs file, add the following block of code: 在Startup.cs文件中,添加以下代码块:

      public void ConfigureServices(IServiceCollection services) { services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor(); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddAzureAd(options => Configuration.Bind("AzureAd", options)) .AddOpenIdConnect("oidc", options => { options.Authority = "http://localhost:5000"; options.ClientId = "<<client-id>>"; options.SignInScheme = "cookie"; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.RequireHttpsMetadata = false; }) .AddCookie(); services.AddMvc();} 
  3. In HomeController class, I added a private variable called httpContextAccessor and also set it in the constructor. HomeController类中,我添加了一个名为httpContextAccessor的私有变量,并将其设置在构造函数中。

      private IHttpContextAccessor _httpContextAccessor; public HomeController(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } 
  4. In the HomeController class, I added some code to access the access token. HomeController类中,我添加了一些代码来访问访问令牌。

      public IActionResult Index() { if (User.Identity.IsAuthenticated) { var attempt1 = Request.Headers["Authorization"]; var attempt2 = HttpContext.GetTokenAsync("access_token"); var attempt3 = _httpContextAccessor.HttpContext.GetTokenAsync("access_token"); var attempt4 = _httpContextAccessor.HttpContext.Request.Headers["Authorziation"]; } return View(); } 

But all of them return either empty or null. 但是它们全部返回空或空。 Did I miss anything? 我有想念吗?

I've looked at this following posts for reference: How to refresh access token How to get access token from HttpContext in .Net core 2.0 我查看了以下这些帖子以供参考: 如何刷新访问令牌 如何在.Net core 2.0中从HttpContext获取访问令牌

You need to set SaveTokens to true in OpenID Connect configuration: 您需要在OpenID Connect配置中将SaveTokens设置为true:

  1. Clone that code sample 克隆该代码示例
  2. Keep the Startup.cs , you don't need to add .AddOpenIdConnect part , AddAzureAd extension method would help add Azure Active Directory Authentication to your application. 保留Startup.cs ,无需添加.AddOpenIdConnect部分, AddAzureAd扩展方法将有助于向您的应用程序添加Azure Active Directory身份验证。

  3. Modify the AzureAdAuthenticationBuilderExtensions.cs in Extensions folder : 修改Extensions文件夹中的AzureAdAuthenticationBuilderExtensions.cs

     public void Configure(string name, OpenIdConnectOptions options) { options.ClientId = _azureOptions.ClientId; options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}"; options.UseTokenLifetime = true; options.CallbackPath = _azureOptions.CallbackPath; options.RequireHttpsMetadata = false; options.SaveTokens = true; // set to true } 
  4. Then you can get the ID token from httpContextAccessor : 然后,您可以从httpContextAccessor获取ID令牌:

     var idToken = _httpContextAccessor.HttpContext.GetTokenAsync("id_token"); 

But the access token is still null . 但是访问令牌仍然为null。 The sample shows how to use the OpenID Connect ASP.NET Core middleware to sign-in users from a single Azure AD tenant , that means you can get the ID Token which is sent to the client application as part of an OpenID Connect flow and is used by the client to authenticate the user. 该示例演示如何使用OpenID Connect ASP.NET Core中间件从单个Azure AD租户登录用户,这意味着您可以获得ID Token ,该ID Token作为OpenID Connect流程的一部分发送到客户端应用程序,并且由客户端用来验证用户身份。 Please refer to document : ID tokens . 请参阅文档: ID令牌

While Access tokens enable clients to securely call APIs protected by Azure . 通过Access tokens客户端可以安全地调用受Azure保护的API。 Please refer to document : Azure Active Directory access tokens . 请参考文档: Azure Active Directory访问令牌

If you want to get the access token for accessing resource which protected by Azure AD , you should use ADAL (Azure AD V1.0 endpoint) to obtain the token , see code sample(especially use OnAuthorizationCodeReceived to acquire access token ): 如果要获取用于访问受Azure AD保护的资源的访问令牌,则应使用ADAL (Azure AD V1.0端点)获取令牌,请参见代码示例(尤其是使用OnAuthorizationCodeReceived获取访问令牌 ):

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

Or use MSAL if you are using Azure AD V2.0 endpoint . 如果使用的是Azure AD V2.0终结 ,请使用MSAL

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

相关问题 OpenID Connect:验证用户ID令牌或访问令牌的正确方法?刷新ID令牌? - OpenID Connect: Proper way of authenticating user - ID token or Access token? Refreshing ID tokens? Blazor 服务器 - 从当前登录用户获取 AAD 访问令牌 - Blazor server - get AAD access token from current logged in user 用户无法访问 IdP 时 OpenID Connect 帐户恢复? - OpenID Connect account recovery when the user can't access the IdP? Django Rest接口-无法访问我的资源中经过身份验证的用户 - Django Rest Interface - unable to access authenticated user in my resource 如何在不使用OpenID的情况下使用AAD身份验证从AAD检索登录用户的组/角色“ MailNickName” - How to retrieve the SignIn user's group/role “MailNickName” from AAD using AAD authentication without OpenID Symfony 4身份验证的用户令牌丢失 - Symfony 4 authenticated user token lost 使用 OAuth 2.0 / OpenID Connect 访问与 ID 令牌的 REST-API 授权的最佳实践 - Best practise for REST-API authorization using OAuth 2.0 / OpenID Connect access vs. ID token 注销后无法清除访问令牌 - Unable to clear access token after log out Openid - 身份验证后的用户详细信息 - Openid - User details after authentication User.Identity.IsAuthenticated 在使用 OpenId Connect 和 Auth0 登录后返回 false - User.Identity.IsAuthenticated returns false after login while using OpenId Connect with Auth0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM