2018-05-16 12:44:32 +02:00
|
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Net.Http;
|
|
|
|
|
using System.Net.Http.Headers;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace WebMVC.Infrastructure
|
|
|
|
|
{
|
|
|
|
|
public class HttpClientAuthorizationDelegatingHandler
|
|
|
|
|
: DelegatingHandler
|
|
|
|
|
{
|
2021-07-22 08:44:13 +08:00
|
|
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
2018-05-16 12:44:32 +02:00
|
|
|
|
|
2021-07-22 08:44:13 +08:00
|
|
|
|
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
|
2018-05-16 12:44:32 +02:00
|
|
|
|
{
|
2021-07-22 08:44:13 +08:00
|
|
|
|
_httpContextAccessor = httpContextAccessor;
|
2018-05-16 12:44:32 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
|
|
|
{
|
2021-07-22 08:44:13 +08:00
|
|
|
|
var authorizationHeader = _httpContextAccessor.HttpContext
|
2018-05-16 12:44:32 +02:00
|
|
|
|
.Request.Headers["Authorization"];
|
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(authorizationHeader))
|
|
|
|
|
{
|
|
|
|
|
request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var token = await GetToken();
|
|
|
|
|
|
|
|
|
|
if (token != null)
|
|
|
|
|
{
|
|
|
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return await base.SendAsync(request, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async Task<string> GetToken()
|
|
|
|
|
{
|
|
|
|
|
const string ACCESS_TOKEN = "access_token";
|
|
|
|
|
|
2021-07-22 08:44:13 +08:00
|
|
|
|
return await _httpContextAccessor.HttpContext
|
2018-05-16 12:44:32 +02:00
|
|
|
|
.GetTokenAsync(ACCESS_TOKEN);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|