【发布时间】:2021-07-09 18:08:47
【问题描述】:
我正在尝试在 .NET Core Web 应用中间件中为受 AzureAD 保护的 WebAPI 生成访问令牌。
这个中间件是使用 Ajax 调用从前端 UI Javascript 调用的。这里的意图是中间件应该能够通过传递正确的访问令牌来调用受 AzureAD 保护的 WebAPI。
中间件MyHandlerMiddleware.cs调用TodoListService.cs的GetAsync方法。
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