1
+ using System . IdentityModel . Tokens . Jwt ;
2
+ using System . Security . Claims ;
3
+ using System . Text ;
4
+ using BusinessLogic . Configs ;
5
+ using Microsoft . Extensions . Options ;
6
+ using Microsoft . IdentityModel . Tokens ;
7
+
8
+ namespace BusinessLogic . Jwt ;
9
+
10
+ public interface IJwtGeneratorService
11
+ {
12
+ JwtGenerationResult GenerateToken ( Guid userId ) ;
13
+ }
14
+
15
+ public class JwtGeneratorService : IJwtGeneratorService
16
+ {
17
+ private readonly JwtConfig _config ;
18
+
19
+ private static readonly JwtSecurityTokenHandler JwtSecurityTokenHandler = new ( ) ;
20
+
21
+ public JwtGeneratorService ( IOptions < JwtConfig > options )
22
+ {
23
+ _config = options . Value ;
24
+ }
25
+
26
+ public JwtGenerationResult GenerateToken ( Guid userId )
27
+ {
28
+ var issuer = _config . Issuer ;
29
+ var audience = _config . Audience ;
30
+
31
+ var key = Encoding . ASCII . GetBytes ( _config . Key ) ;
32
+
33
+ var signingCredentials = new SigningCredentials ( new SymmetricSecurityKey ( key ) , SecurityAlgorithms . HmacSha256 ) ;
34
+
35
+ var tokenJwt = new JwtSecurityToken (
36
+ issuer : issuer ,
37
+ audience : audience ,
38
+ notBefore : null ,
39
+ claims : new [ ]
40
+ {
41
+ new Claim ( KnownJwtClaims . UserId , userId . ToString ( ) ) ,
42
+ // the JTI is used for our refresh token which we will be covering in the next video
43
+ new Claim (
44
+ JwtRegisteredClaimNames . Jti ,
45
+ Guid . NewGuid ( )
46
+ . ToString ( )
47
+ )
48
+ } ,
49
+ expires : DateTime . UtcNow . AddSeconds ( _config . LifetimeSeconds ) ,
50
+ signingCredentials : signingCredentials
51
+ ) ;
52
+
53
+ var refreshJwt = new JwtSecurityToken (
54
+ issuer : issuer ,
55
+ audience : audience ,
56
+ notBefore : null ,
57
+ claims : new [ ]
58
+ {
59
+ new Claim ( KnownJwtClaims . UserId , userId . ToString ( ) ) ,
60
+ // the JTI is used for our refresh token which we will be covering in the next video
61
+ new Claim (
62
+ JwtRegisteredClaimNames . Jti ,
63
+ Guid . NewGuid ( )
64
+ . ToString ( )
65
+ )
66
+ } ,
67
+ expires : DateTime . UtcNow . AddSeconds ( _config . LifetimeSeconds ) ,
68
+ signingCredentials : signingCredentials
69
+ ) ;
70
+
71
+ var token = JwtSecurityTokenHandler . WriteToken ( tokenJwt ) ;
72
+ var refreshToken = JwtSecurityTokenHandler . WriteToken ( refreshJwt ) ;
73
+
74
+ return new ( token , refreshToken ) ;
75
+ }
76
+ }
0 commit comments