Last active
June 28, 2020 16:06
-
-
Save smaglio81/4dae6813e5d8565116b093620870cc85 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.Net.Http; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.Options; | |
namespace YourProject | |
{ | |
public interface IAtlassianOAuthenticator | |
{ | |
HttpClient Client { get; } | |
Task<AtlassianOAuthTokenResponse> AuthenticateAsync(); | |
} | |
public interface IPasswordRetriever // you have to implement this class | |
{ | |
string GetPassword(string key); | |
} | |
public class AtlassianOAuthenticator : IAtlassianOAuthenticator | |
{ | |
private readonly YourProjectOptions _options; | |
private readonly IPasswordRetriever _passwordRetriever; | |
public HttpClient Client { get; } | |
public AtlassianOAuthenticator( | |
IOptions<YourProjectOptions> options, | |
IPasswordRetriever passwordRetriever, | |
HttpClient client | |
) | |
{ | |
_options = options.Value; | |
_passwordRetriever = passwordRetriever; | |
Client = client; | |
client.BaseAddress = AtlassianConstants.AtlassianApiRootUri; | |
} | |
internal string GetPassword(string nameExt) | |
{ | |
var name = _options.ApplicationName + nameExt; | |
var password = _passwordRetriever.GetPassword(name); // you write this one | |
return password; | |
} | |
public async Task<AtlassianOAuthTokenResponse> AuthenticateAsync() | |
{ | |
var credentials = new AtlassianOAuthCredentials() | |
{ | |
audience = AtlassianConstants.YourInstanceRootUrl, | |
grant_type = "client_credentials", | |
client_id = GetPassword(".JiraOAuth2ClientId"), | |
client_secret = GetPassword(".JiraOAuth2ClientSecret") | |
}; | |
var response = await Client.PostAsJsonAsync("oauth/token", credentials); | |
response.EnsureSuccessStatusCode(); | |
var result = await response.DeserializeAsync<AtlassianOAuthTokenResponse>(); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment