Created
June 28, 2020 15:50
-
-
Save smaglio81/f93321d63fb249d7196673e9afe7c14e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace YourProject | |
{ | |
public class JiraOAuthDelegatingHandler : DelegatingHandler | |
{ | |
private readonly IAtlassianOAuthCredentialsManager _manager; | |
public JiraOAuthDelegatingHandler( | |
IAtlassianOAuthCredentialsManager manager | |
) | |
{ | |
_manager = manager; | |
} | |
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
var headers = request.Headers; | |
if (string.IsNullOrWhiteSpace(headers.Authorization?.Parameter)) | |
{ | |
var jwt = await _manager.GetJwtAsync(); | |
headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); | |
} | |
var retries = 0; | |
HttpResponseMessage response; | |
do | |
{ | |
response = await base.SendAsync(request, cancellationToken); | |
// unauthorized responses should have the JWT token refreshed and then try again. | |
if (response.StatusCode == HttpStatusCode.Unauthorized) | |
{ | |
await _manager.RefreshJwtAsync(); | |
var jwt = await _manager.GetJwtAsync(); | |
headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); | |
} | |
retries++; // this could go in the if statement, but it works here too | |
} while (response.StatusCode == HttpStatusCode.Unauthorized && retries < 2); | |
if (!response.IsSuccessStatusCode) | |
{ | |
var body = await response.Content.ReadAsStringAsync(); | |
var message = $"{(int)response.StatusCode} ({response.StatusCode}) - {body}"; | |
throw new HttpRequestException(message); | |
} | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment