【问题标题】:How to generate API Azure AD Access Token in .NET Core Middleware in .NET Core MVC如何在 .NET Core MVC 中的 .NET Core 中间件中生成 API Azure AD 访问令牌
【发布时间】:2021-07-09 18:08:47
【问题描述】:

我正在尝试在 .NET Core Web 应用中间件中为受 AzureAD 保护的 WebAPI 生成访问令牌。

这个中间件是使用 Ajax 调用从前端 UI Javascript 调用的。这里的意图是中间件应该能够通过传递正确的访问令牌来调用受 AzureAD 保护的 WebAPI。

中间件MyHandlerMiddleware.cs调用TodoListService.csGetAsync方法。 GetAsync 调用PrepareAuthenticatedClient 并且在此方法中,它第一次尝试检索访问令牌。对此,它会抛出异常

IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. 
See https://aka.ms/ms-id-web/ca_incremental-consent. "}

.NET Core Web MVC 应用中尝试获取访问令牌的中间件代码

public class MyHandlerMiddleware
    {
        private ITodoListService _todoListService;

        public MyHandlerMiddleware(RequestDelegate next)
        {
            // This is an HTTP Handler, so no need to store next
        }

        public async Task Invoke(HttpContext context, ITodoListService todoListService)
        {
            _todoListService = todoListService;
            string result = "";
            try
            {
                IEnumerable<Todo> listToDo = await _todoListService.GetAsync();
                if(listToDo == null)
                {
                    throw new System.Exception();
                }
                result = "Success";
            }
            catch (System.Exception ex)
            {
                result = "Error";
            }

            string response = abc;
            context.Response.ContentType = GetContentType();
            await context.Response.WriteAsync(response);
        }
   }

TodoListService.cs 代码

public class TodoListService : ITodoListService
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly HttpClient _httpClient;
        private readonly string _TodoListScope = string.Empty;
        private readonly string _TodoListBaseAddress = string.Empty;
        private readonly ITokenAcquisition _tokenAcquisition;

        public TodoListService(ITokenAcquisition tokenAcquisition, HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor contextAccessor)
        {
            _httpClient = httpClient;
            _tokenAcquisition = tokenAcquisition;
            _contextAccessor = contextAccessor;
            _TodoListScope = configuration["TodoList:TodoListScope"];
            _TodoListBaseAddress = configuration["TodoList:TodoListBaseAddress"];
        }

        public async Task<IEnumerable<Todo>> GetAsync()
        {
            await PrepareAuthenticatedClient();
            var response = await _httpClient.GetAsync($"{ _TodoListBaseAddress}/api/todolist");
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();
                IEnumerable<Todo> todolist = JsonConvert.DeserializeObject<IEnumerable<Todo>>(content);

                return todolist;
            }

            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}.");
        }

        private async Task PrepareAuthenticatedClient()
        {
            string accessToken = "";
            try
            {
                accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope }, null, null, _contextAccessor.HttpContext.User);
            }
            catch (System.Exception ex)
            {
                var a = 10;
            }
            Debug.WriteLine($"access token-{accessToken}");
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
    }

【问题讨论】:

    标签: .net-core azure-active-directory asp.net-core-mvc msal asp.net-core-middleware


    【解决方案1】:

    这是因为租户管理员需要为您要使用的范围提供对您的 Web API 的管理员同意。

    这是具有相同错误的场景,我建议您浏览以下链接。 请参考以下教程? https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2/tree/master/2.%20Web%20API%20now%20calls%20Microsoft%20Graph

    如果以上内容没有帮助,也请关注此链接,并在此处讨论多个问题的同一主题:https://github.com/AzureAD/microsoft-identity-web/issues/667

    如果令牌是在用户上下文中获取的,则需要授权委托权限;如果令牌是在应用程序上下文中获取的,则需要应用程序权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2020-06-28
      • 1970-01-01
      • 2021-06-20
      • 2021-11-05
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多