forked from ringcentral/RingCentral.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthorizeUriExtension.cs
67 lines (58 loc) · 2.36 KB
/
AuthorizeUriExtension.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
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace RingCentral.Net.AuthorizeUri
{
public class AuthorizeUriExtension : SdkExtension
{
private readonly AuthorizeUriOptions _options;
private RestClient _rc;
public AuthorizeUriExtension(AuthorizeUriOptions authorizeUriOptions = null)
{
_options = authorizeUriOptions ?? AuthorizeUriOptions.DefaultInstance;
}
public string CodeVerifier { get; private set; }
public override Task Install(RestClient rc)
{
_rc = rc;
return Task.CompletedTask;
}
public string BuildUri(AuthorizeRequest authorizeRequest)
{
if (authorizeRequest.response_type == null) authorizeRequest.response_type = "code";
if (authorizeRequest.client_id == null) authorizeRequest.client_id = _rc.clientId;
// PKCE: https://medium.com/ringcentral-developers/use-authorization-code-pkce-for-ringcentral-api-in-client-app-e9108f04b5f0
if (authorizeRequest.code_challenge_method == "S256")
{
var randomBytes = new byte[32];
new Random().NextBytes(randomBytes);
CodeVerifier = Convert.ToBase64String(randomBytes)
.Replace("+", "-")
.Replace("/", "_")
.Replace("=", "");
var sha256Hash = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(CodeVerifier));
authorizeRequest.code_challenge = Convert.ToBase64String(sha256Hash)
.Replace("+", "-")
.Replace("/", "_")
.Replace("=", "");
}
var query = string.Join("&",
Utils.GetPairs(authorizeRequest).Select(t => $"{t.name}={Uri.EscapeDataString(t.value.ToString())}"));
UriBuilder uriBuilder;
if (_options.baseUri == null)
uriBuilder = new UriBuilder(_rc.server)
{
Path = "/restapi/oauth/authorize",
Query = query
};
else
uriBuilder = new UriBuilder(_options.baseUri)
{
Query = query
};
return uriBuilder.Uri.ToString();
}
}
}