-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
61 lines (52 loc) · 1.89 KB
/
Program.cs
File metadata and controls
61 lines (52 loc) · 1.89 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
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using JwtGenerator;
using JwtGenerator.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddUserSecrets<Program>()
.Build();
var services = new ServiceCollection();
services.AddSingleton<JwtSecurityTokenService>()
.AddLogging(builder => builder.AddConsole())
.Configure<GreenTinOptions>(config.GetSection(nameof(GreenTinOptions)));
var provider = services.BuildServiceProvider();
var jwtSecurity = provider.GetRequiredService<JwtSecurityTokenService>();
var logger = provider.GetRequiredService<ILogger<Program>>();
try
{
var options = provider.GetRequiredService<IOptions<GreenTinOptions>>().Value.Jwt;
var emailClaim = new Claim("email", "john.doe@larch.com");
var token = jwtSecurity.CreateToken(
options.Audience,
options.Issuer,
options.PrivateKey,
options.ExpiryInMinutes,
emailClaim);
logger.LogInformation("{Token}", token);
var principal = jwtSecurity.ValidateToken(token, options.Audience, options.Issuer, options.PublicKey);
logger.LogInformation("Validated {Uid}:", principal.FindFirst(c => c.Type == "uid"));
}
catch (NotSupportedException e)
{
logger.LogError(e, "Not supported to process token");
}
catch (ArgumentException e)
{
logger.LogError(e, "Failed to process token");
}
catch (SecurityTokenSignatureKeyNotFoundException e)
{
logger.LogError(e, "Failed to process token");
}
catch (SecurityTokenExpiredException e)
{
logger.LogError(e, "Failed to process expired token");
}
// ReSharper disable once ClassNeverInstantiated.Global
public partial class Program;