-
Notifications
You must be signed in to change notification settings - Fork 533
/
DefaultAppleClientSecretGenerator.cs
129 lines (111 loc) · 5.04 KB
/
DefaultAppleClientSecretGenerator.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace AspNet.Security.OAuth.Apple.Internal
{
internal sealed class DefaultAppleClientSecretGenerator : AppleClientSecretGenerator
{
private readonly ISystemClock _clock;
private readonly ILogger _logger;
private readonly AppleKeyStore _keyStore;
private readonly JwtSecurityTokenHandler _tokenHandler;
private string _clientSecret;
private DateTimeOffset _expiresAt;
public DefaultAppleClientSecretGenerator(
[NotNull] AppleKeyStore keyStore,
[NotNull] ISystemClock clock,
[NotNull] JwtSecurityTokenHandler tokenHandler,
[NotNull] ILogger<DefaultAppleClientSecretGenerator> logger)
{
_keyStore = keyStore;
_clock = clock;
_tokenHandler = tokenHandler;
_logger = logger;
}
/// <inheritdoc />
public override async Task<string> GenerateAsync([NotNull] AppleGenerateClientSecretContext context)
{
if (_clientSecret == null || _clock.UtcNow >= _expiresAt)
{
try
{
(_clientSecret, _expiresAt) = await GenerateNewSecretAsync(context);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to generate new client secret for the {context.Scheme.Name} authentication scheme.");
throw;
}
}
return _clientSecret;
}
private async Task<(string clientSecret, DateTimeOffset expiresAt)> GenerateNewSecretAsync(
[NotNull] AppleGenerateClientSecretContext context)
{
var expiresAt = _clock.UtcNow.Add(context.Options.ClientSecretExpiresAfter).UtcDateTime;
var subject = new Claim("sub", context.Options.ClientId);
_logger.LogDebug(
"Generating new client secret for subject {Subject} that will expire at {ExpiresAt}.",
subject.Value,
expiresAt);
var tokenDescriptor = new SecurityTokenDescriptor()
{
Audience = context.Options.TokenAudience,
Expires = expiresAt,
Issuer = context.Options.TeamId,
Subject = new ClaimsIdentity(new[] { subject }),
};
byte[] keyBlob = await _keyStore.LoadPrivateKeyAsync(context);
string clientSecret;
using (var algorithm = CreateAlgorithm(keyBlob, context.Options.PrivateKeyPassword))
{
tokenDescriptor.SigningCredentials = CreateSigningCredentials(context.Options.KeyId, algorithm);
clientSecret = _tokenHandler.CreateEncodedJwt(tokenDescriptor);
}
_logger.LogTrace("Generated new client secret with value {ClientSecret}.", clientSecret);
return (clientSecret, expiresAt);
}
private ECDsa CreateAlgorithm(byte[] keyBlob, string password)
{
// This becomes xplat in .NET Core 3.0: https://github.com/dotnet/corefx/pull/30271
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
CreateAlgorithmWindows(keyBlob) :
CreateAlgorithmLinuxOrMac(keyBlob, password);
}
private ECDsa CreateAlgorithmLinuxOrMac(byte[] keyBlob, string password)
{
// Does not support .p8 files in .NET Core 2.x as-per https://github.com/dotnet/corefx/issues/18733#issuecomment-296723615
// Unlike Linux, macOS does not support empty passwords for .pfx files.
using (var cert = new X509Certificate2(keyBlob, password))
{
return cert.GetECDsaPrivateKey();
}
}
private ECDsa CreateAlgorithmWindows(byte[] keyBlob)
{
// Only Windows supports .p8 files in .NET Core 2.0 as-per https://github.com/dotnet/corefx/issues/18733
using (var privateKey = CngKey.Import(keyBlob, CngKeyBlobFormat.Pkcs8PrivateBlob))
{
return new ECDsaCng(privateKey) { HashAlgorithm = CngAlgorithm.Sha256 };
}
}
private SigningCredentials CreateSigningCredentials(string keyId, ECDsa algorithm)
{
var key = new ECDsaSecurityKey(algorithm) { KeyId = keyId };
return new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256Signature);
}
}
}