4
4
using Microsoft . Extensions . Configuration ;
5
5
using Microsoft . Extensions . DependencyInjection ;
6
6
using Microsoft . OpenApi . Models ;
7
- using System . Collections . Generic ;
8
7
using DataAccess ;
9
8
using MongoDB . Driver ;
10
9
using Domain . Repositories ;
14
13
using System . Security . Cryptography ;
15
14
using System ;
16
15
using Microsoft . AspNetCore . Authentication . JwtBearer ;
16
+ using Microsoft . AspNetCore . DataProtection ;
17
+ using System . IO ;
18
+ using System . Threading . Tasks ;
19
+ using System . Text . Json ;
17
20
18
21
namespace IoCConfig
19
22
{
@@ -59,9 +62,40 @@ public static void AddCustomAuthentication(this IServiceCollection services, ICo
59
62
ValidAudience = configuration [ "Jwt:Audience" ] ,
60
63
IssuerSigningKey = new RsaSecurityKey ( rsa )
61
64
} ;
65
+
66
+ options . Events = new JwtBearerEvents
67
+ {
68
+ OnMessageReceived = context =>
69
+ {
70
+ if ( context . Request . Cookies . TryGetValue ( configuration [ "Jwt:CookieName" ] , out var encryptedToken ) )
71
+ {
72
+ var dataProtector = context . HttpContext . RequestServices
73
+ . GetRequiredService < IDataProtectionProvider > ( )
74
+ . CreateProtector ( configuration [ "Jwt:DataProtectionPurpose" ] ) ;
75
+
76
+ try
77
+ {
78
+ var authCookie = JsonSerializer . Deserialize < AuthCookie > ( dataProtector . Unprotect ( encryptedToken ) ) ;
79
+ context . Token = authCookie . AccessToken ;
80
+ }
81
+ catch
82
+ {
83
+ context . Fail ( "Invalid or tampered token" ) ;
84
+ }
85
+ }
86
+
87
+ return Task . CompletedTask ;
88
+ }
89
+ } ;
62
90
} ) ;
63
91
}
64
92
93
+ public static void AddCustomDataProtection ( this IServiceCollection services , IConfiguration configuration )
94
+ {
95
+ services . AddDataProtection ( )
96
+ . PersistKeysToFileSystem ( new DirectoryInfo ( configuration [ "Jwt:DataProtectionKeysPath" ] ) )
97
+ . SetApplicationName ( configuration [ "Jwt:DataProtectionApplicationName" ] ) ;
98
+ }
65
99
public static void AddCustomServices ( this IServiceCollection services )
66
100
{
67
101
services . AddScoped < IJwtTokenService , JwtTokenService > ( ) ;
@@ -87,17 +121,6 @@ public static void AddCustomSwagger(this IServiceCollection services)
87
121
Title = "Micro IDP API Document" ,
88
122
Version = "v1"
89
123
} ) ;
90
-
91
- options . AddSecurityDefinition ( "Bearer" , new OpenApiSecurityScheme
92
- {
93
- Description = @"JWT Authorization header using the Bearer scheme." ,
94
- Name = "Authorization" ,
95
- In = ParameterLocation . Header ,
96
- Type = SecuritySchemeType . ApiKey ,
97
- Scheme = "Bearer"
98
- } ) ;
99
-
100
- options . AddSecurityRequirement ( new OpenApiSecurityRequirement ( ) { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType . SecurityScheme , Id = "Bearer" } , Scheme = "oauth2" , Name = "Bearer" , In = ParameterLocation . Header , } , new List < string > ( ) } } ) ;
101
124
} ) ;
102
125
}
103
126
0 commit comments