1
1
using System ;
2
2
using System . Collections . Generic ;
3
- using System . IdentityModel . Tokens . Jwt ;
4
3
using System . Security . Claims ;
5
4
using System . Security . Cryptography ;
5
+ using Microsoft . IdentityModel . JsonWebTokens ;
6
6
using Microsoft . IdentityModel . Tokens ;
7
7
using Xunit ;
8
8
9
9
namespace ScottBrady91 . BlogExampleCode . RsaPssJwtSigning
10
10
{
11
11
public class Program
12
12
{
13
- private static readonly JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler ( ) ;
13
+ private static readonly JsonWebTokenHandler handler = new JsonWebTokenHandler ( ) ;
14
14
private static readonly RsaSecurityKey key = new RsaSecurityKey ( RSA . Create ( 2048 ) ) ;
15
15
private static readonly DateTime now = DateTime . UtcNow ;
16
16
@@ -34,25 +34,23 @@ public static void Main(string[] args)
34
34
35
35
private static string CreatePssToken ( )
36
36
{
37
- var jwt = handler . CreateEncodedJwt ( descriptor ) ;
37
+ var jwt = handler . CreateToken ( descriptor ) ;
38
38
Console . WriteLine ( jwt ) ;
39
39
40
40
return jwt ;
41
41
}
42
42
43
43
private static void ValidatePssToken ( string jwt )
44
44
{
45
- var claimsPrincipal = handler . ValidateToken (
46
- jwt ,
45
+ var result = handler . ValidateToken ( jwt ,
47
46
new TokenValidationParameters
48
47
{
49
48
ValidIssuer = descriptor . Issuer , // "me"
50
49
ValidAudience = descriptor . Audience , // "you"
51
50
IssuerSigningKey = new RsaSecurityKey ( key . Rsa . ExportParameters ( false ) ) // public key
52
- } ,
53
- out SecurityToken parsedToken ) ;
51
+ } ) ;
54
52
55
- if ( ! claimsPrincipal . Identity . IsAuthenticated ) throw new Exception ( "It's all gone wrong" ) ;
53
+ if ( ! result . IsValid ) throw new Exception ( "It's all gone wrong" ) ;
56
54
Console . WriteLine ( "Token Validated!" ) ;
57
55
}
58
56
@@ -61,8 +59,8 @@ public void WhenGeneratedWithDeterministicSignatureScheme_ExpectIdenticalJwts()
61
59
{
62
60
descriptor . SigningCredentials = new SigningCredentials ( key , "RS256" ) ;
63
61
64
- var token1 = handler . CreateEncodedJwt ( descriptor ) ;
65
- var token2 = handler . CreateEncodedJwt ( descriptor ) ;
62
+ var token1 = handler . CreateToken ( descriptor ) ;
63
+ var token2 = handler . CreateToken ( descriptor ) ;
66
64
67
65
Assert . Equal ( token1 , token2 ) ;
68
66
}
@@ -72,8 +70,8 @@ public void WhenGeneratedWithProbabilisticSignatureScheme_ExpectDifferentJwts()
72
70
{
73
71
descriptor . SigningCredentials = new SigningCredentials ( key , "PS256" ) ;
74
72
75
- var token1 = handler . CreateEncodedJwt ( descriptor ) ;
76
- var token2 = handler . CreateEncodedJwt ( descriptor ) ;
73
+ var token1 = handler . CreateToken ( descriptor ) ;
74
+ var token2 = handler . CreateToken ( descriptor ) ;
77
75
78
76
Assert . NotEqual ( token1 , token2 ) ;
79
77
}
0 commit comments