-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathStructuredToken.cs
More file actions
57 lines (52 loc) · 1.68 KB
/
StructuredToken.cs
File metadata and controls
57 lines (52 loc) · 1.68 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.Text.Json;
using System.Text.Json.Serialization;
namespace GitCredentialManager.Authentication
{
public abstract class StructuredToken
{
private class JwtHeader
{
[JsonRequired]
[JsonInclude]
[JsonPropertyName("typ")]
public string Type { get; private set; }
}
private class JwtPayload : StructuredToken
{
[JsonRequired]
[JsonInclude]
[JsonPropertyName("exp")]
public long Expiry { get; private set; }
public override bool IsExpired
{
get
{
return Expiry < DateTimeOffset.Now.ToUnixTimeSeconds();
}
}
}
public abstract bool IsExpired { get; }
public static bool TryCreate(string value, out StructuredToken token)
{
try
{
// elements of JWT structure "<header>.<payload>.<signature>"
var parts = value.Split('.');
if (parts.Length == 3)
{
var header = JsonSerializer.Deserialize<JwtHeader>(Base64UrlConvert.Decode(parts[0]));
if ("JWT".Equals(header.Type, StringComparison.OrdinalIgnoreCase))
{
token = JsonSerializer.Deserialize<JwtPayload>(Base64UrlConvert.Decode(parts[1]));
return true;
}
}
}
catch { }
// invalid token data on content mismatch or deserializer exception
token = null;
return false;
}
}
}