forked from passwordless-lib/fido2-net-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.cs
223 lines (185 loc) · 8.68 KB
/
Controller.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
using System.Text;
using Fido2NetLib;
using Fido2NetLib.Development;
using Fido2NetLib.Objects;
using Microsoft.AspNetCore.Mvc;
namespace Fido2Demo;
[Route("api/[controller]")]
public class MyController : Controller
{
private IFido2 _fido2;
public static IMetadataService _mds;
public static readonly DevelopmentInMemoryStore DemoStorage = new();
public MyController(IFido2 fido2)
{
_fido2 = fido2;
}
private string FormatException(Exception e)
{
return string.Format("{0}{1}", e.Message, e.InnerException != null ? " (" + e.InnerException.Message + ")" : "");
}
[HttpPost]
[Route("/makeCredentialOptions")]
public JsonResult MakeCredentialOptions([FromForm] string username,
[FromForm] string displayName,
[FromForm] string attType,
[FromForm] string authType,
[FromForm] string residentKey,
[FromForm] string userVerification)
{
try
{
if (string.IsNullOrEmpty(username))
{
username = $"{displayName} (Usernameless user created at {DateTime.UtcNow})";
}
// 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. Create options
var authenticatorSelection = new AuthenticatorSelection
{
ResidentKey = residentKey.ToEnum<ResidentKeyRequirement>(),
UserVerification = userVerification.ToEnum<UserVerificationRequirement>()
};
if (!string.IsNullOrEmpty(authType))
authenticatorSelection.AuthenticatorAttachment = authType.ToEnum<AuthenticatorAttachment>();
var exts = new AuthenticationExtensionsClientInputs()
{
Extensions = true,
UserVerificationMethod = true,
DevicePubKey = new AuthenticationExtensionsDevicePublicKeyInputs() { Attestation = attType },
CredProps = true
};
var options = _fido2.RequestNewCredential(user, existingKeys, authenticatorSelection, attType.ToEnum<AttestationConveyancePreference>(), exts);
// 4. Temporarily store options, session/in-memory cache/redis/db
HttpContext.Session.SetString("fido2.attestationOptions", options.ToJson());
// 5. return options to client
return Json(options);
}
catch (Exception e)
{
return Json(new { Status = "error", ErrorMessage = FormatException(e) });
}
}
[HttpPost]
[Route("/makeCredential")]
public async Task<JsonResult> MakeCredential([FromBody] AuthenticatorAttestationRawResponse attestationResponse, CancellationToken cancellationToken)
{
try
{
// 1. get the options we sent the client
var jsonOptions = HttpContext.Session.GetString("fido2.attestationOptions");
var options = CredentialCreateOptions.FromJson(jsonOptions);
// 2. Create callback so that lib can verify credential id is unique to this user
IsCredentialIdUniqueToUserAsyncDelegate callback = static async (args, cancellationToken) =>
{
var users = await DemoStorage.GetUsersByCredentialIdAsync(args.CredentialId, cancellationToken);
if (users.Count > 0)
return false;
return true;
};
// 2. Verify and make the credentials
var credential = await _fido2.MakeNewCredentialAsync(attestationResponse, options, callback, cancellationToken: cancellationToken);
// 3. Store the credentials in db
DemoStorage.AddCredentialToUser(options.User, new StoredCredential
{
Id = credential.Id,
PublicKey = credential.PublicKey,
UserHandle = credential.User.Id,
SignCount = credential.SignCount,
AttestationFormat = credential.AttestationFormat,
RegDate = DateTimeOffset.UtcNow,
AaGuid = credential.AaGuid,
Transports = credential.Transports,
IsBackupEligible = credential.IsBackupEligible,
IsBackedUp = credential.IsBackedUp,
AttestationObject = credential.AttestationObject,
AttestationClientDataJson = credential.AttestationClientDataJson,
DevicePublicKeys = [credential.DevicePublicKey]
});
// 4. return "ok" to the client
return Json(credential);
}
catch (Exception e)
{
return Json(new { status = "error", errorMessage = FormatException(e) });
}
}
[HttpPost]
[Route("/assertionOptions")]
public ActionResult AssertionOptionsPost([FromForm] string username, [FromForm] string userVerification)
{
try
{
var existingCredentials = new List<PublicKeyCredentialDescriptor>();
if (!string.IsNullOrEmpty(username))
{
// 1. Get user from DB
var user = DemoStorage.GetUser(username) ?? throw new ArgumentException("Username was not registered");
// 2. Get registered credentials from database
existingCredentials = DemoStorage.GetCredentialsByUser(user).Select(c => c.Descriptor).ToList();
}
var exts = new AuthenticationExtensionsClientInputs()
{
Extensions = true,
UserVerificationMethod = true,
DevicePubKey = new AuthenticationExtensionsDevicePublicKeyInputs()
};
// 3. Create options
var uv = string.IsNullOrEmpty(userVerification) ? UserVerificationRequirement.Discouraged : userVerification.ToEnum<UserVerificationRequirement>();
var options = _fido2.GetAssertionOptions(
existingCredentials,
uv,
exts
);
// 4. Temporarily store options, session/in-memory cache/redis/db
HttpContext.Session.SetString("fido2.assertionOptions", options.ToJson());
// 5. Return options to client
return Json(options);
}
catch (Exception e)
{
return Json(new { Status = "error", ErrorMessage = FormatException(e) });
}
}
[HttpPost]
[Route("/makeAssertion")]
public async Task<JsonResult> MakeAssertion([FromBody] AuthenticatorAssertionRawResponse clientResponse, CancellationToken cancellationToken)
{
try
{
// 1. Get the assertion options we sent the client
var jsonOptions = HttpContext.Session.GetString("fido2.assertionOptions");
var options = AssertionOptions.FromJson(jsonOptions);
// 2. Get registered credential from database
var creds = DemoStorage.GetCredentialById(clientResponse.Id) ?? throw new Exception("Unknown credentials");
// 3. Get credential counter from database
var storedCounter = creds.SignCount;
// 4. Create callback to check if the user handle owns the credentialId
IsUserHandleOwnerOfCredentialIdAsync callback = static async (args, cancellationToken) =>
{
var storedCreds = await DemoStorage.GetCredentialsByUserHandleAsync(args.UserHandle, cancellationToken);
return storedCreds.Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId));
};
// 5. Make the assertion
var res = await _fido2.MakeAssertionAsync(clientResponse, options, creds.PublicKey, creds.DevicePublicKeys, storedCounter, callback, cancellationToken: cancellationToken);
// 6. Store the updated counter
DemoStorage.UpdateCounter(res.CredentialId, res.SignCount);
if (res.DevicePublicKey is not null)
creds.DevicePublicKeys.Add(res.DevicePublicKey);
// 7. return OK to client
return Json(res);
}
catch (Exception e)
{
return Json(new { Status = "error", ErrorMessage = FormatException(e) });
}
}
}