-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathCustomJwtDataFormat.cs
More file actions
57 lines (51 loc) · 2.19 KB
/
CustomJwtDataFormat.cs
File metadata and controls
57 lines (51 loc) · 2.19 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
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
//using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.IdentityModel.Tokens;
namespace SampleWeb.Authentication
{
public class CustomJwtDataFormat : ISecureDataFormat<AuthenticationTicket> {
private readonly string _algorithm;
private readonly TokenValidationParameters _validationParameters;
public CustomJwtDataFormat(string algorithm, TokenValidationParameters validationParameters) {
_algorithm = algorithm;
_validationParameters = validationParameters;
}
public AuthenticationTicket Unprotect(string protectedText)
=> Unprotect(protectedText, null);
public AuthenticationTicket Unprotect(string protectedText, string purpose) {
var handler = new JwtSecurityTokenHandler();
handler.InboundClaimTypeMap[JwtRegisteredClaimNames.Sub] = ClaimTypes.Name;
ClaimsPrincipal principal;
try {
SecurityToken validToken;
principal = handler.ValidateToken(protectedText, _validationParameters, out validToken);
var validJwt = validToken as JwtSecurityToken;
if (validJwt == null) {
throw new ArgumentException("Invalid JWT");
}
if (!validJwt.Header.Alg.Equals(_algorithm, StringComparison.Ordinal)) {
throw new ArgumentException($"Algorithm must be '{_algorithm}'");
}
}
catch (SecurityTokenValidationException) {
return null;
}
catch (ArgumentException) {
return null;
}
return new AuthenticationTicket(principal, new AuthenticationProperties(), "Cookie");
}
public string Protect(AuthenticationTicket data) {
throw new NotImplementedException();
}
public string Protect(AuthenticationTicket data, string purpose) {
throw new NotImplementedException();
}
}
}