在 c# 中为使用 AzureAd 登录的当前用户获取 Jwt 令牌

Posted

技术标签:

【中文标题】在 c# 中为使用 AzureAd 登录的当前用户获取 Jwt 令牌【英文标题】:Getting Jwt Token for current user logged in with AzureAd In c# 【发布时间】:2021-11-11 05:17:48 【问题描述】:

我使用 AzureAd 进行身份验证。登录工作正常,没有问题。 现在我正在尝试为登录的用户获取 AzurAd 令牌并将其发送到另一个 API。 我尝试使用 AcquireTokenAsync 但它没有返回组和完整令牌,或者我做错了什么?

【问题讨论】:

【参考方案1】:

按照这些文档,我在这里成功获得了访问令牌。

我想你也看到了this doc 启用登录。这是给calling api的。

我的 appsetting.json

"AzureAd": 
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "domain.onmicrosoft.com",
    "TenantId": "common",
    "ClientId": "2c0exxxxxxxdf157",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc",
    "ClientSecret": "O67Q3xxxxxxxxZ-J"
  ,
  "GraphBeta": 
    "BaseUrl": "https://graph.microsoft.com/beta",
    "Scopes": "user.read"
  

我的startup.cs:

public void ConfigureServices(IServiceCollection services)
        
            services.AddControllersWithViews();
            services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd")
                .EnableTokenAcquisitionToCallDownstreamApi(new string[]  "user.read" )
               .AddDownstreamWebApi("MyApi", Configuration.GetSection("GraphBeta")).AddInMemoryTokenCaches();
        

我的控制器

using aspnetcore_azuread.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Web;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace aspnetcore_azuread.Controllers

    [Authorize]
    public class HomeController : Controller
    
        private readonly ILogger<HomeController> _logger;
        private readonly ITokenAcquisition _tokenAcquisition;

        public HomeController(ILogger<HomeController> logger, ITokenAcquisition tokenAcquisition)
        
            _logger = logger;
            _tokenAcquisition = tokenAcquisition;
        

        public IActionResult Index()
        
            return View();
        

        public IActionResult Privacy()
        
            return View();
        

        [AuthorizeForScopes(Scopes = new[]  "user.read" )]
        public async Task<string> testAsync() 
            string[] scopes = new string[]  "user.read" ;
            string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
            return accessToken;
        


        [AllowAnonymous]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        
            return View(new ErrorViewModel  RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier );
        
    

【讨论】:

以上是关于在 c# 中为使用 AzureAd 登录的当前用户获取 Jwt 令牌的主要内容,如果未能解决你的问题,请参考以下文章