11using System . Reflection ;
2+ using System . Text ;
23using Kairos . Account . Configuration ;
34using Kairos . Account . Domain ;
45using Kairos . Account . Infra ;
56using Kairos . Account . Infra . Consumers ;
67using Kairos . Shared . Contracts . Account ;
78using MassTransit ;
9+ using Microsoft . AspNetCore . Authentication . JwtBearer ;
810using Microsoft . AspNetCore . Identity ;
911using Microsoft . EntityFrameworkCore ;
1012using Microsoft . Extensions . Configuration ;
1113using Microsoft . Extensions . DependencyInjection ;
14+ using Microsoft . Extensions . Options ;
15+ using Microsoft . IdentityModel . Tokens ;
1216
1317namespace Kairos . Account ;
1418
@@ -21,6 +25,7 @@ public static IServiceCollection AddAccount(
2125 services . Configure < Settings > ( config ) ;
2226
2327 return services
28+ . AddAuth ( )
2429 . AddIdentity ( config )
2530 . AddMediatR ( cfg =>
2631 {
@@ -89,4 +94,45 @@ static IServiceCollection AddIdentity(
8994
9095 return services ;
9196 }
97+
98+ static IServiceCollection AddAuth ( this IServiceCollection services )
99+ {
100+ var jwt = services
101+ . BuildServiceProvider ( )
102+ . GetRequiredService < IOptions < Settings > > ( )
103+ . Value . Jwt ;
104+
105+ services
106+ . AddAuthentication ( o =>
107+ {
108+ o . DefaultAuthenticateScheme = JwtBearerDefaults . AuthenticationScheme ;
109+ o . DefaultChallengeScheme = JwtBearerDefaults . AuthenticationScheme ;
110+ } )
111+ . AddJwtBearer ( o =>
112+ {
113+ o . TokenValidationParameters = new TokenValidationParameters
114+ {
115+ ValidateIssuer = true ,
116+ ValidateAudience = true ,
117+ ValidateLifetime = true ,
118+ ValidateIssuerSigningKey = true ,
119+ ValidIssuer = jwt . Issuer ,
120+ ValidAudience = jwt . Audience ,
121+ IssuerSigningKey = new SymmetricSecurityKey ( Encoding . UTF8 . GetBytes ( jwt . Secret ) )
122+ } ;
123+
124+ o . Events = new JwtBearerEvents
125+ {
126+ OnMessageReceived = context =>
127+ {
128+ context . Token = context . Request . Cookies [ jwt . CookieName ] ;
129+ return Task . CompletedTask ;
130+ }
131+ } ;
132+ } ) ;
133+
134+ services . AddAuthorization ( ) ;
135+
136+ return services ;
137+ }
92138}
0 commit comments