-
Notifications
You must be signed in to change notification settings - Fork 0
/
CognitoAuthenticator.cs
87 lines (77 loc) · 2.4 KB
/
CognitoAuthenticator.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
using RestSharp;
using RestSharp.Authenticators;
namespace RestSharpCognitoAuthenticator;
public class CognitoAuthenticator : AuthenticatorBase
{
private readonly string baseUrl;
private readonly string clientId;
private readonly string username;
private readonly string password;
private readonly string userAgent;
private readonly int timeout;
/// <summary>
/// AWS Cognito用のAuthenticator
/// </summary>
public CognitoAuthenticator(
string baseUrl,
string clientId,
string username,
string password,
string token = "",
string userAgent = "test-requets",
int timeout = -1
) : base(token)
{
this.baseUrl = baseUrl;
this.clientId = clientId;
this.username = username;
this.password = password;
this.userAgent = userAgent;
this.timeout = timeout;
}
protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
{
var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token;
return new HeaderParameter(KnownHeaders.Authorization, token);
}
private async Task<string> GetToken()
{
var authClient = new RestClient(
new RestClientOptions(baseUrl)
{
MaxTimeout = timeout
}
);
var body = $@"{{
""AuthFlow"": ""USER_PASSWORD_AUTH"",
""ClientId"": ""{clientId}"",
""AuthParameters"": {{
""USERNAME"": ""{username}"",
""PASSWORD"": ""{password}""
}}
}}";
var request = new RestRequest()
.AddHeader("Content-Type", "application/x-amz-json-1.1")
.AddHeader("X-Amz-User-Agent", userAgent)
.AddHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth")
.AddJsonBody(body);
var response = await authClient.PostAsync<CognitoResponse>(request);
return response?.AuthenticationResult?.IdToken ?? "";
}
}
record CognitoResponse
{
public AuthenticationResult? AuthenticationResult { get; init; }
public ChallengeParameters? ChallengeParameters { get; init; }
}
record AuthenticationResult
{
public string? AccessToken { get; init; }
public int ExpiresIn { get; init; }
public string? IdToken { get; init; }
public string? RefreshToken { get; init; }
public string? TokenType { get; init; }
}
record ChallengeParameters
{
}