token 的解讀與驗證

 

範例程式碼如下

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 Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Sockets;
using System.Security.Claims;
using System.Text;

//{
// "alg": "HS256",
// "typ": "JWT"
//}.
//{
// "iss": "https://appleid.apple.com",
// "aud": "com.your.app.id",
// "exp": 1696621649,
// "iat": 1596621049,
// "sub": "001451.3dc436155xxxxxxxxxxxxxxxxxxxx59f.0447",
// "c_hash": "iUqI9Vyxxxxxxxxxg-CyoA",
// "email": "8m2xxxxmew@privaterelay.appleid.com",
// "email_verified": "true",
// "is_private_email": "true",
// "auth_time": 1596621049,
// "nonce_supported": true
//}

string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLnlvdXIuYXBwLmlkIiwiZXhwIjoxNjk2NjIxNjQ5LCJpYXQiOjE1OTY2MjEwNDksInN1YiI6IjAwMTQ1MS4zZGM0MzYxNTV4eHh4eHh4eHh4eHh4eHh4eHh4eDU5Zi4wNDQ3IiwiY19oYXNoIjoiaVVxSTlWeXh4eHh4eHh4eGctQ3lvQSIsImVtYWlsIjoiOG0yeHh4eG1ld0Bwcml2YXRlcmVsYXkuYXBwbGVpZC5jb20iLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJpc19wcml2YXRlX2VtYWlsIjoidHJ1ZSIsImF1dGhfdGltZSI6MTU5NjYyMTA0OSwibm9uY2Vfc3VwcG9ydGVkIjp0cnVlfQ.4h_6jxfGUbsQHPHFZ9EaSAR_eaDLgPFFoYhgDfEaNLc";

//一、token 解讀
try
{
JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
}
catch (Exception ex)
{
throw ex;
}

//二、token 驗證
try
{
string secret = "your-256-bit-secret";
ClaimsPrincipal principal = new JwtSecurityTokenHandler()
.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://appleid.apple.com",
ValidateAudience = true,
ValidAudience = "com.your.app.id",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
}, out var validatedToken);
}
catch (Exception ex)
{
throw ex;
}

Console.WriteLine();