/
TokenAuthenticationProvider.cs
67 lines (56 loc) · 2.55 KB
/
TokenAuthenticationProvider.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
// Copyright (c) GitHub 2023 - Licensed as MIT.
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Authentication;
namespace GitHub.Octokit.Authentication;
// TODO: Consider implementing `Basic` authentication scheme as a separate class
// TODO: Consider implementing `Anonymous` authentication scheme as a separate class
// TODO: Consider implementing `AccessToken/Device` authentication scheme as a separate class
// TODO: Consider implementing `GitHub Apps` authentication scheme as a separate class
public class TokenAuthenticationProvider : IAuthenticationProvider
{
private const string AuthorizationHeaderKey = "Authorization";
/// <summary>
/// Gets the <see cref="IAuthenticationProvider"/> instance for the token authentication scheme.
/// </summary>
public IAuthenticationProvider TokenAuthProvider => this;
/// <summary>
/// Gets or sets the client identifier.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the token.
/// </summary>
public string Token { get; set; }
/// <summary>
/// Instantiates a new instance of the <see cref="TokenAuthenticationProvider"/> class.
/// </summary>
/// <param name="clientId">The client identifier to use.</param>
/// <param name="token">The token to use.</param>
/// <exception cref="ArgumentNullException"></exception>
public TokenAuthenticationProvider(string clientId, string token)
{
ArgumentException.ThrowIfNullOrEmpty(clientId);
ArgumentException.ThrowIfNullOrEmpty(token);
ClientId = clientId;
Token = token;
}
/// <summary>
/// Authenticates the application request.
/// This currently acts as a synchronous (no await) method - but will change as we do more work on the authentication library.
/// </summary>
/// <param name="request"></param>
/// <param name="additionalAuthenticationContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public Task AuthenticateRequestAsync(RequestInformation? request, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentException.ThrowIfNullOrEmpty(Token);
if (!request.Headers.ContainsKey(AuthorizationHeaderKey))
{
request.Headers.Add(AuthorizationHeaderKey, $"Bearer {Token}");
}
return Task.CompletedTask;
}
}