-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathPopAuthenticationOperation.cs
More file actions
177 lines (149 loc) · 6.88 KB
/
PopAuthenticationOperation.cs
File metadata and controls
177 lines (149 loc) · 6.88 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.AppConfig;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.Utils;
using JObject = System.Text.Json.Nodes.JsonObject;
using JToken = System.Text.Json.Nodes.JsonNode;
namespace Microsoft.Identity.Client.AuthScheme.PoP
{
internal class PopAuthenticationOperation : IAuthenticationOperation2
{
private readonly PoPAuthenticationConfiguration _popAuthenticationConfiguration;
private readonly IPoPCryptoProvider _popCryptoProvider;
/// <summary>
/// Creates POP tokens, i.e. tokens that are bound to an HTTP request and are digitally signed.
/// </summary>
/// <remarks>
/// Currently the signing credential algorithm is hard-coded to RSA with SHA256. Extensibility should be done
/// by integrating Wilson's SigningCredentials
/// </remarks>
public PopAuthenticationOperation(PoPAuthenticationConfiguration popAuthenticationConfiguration, IServiceBundle serviceBundle)
{
if (serviceBundle == null)
{
throw new ArgumentNullException(nameof(serviceBundle));
}
_popAuthenticationConfiguration = popAuthenticationConfiguration ?? throw new ArgumentNullException(nameof(popAuthenticationConfiguration));
_popCryptoProvider = _popAuthenticationConfiguration.PopCryptoProvider ?? serviceBundle.PlatformProxy.GetDefaultPoPCryptoProvider();
var keyThumbprint = ComputeThumbprint(_popCryptoProvider.CannonicalPublicKeyJwk);
KeyId = Base64UrlHelpers.Encode(keyThumbprint);
}
public int TelemetryTokenType => TelemetryTokenTypeConstants.Pop;
public string AuthorizationHeaderPrefix => Constants.PoPAuthHeaderPrefix;
public string AccessTokenType => Constants.PoPTokenType;
/// <summary>
/// For PoP, we chose to use the base64(jwk_thumbprint)
/// </summary>
public string KeyId { get; }
public IReadOnlyDictionary<string, string> GetTokenRequestParams()
{
return new Dictionary<string, string>() {
{ OAuth2Parameter.TokenType, Constants.PoPTokenType},
{ Constants.RequestConfirmation, ComputeReqCnf()}
};
}
public void FormatResult(AuthenticationResult authenticationResult)
{
if (!_popAuthenticationConfiguration.SignHttpRequest)
{
// token will be signed by the caller
return;
}
var header = new JObject();
header[JsonWebTokenConstants.Algorithm] = _popCryptoProvider.CryptographicAlgorithm;
header[JsonWebTokenConstants.KeyId] = KeyId;
header[JsonWebTokenConstants.Type] = Constants.PoPTokenType;
var body = CreateBody(authenticationResult.AccessToken);
string popToken = CreateJWS(JsonHelper.JsonObjectToString(body), JsonHelper.JsonObjectToString(header));
authenticationResult.AccessToken = popToken;
}
public Task FormatResultAsync(AuthenticationResult authenticationResult, CancellationToken cancellationToken = default)
{
// For now, PoP token creation is synchronous, so we wrap the sync method
// Future enhancement could make crypto operations truly async
FormatResult(authenticationResult);
return Task.CompletedTask;
}
private JObject CreateBody(string accessToken)
{
var publicKeyJwk = JToken.Parse(_popCryptoProvider.CannonicalPublicKeyJwk);
var body = new JObject
{
// Mandatory parameters
[PoPClaimTypes.Cnf] = new JObject
{
[PoPClaimTypes.JWK] = publicKeyJwk
},
[PoPClaimTypes.Ts] = DateTimeHelpers.CurrDateTimeInUnixTimestamp(),
[PoPClaimTypes.At] = accessToken,
[PoPClaimTypes.Nonce] = _popAuthenticationConfiguration.Nonce ?? CreateSimpleNonce(),
};
if (_popAuthenticationConfiguration.HttpMethod != null)
{
body[PoPClaimTypes.HttpMethod] = _popAuthenticationConfiguration.HttpMethod?.ToString();
}
if (!string.IsNullOrEmpty(_popAuthenticationConfiguration.HttpHost))
{
body[PoPClaimTypes.Host] = _popAuthenticationConfiguration.HttpHost;
}
if (!string.IsNullOrEmpty(_popAuthenticationConfiguration.HttpPath))
{
body[PoPClaimTypes.Path] = _popAuthenticationConfiguration.HttpPath;
}
return body;
}
private static string CreateSimpleNonce()
{
// Guid with no hyphens
return Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
}
private string ComputeReqCnf()
{
// There are 4 possible formats for a JWK, but Evo supports only this one for simplicity
var jwk = $@"{{""{JsonWebKeyParameterNames.Kid}"":""{KeyId}""}}";
return Base64UrlHelpers.Encode(jwk);
}
/// <summary>
/// A key ID that uniquely describes a public / private key pair. While KeyID is not normally
/// strict, AAD support for PoP requires that we use the base64 encoded JWK thumbprint, as described by
/// https://tools.ietf.org/html/rfc7638
/// </summary>
private static byte[] ComputeThumbprint(string canonicalJwk)
{
using (SHA256 hash = SHA256.Create())
{
return hash.ComputeHash(Encoding.UTF8.GetBytes(canonicalJwk));
}
}
/// <summary>
/// Creates a JWS (json web signature) as per: https://tools.ietf.org/html/rfc7515
/// Format: header.payload.signed_payload
/// </summary>
private string CreateJWS(string payload, string header)
{
StringBuilder sb = new StringBuilder();
sb.Append(Base64UrlHelpers.Encode(Encoding.UTF8.GetBytes(header)));
sb.Append('.');
sb.Append(Base64UrlHelpers.Encode(payload));
string headerAndPayload = sb.ToString();
sb.Append('.');
sb.Append(Base64UrlHelpers.Encode(_popCryptoProvider.Sign(Encoding.UTF8.GetBytes(headerAndPayload))));
return sb.ToString();
}
public Task<bool> ValidateCachedTokenAsync(MsalCacheValidationData cachedTokenData)
{
// no-op
return Task.FromResult(true);
}
}
}