-
-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathUserController.cs
314 lines (274 loc) · 12.7 KB
/
UserController.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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
namespace BlazorWasmDemo.Server.Controllers;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Fido2NetLib;
using Fido2NetLib.Development;
using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private static readonly SigningCredentials _signingCredentials = new(
new SymmetricSecurityKey("This is my very long and totally secret key for signing tokens, which clients may never learn or I'd have to replace it."u8.ToArray()),
SecurityAlgorithms.HmacSha256
);
private static readonly DevelopmentInMemoryStore _demoStorage = new();
private static readonly Dictionary<string, CredentialCreateOptions> _pendingCredentials = new();
private static readonly Dictionary<string, AssertionOptions> _pendingAssertions = new();
private readonly IFido2 _fido2;
private static string FormatException(Exception e) => $"{e.Message}{e.InnerException?.Message ?? string.Empty}";
public UserController(IFido2 fido2)
{
_fido2 = fido2;
}
/// <summary>
/// Creates options to create a new credential for a user.
/// </summary>
/// <param name="username">(optional) The user's internal identifier. Omit for usernameless account.</param>
/// <param name="displayName">(optional as query) Name for display purposes.</param>
/// <param name="attestationType">(optional as query)</param>
/// <param name="authenticator">(optional as query)</param>
/// <param name="userVerification">(optional as query)</param>
/// <param name="residentKey">(optional as query)</param>
/// <returns>A new <see cref="CredentialCreateOptions"/>. Contains an error message if .Status is "error".</returns>
[HttpGet("{username}/credential-options")]
[HttpGet("credential-options")]
public CredentialCreateOptions GetCredentialOptions(
[FromRoute] string? username,
[FromQuery] string? displayName,
[FromQuery] AttestationConveyancePreference? attestationType,
[FromQuery] AuthenticatorAttachment? authenticator,
[FromQuery] UserVerificationRequirement? userVerification,
[FromQuery] ResidentKeyRequirement? residentKey)
{
try
{
var key = username;
if (string.IsNullOrEmpty(username))
{
var created = DateTime.UtcNow;
if (string.IsNullOrEmpty(displayName))
{
// More precise generated name for less collisions in _pendingCredentials
username = $"(Usernameless user created {created})";
}
else
{
// Less precise but nicer for user if there's a displayName set anyway
username = $"{displayName} (Usernameless user created {created.ToShortDateString()})";
}
key = Convert.ToBase64String(Encoding.UTF8.GetBytes(username));
}
Debug.Assert(key != null); // If it was null before, it was set to the base64 value. Analyzer doesn't understand this though.
// 1. Get user from DB by username (in our example, auto create missing users)
var user = _demoStorage.GetOrAddUser(username, () => new Fido2User
{
DisplayName = displayName,
Name = username,
Id = Encoding.UTF8.GetBytes(username) // byte representation of userID is required
});
// 2. Get user existing keys by username
var existingKeys = _demoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();
// 3. Build authenticator selection
var authenticatorSelection = AuthenticatorSelection.Default;
if (authenticator != null)
{
authenticatorSelection.AuthenticatorAttachment = authenticator;
}
if (userVerification != null)
{
authenticatorSelection.UserVerification = userVerification.Value;
}
if (residentKey != null)
{
authenticatorSelection.ResidentKey = residentKey.Value;
}
// 4. Create options
var options = _fido2.RequestNewCredential(new RequestNewCredentialParams
{
User = user,
ExcludeCredentials = existingKeys,
AuthenticatorSelection = authenticatorSelection,
AttestationPreference = attestationType ?? AttestationConveyancePreference.None,
Extensions = new AuthenticationExtensionsClientInputs
{
Extensions = true,
UserVerificationMethod = true,
CredProps = true
}
});
// 5. Temporarily store options, session/in-memory cache/redis/db
_pendingCredentials[key] = options;
// 6. return options to client
return options;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Creates a new credential for a user.
/// </summary>
/// <param name="username">Username of registering user. If usernameless, use base64 encoded options.User.Name from the credential-options used to create the credential.</param>
/// <param name="attestationResponse"></param>
/// <param name="cancellationToken"></param>
/// <returns>a string containing either "OK" or an error message.</returns>
[HttpPut("{username}/credential")]
public async Task<string> CreateCredentialAsync([FromRoute] string username, [FromBody] AuthenticatorAttestationRawResponse attestationResponse, CancellationToken cancellationToken)
{
try
{
// 1. Get the options we sent the client
var options = _pendingCredentials[username];
// 2. Create callback so that lib can verify credential id is unique to this user
// 3. Verify and make the credentials
var credential = await _fido2.MakeNewCredentialAsync(new MakeNewCredentialParams
{
AttestationResponse = attestationResponse,
OriginalOptions = options,
IsCredentialIdUniqueToUserCallback = CredentialIdUniqueToUserAsync
}, cancellationToken: cancellationToken);
// 4. Store the credentials in db
_demoStorage.AddCredentialToUser(options.User, new StoredCredential
{
AttestationFormat = credential.AttestationFormat,
Id = credential.Id,
PublicKey = credential.PublicKey,
UserHandle = credential.User.Id,
SignCount = credential.SignCount,
RegDate = DateTimeOffset.UtcNow,
AaGuid = credential.AaGuid,
Transports = credential.Transports,
IsBackupEligible = credential.IsBackupEligible,
IsBackedUp = credential.IsBackedUp,
AttestationObject = credential.AttestationObject,
AttestationClientDataJson = credential.AttestationClientDataJson,
});
// 5. Now we need to remove the options from the pending dictionary
_pendingCredentials.Remove(Request.Host.ToString());
// 5. return OK to client
return "OK";
}
catch (Exception e)
{
return FormatException(e);
}
}
private static async Task<bool> CredentialIdUniqueToUserAsync(IsCredentialIdUniqueToUserParams args, CancellationToken cancellationToken)
{
var users = await _demoStorage.GetUsersByCredentialIdAsync(args.CredentialId, cancellationToken);
return users.Count <= 0;
}
[HttpGet("{username}/assertion-options")]
[HttpGet("assertion-options")]
public AssertionOptions MakeAssertionOptions([FromRoute] string? username, [FromQuery] UserVerificationRequirement? userVerification)
{
try
{
var existingKeys = new List<PublicKeyCredentialDescriptor>();
if (!string.IsNullOrEmpty(username))
{
// 1. Get user and their credentials from DB
var user = _demoStorage.GetUser(username);
if (user != null)
existingKeys = _demoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();
}
var exts = new AuthenticationExtensionsClientInputs
{
UserVerificationMethod = true,
Extensions = true
};
// 2. Create options (usernameless users will be prompted by their device to select a credential from their own list)
var options = _fido2.GetAssertionOptions(new GetAssertionOptionsParams
{
AllowedCredentials = existingKeys,
UserVerification = userVerification ?? UserVerificationRequirement.Discouraged,
Extensions = exts
});
// 4. Temporarily store options, session/in-memory cache/redis/db
_pendingAssertions[new string(options.Challenge.Select(b => (char)b).ToArray())] = options;
// 5. return options to client
return options;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Verifies an assertion response from a client, generating a new JWT for the user.
/// </summary>
/// <param name="clientResponse">The client's authenticator's response to the challenge.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Either a new JWT header or an error message.
/// Example successful response:
/// "Bearer eyyylmaooimtotallyatoken"
/// Example error response:
/// "Error: Invalid assertion"
/// </returns>
[HttpPost("assertion")]
public async Task<string> MakeAssertionAsync([FromBody] AuthenticatorAssertionRawResponse clientResponse,
CancellationToken cancellationToken)
{
try
{
// 1. Get the assertion options we sent the client remove them from memory so they can't be used again
var response = JsonSerializer.Deserialize<AuthenticatorResponse>(clientResponse.Response.ClientDataJson);
if (response is null)
{
return "Error: Could not deserialize client data";
}
var key = new string(response.Challenge.Select(b => (char)b).ToArray());
if (!_pendingAssertions.TryGetValue(key, out var options))
{
return "Error: Challenge not found, please get a new one via GET /{username?}/assertion-options";
}
_pendingAssertions.Remove(key);
// 2. Get registered credential from database
var creds = _demoStorage.GetCredentialById(clientResponse.RawId) ?? throw new Exception("Unknown credentials");
// 3. Make the assertion
var res = await _fido2.MakeAssertionAsync(new MakeAssertionParams
{
AssertionResponse = clientResponse,
OriginalOptions = options,
StoredPublicKey = creds.PublicKey,
StoredSignatureCounter = creds.SignCount,
IsUserHandleOwnerOfCredentialIdCallback = UserHandleOwnerOfCredentialIdAsync
}, cancellationToken: cancellationToken);
// 4. Store the updated counter
_demoStorage.UpdateCounter(res.CredentialId, res.SignCount);
// 5. return result to client
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateEncodedJwt(
HttpContext.Request.Host.Host,
HttpContext.Request.Headers.Referer,
new ClaimsIdentity(new Claim[] { new(ClaimTypes.Actor, Encoding.UTF8.GetString(creds.UserHandle)) }),
DateTime.Now.Subtract(TimeSpan.FromMinutes(1)),
DateTime.Now.AddDays(1),
DateTime.Now,
_signingCredentials,
null);
if (token is null)
{
return "Error: Token couldn't be created";
}
return $"Bearer {token}";
}
catch (Exception e)
{
return $"Error: {FormatException(e)}";
}
}
private static async Task<bool> UserHandleOwnerOfCredentialIdAsync(IsUserHandleOwnerOfCredentialIdParams args, CancellationToken cancellationToken)
{
var storedCreds = await _demoStorage.GetCredentialsByUserHandleAsync(args.UserHandle, cancellationToken);
return storedCreds.Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId));
}
}