-
Notifications
You must be signed in to change notification settings - Fork 19
/
OAuthClient.cs
88 lines (71 loc) · 2.69 KB
/
OAuthClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Docker.Registry.DotNet.Helpers;
using Newtonsoft.Json;
namespace Docker.Registry.DotNet.OAuth
{
internal class OAuthClient
{
private readonly HttpClient _client = new HttpClient();
private async Task<OAuthToken> GetTokenInnerAsync(
string realm,
string service,
string scope,
string username,
string password,
CancellationToken cancellationToken = default)
{
var queryString = new QueryString();
queryString.AddIfNotEmpty("service", service);
queryString.AddIfNotEmpty("scope", scope);
var builder = new UriBuilder(new Uri(realm))
{
Query = queryString.GetQueryString()
};
var request = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
if (username != null && password != null)
{
// https://gist.github.com/jlhawn/8f218e7c0b14c941c41f
var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
var parameter = Convert.ToBase64String(bytes);
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", parameter);
}
using (var response = await this._client.SendAsync(request, cancellationToken))
{
if (!response.IsSuccessStatusCode)
throw new UnauthorizedAccessException("Unable to authenticate.");
var body = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<OAuthToken>(body);
return token;
}
}
public Task<OAuthToken> GetTokenAsync(
string realm,
string service,
string scope,
CancellationToken cancellationToken = default)
{
return this.GetTokenInnerAsync(realm, service, scope, null, null, cancellationToken);
}
public Task<OAuthToken> GetTokenAsync(
string realm,
string service,
string scope,
string username,
string password,
CancellationToken cancellationToken = default)
{
return this.GetTokenInnerAsync(
realm,
service,
scope,
username,
password,
cancellationToken);
}
}
}