| | | 1 | | namespace Nabs.Scenarios; |
| | | 2 | | |
| | | 3 | | public static class DependencyInversionExtensions |
| | | 4 | | { |
| | | 5 | | const string _bearerTokenSettingsSection = "BearerTokenSettings"; |
| | | 6 | | |
| | | 7 | | public static IHostApplicationBuilder AddServiceAuthentication( |
| | | 8 | | this IHostApplicationBuilder builder, |
| | | 9 | | Func<TokenValidatedContext, Task> onTokenValidated) |
| | | 10 | | { |
| | 0 | 11 | | builder.Services |
| | 0 | 12 | | .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| | 0 | 13 | | .AddJwtBearer(options => |
| | 0 | 14 | | { |
| | 0 | 15 | | var bearerTokenSettingsSection = builder.Configuration.GetRequiredSection(_bearerTokenSettingsSection); |
| | 0 | 16 | | var bearerTokenSettings = new BearerTokenSettings(); |
| | 0 | 17 | | bearerTokenSettingsSection.Bind(bearerTokenSettings); |
| | 0 | 18 | | |
| | 0 | 19 | | options.TokenValidationParameters = new() |
| | 0 | 20 | | { |
| | 0 | 21 | | ValidateIssuer = true, |
| | 0 | 22 | | ValidIssuer = bearerTokenSettings.Issuer, |
| | 0 | 23 | | ValidateAudience = true, |
| | 0 | 24 | | ValidAudience = bearerTokenSettings.Audience, |
| | 0 | 25 | | ValidateIssuerSigningKey = true, |
| | 0 | 26 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(bearerTokenSettings.Secret)), |
| | 0 | 27 | | ValidateLifetime = true, |
| | 0 | 28 | | ClockSkew = TimeSpan.FromMinutes(1) |
| | 0 | 29 | | }; |
| | 0 | 30 | | |
| | 0 | 31 | | options.Events = new() |
| | 0 | 32 | | { |
| | 0 | 33 | | OnTokenValidated = onTokenValidated |
| | 0 | 34 | | }; |
| | 0 | 35 | | }); |
| | | 36 | | |
| | 0 | 37 | | return builder; |
| | | 38 | | } |
| | | 39 | | } |