-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIssuerController.cs
More file actions
386 lines (369 loc) · 17.9 KB
/
IssuerController.cs
File metadata and controls
386 lines (369 loc) · 17.9 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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http.Extensions;
namespace AspNetCoreVerifiableCredentials
{
[Route("api/[controller]/[action]")]
[ApiController]
public class IssuerController : ControllerBase
{
protected IMemoryCache _cache;
protected readonly ILogger<IssuerController> _log;
private IHttpClientFactory _httpClientFactory;
private IConfiguration _configuration;
private string _apiKey;
public IssuerController(IConfiguration configuration, IMemoryCache memoryCache, ILogger<IssuerController> log, IHttpClientFactory httpClientFactory)
{
_cache = memoryCache;
_log = log;
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_apiKey = System.Environment.GetEnvironmentVariable("API-KEY");
}
private IssuanceRequest SetClaims(IssuanceRequest request)
{
request.claims = new Dictionary<string, string>();
request.claims.Add("given_name", "Megan");
request.claims.Add("family_name", "Bowen");
string photoClaimName = "";
// get photo claim from manifest
if (GetCredentialManifest(out string manifest, out string error))
{
JObject jsonManifest = JObject.Parse(manifest);
foreach (var claim in jsonManifest["display"]["claims"])
{
string claimName = ((JProperty)claim).Name;
if (jsonManifest["display"]["claims"][claimName]["type"].ToString() == "image/jpg;base64url")
{
photoClaimName = claimName.Replace("vc.credentialSubject.", "");
}
}
}
if (!string.IsNullOrWhiteSpace(photoClaimName))
{
// if we have a photoId in the Session
string photoId = this.Request.Headers["rsid"];
if (!string.IsNullOrWhiteSpace(photoId))
{
// if we have a photo in-mem cache
if (_cache.TryGetValue(photoId, out string photo))
{
_log.LogTrace($"Adding user photo to credential. photoId: {photoId}");
request.claims.Add(photoClaimName, photo);
}
else
{
_log.LogTrace($"Couldn't find a user photo to add to credential. photoId: {photoId}");
}
}
}
return request;
}
/// <summary>
/// This method is called from the UI to initiate the issuance of the verifiable credential
/// </summary>
/// <returns>JSON object with the address to the presentation request and optionally a QR code and a state value which can be used to check on the response status</returns>
[AllowAnonymous]
[HttpGet("/api/issuer/issuance-request")]
public async Task<ActionResult> IssuanceRequest()
{
_log.LogTrace(this.HttpContext.Request.GetDisplayUrl());
try
{
string manifestUrl = _configuration["VerifiedID:CredentialManifest"];
if (string.IsNullOrWhiteSpace(manifestUrl))
{
string errmsg = $"Manifest missing in config file";
_log.LogError(errmsg);
return BadRequest(new { error = "400", error_description = errmsg });
}
string tenantId = _configuration["VerifiedID:TenantId"];
string manifestTenantId = manifestUrl.Split("/")[5];
if (manifestTenantId != tenantId)
{
string errmsg = $"TenantId in ManifestURL {manifestTenantId}. does not match tenantId in config file {tenantId}";
_log.LogError(errmsg);
return BadRequest(new { error = "400", error_description = errmsg });
}
try
{
//The VC Request API is an authenticated API. We need to clientid and secret (or certificate) to create an access token which
//needs to be send as bearer to the VC Request API
var accessToken = await MsalAccessTokenHandler.GetAccessToken(_configuration);
if (accessToken.Item1 == String.Empty)
{
_log.LogError(String.Format("failed to acquire accesstoken: {0} : {1}", accessToken.error, accessToken.error_description));
return BadRequest(new { error = accessToken.error, error_description = accessToken.error_description });
}
IssuanceRequest request = CreateIssuanceRequest();
// If the credential uses the idTokenHint attestation flow, then you must set the claims before
// calling the Request Service API
SetClaims(request);
string jsonString = JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
_log.LogTrace($"Request API payload: {jsonString}");
var client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.token);
string url = $"{_configuration["VerifiedID:ApiEndpoint"]}createIssuanceRequest";
HttpResponseMessage res = await client.PostAsync(url, new StringContent(jsonString, Encoding.UTF8, "application/json"));
string response = await res.Content.ReadAsStringAsync();
if (res.StatusCode == HttpStatusCode.Created)
{
_log.LogTrace("succesfully called Request API");
JObject requestConfig = JObject.Parse(response);
if (request.pin != null) { requestConfig["pin"] = request.pin.value; }
requestConfig.Add(new JProperty("id", request.callback.state));
jsonString = JsonConvert.SerializeObject(requestConfig);
//We use in memory cache to keep state about the request. The UI will check the state when calling the presentationResponse method
var cacheData = new
{
status = "request_created",
message = "Waiting for QR code to be scanned",
expiry = requestConfig["expiry"].ToString()
};
_cache.Set(request.callback.state, JsonConvert.SerializeObject(cacheData)
, DateTimeOffset.Now.AddSeconds(_configuration.GetValue<int>("AppSettings:CacheExpiresInSeconds", 300)));
return new ContentResult { ContentType = "application/json", Content = jsonString };
}
else
{
_log.LogError("Unsuccesfully called Request API" + response);
return BadRequest(new { error = "400", error_description = "Something went wrong calling the API: " + response });
}
}
catch (Exception ex)
{
return BadRequest(new { error = "400", error_description = "Something went wrong calling the API: " + ex.Message });
}
}
catch (Exception ex)
{
return BadRequest(new { error = "400", error_description = ex.Message });
}
}
private bool GetCredentialManifest(out string manifest, out string error)
{
error = null;
if (!_cache.TryGetValue("manifest", out manifest))
{
string manifestUrl = _configuration["VerifiedID:CredentialManifest"];
if (string.IsNullOrWhiteSpace(manifestUrl))
{
error = $"Manifest missing in config file";
return false;
}
var client = _httpClientFactory.CreateClient();
HttpResponseMessage res = client.GetAsync(manifestUrl).Result;
string response = res.Content.ReadAsStringAsync().Result;
if (res.StatusCode != HttpStatusCode.OK)
{
error = $"HTTP status {(int)res.StatusCode} retrieving manifest from URL {manifestUrl}";
return false;
}
JObject resp = JObject.Parse(response);
string jwtToken = resp["token"].ToString();
jwtToken = jwtToken.Replace("_", "/").Replace("-", "+").Split(".")[1];
jwtToken = jwtToken.PadRight(4 * ((jwtToken.Length + 3) / 4), '=');
manifest = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(jwtToken));
_cache.Set("manifest", manifest);
}
return true;
}
[HttpGet("/api/issuer/get-manifest")]
public ActionResult getManifest()
{
_log.LogTrace(this.HttpContext.Request.GetDisplayUrl());
try
{
if (!GetCredentialManifest(out string manifest, out string errmsg))
{
_log.LogError(errmsg);
return BadRequest(new { error = "400", error_description = errmsg });
}
return new ContentResult { ContentType = "application/json", Content = manifest };
}
catch (Exception ex)
{
return BadRequest(new { error = "400", error_description = ex.Message });
}
}
[HttpGet("/api/issuer/selfie-request")]
public ActionResult SelfieRequest()
{
_log.LogTrace(this.HttpContext.Request.GetDisplayUrl());
try
{
string hostname = GetRequestHostName();
string id = Guid.NewGuid().ToString();
var request = new
{
id = id,
url = $"{hostname}/selfie.html?callbackUrl={hostname}/api/issuer/selfie/{id}",
expiry = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds(),
photo = "",
status = "request_created"
};
string resp = _cache.Set(id, JsonConvert.SerializeObject(request)
, DateTimeOffset.Now.AddSeconds(_configuration.GetValue<int>("AppSettings:CacheExpiresInSeconds", 300)));
return new ContentResult { StatusCode = (int)HttpStatusCode.Created, ContentType = "application/json", Content = resp };
}
catch (Exception ex)
{
return BadRequest(new { error = "400", error_description = ex.Message });
}
}
[AllowAnonymous]
[HttpPost("/api/issuer/userphoto")]
public ActionResult SetUserPhoto()
{
_log.LogTrace(this.HttpContext.Request.GetDisplayUrl());
try
{
string body = new System.IO.StreamReader(this.Request.Body).ReadToEndAsync().Result;
_log.LogTrace(body);
int idx = body.IndexOf(";base64,");
if (-1 == idx)
{
return BadRequest(new { error = "400", error_description = $"Image must be 'data:image/jpeg;base64,'" });
}
string photo = body.Substring(idx + 8);
string photoId = this.Request.Headers["rsid"];
int cacheSeconds = _configuration.GetValue<int>("AppSettings:CacheExpiresInSeconds", 300);
_cache.Set(photoId, photo, DateTimeOffset.Now.AddSeconds(cacheSeconds));
_log.LogTrace($"User set photo to add to credential. photoId: {photoId}");
return new ContentResult
{
StatusCode = (int)HttpStatusCode.Created,
ContentType = "application/json"
,
Content = JsonConvert.SerializeObject(new { id = photoId, message = $"Photo will be cached for {cacheSeconds} seconds" })
};
}
catch (Exception ex)
{
return BadRequest(new { error = "400", error_description = ex.Message });
}
}
//some helper functions
protected string GetRequestHostName()
{
string scheme = "https";// : this.Request.Scheme;
string originalHost = this.Request.Headers["x-original-host"];
string hostname = "";
if (!string.IsNullOrEmpty(originalHost))
hostname = string.Format("{0}://{1}", scheme, originalHost);
else hostname = string.Format("{0}://{1}", scheme, this.Request.Host);
return hostname;
}
protected bool IsMobile()
{
string userAgent = this.Request.Headers.UserAgent;
return (userAgent.Contains("Android") || userAgent.Contains("iPhone"));
}
private IssuanceRequest CreateIssuanceRequest(string stateId = null)
{
IssuanceRequest request = new IssuanceRequest()
{
includeQRCode = _configuration.GetValue("VerifiedID:includeQRCode", false),
authority = _configuration["VerifiedID:DidAuthority"],
registration = new Registration()
{
clientName = _configuration["VerifiedID:client_name"],
purpose = _configuration.GetValue("VerifiedID:purpose", "")
},
callback = new Callback()
{
url = $"{GetRequestHostName()}/api/issuer/issuecallback",
state = string.IsNullOrEmpty(stateId) ? Guid.NewGuid().ToString() : stateId,
headers = new Dictionary<string, string>() { { "api-key", this._apiKey } }
},
type = "ignore-this",
manifest = _configuration["VerifiedID:CredentialManifest"],
pin = null
};
if ("" == request.registration.purpose)
{
request.registration.purpose = null;
}
int issuancePinCodeLength = _configuration.GetValue("VerifiedID:IssuancePinCodeLength", 0);
// if pincode is required, set it up in the request
if (issuancePinCodeLength > 0 && !IsMobile())
{
int pinCode = RandomNumberGenerator.GetInt32(1, int.Parse("".PadRight(issuancePinCodeLength, '9')));
SetPinCode(request, string.Format("{0:D" + issuancePinCodeLength.ToString() + "}", pinCode));
}
SetExpirationDate(request);
return request;
}
private IssuanceRequest SetExpirationDate(IssuanceRequest request)
{
string credentialExpiration = _configuration.GetValue("VerifiedID:CredentialExpiration", "");
DateTime expDateUtc;
DateTime utcNow = DateTime.UtcNow;
// This is just examples for how to specify your own expiry dates
switch (credentialExpiration.ToUpperInvariant())
{
case "EOD":
expDateUtc = DateTime.UtcNow;
break;
case "EOW":
int start = (int)utcNow.DayOfWeek;
int target = (int)DayOfWeek.Sunday;
if (target <= start)
target += 7;
expDateUtc = utcNow.AddDays(target - start);
break;
case "EOM":
expDateUtc = new DateTime(utcNow.Year, utcNow.Month, DateTime.DaysInMonth(utcNow.Year, utcNow.Month));
break;
case "EOQ":
int quarterEndMonth = (int)(3 * Math.Ceiling((double)utcNow.Month / 3));
expDateUtc = new DateTime(utcNow.Year, quarterEndMonth, DateTime.DaysInMonth(utcNow.Year, quarterEndMonth));
break;
case "EOY":
expDateUtc = new DateTime(utcNow.Year, 12, 31);
break;
default:
return request;
}
// Remember that this date is expressed in UTC and Wallets/Authenticator displays the expiry date
// in local timezone. So for example, EOY will be displayed as "Jan 1" if the user is in a timezone
// east of GMT. Also, if you issue a VC that should expire 5pm locally, then you need to calculate
// what 5pm locally is in UTC time
request.expirationDate = $"{Convert.ToDateTime(expDateUtc).ToString("yyyy-MM-dd")}T23:59:59.000Z";
return request;
}
private IssuanceRequest SetPinCode(IssuanceRequest request, string pinCode = null)
{
_log.LogTrace("pin={0}", pinCode);
if (string.IsNullOrWhiteSpace(pinCode))
{
request.pin = null;
}
else
{
request.pin = new Pin()
{
length = pinCode.Length,
value = pinCode
};
}
return request;
}
}
}