Skip to content

Instantly share code, notes, and snippets.

@smaglio81
Created June 28, 2020 15:50
Show Gist options
  • Save smaglio81/f93321d63fb249d7196673e9afe7c14e to your computer and use it in GitHub Desktop.
Save smaglio81/f93321d63fb249d7196673e9afe7c14e to your computer and use it in GitHub Desktop.
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