| | 1 | | using Microsoft.AspNetCore.Authentication.Cookies; |
| | 2 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 3 | | using Microsoft.IdentityModel.Tokens; |
| | 4 | | using MRA.Infrastructure.Settings.Options; |
| | 5 | | using System.Text; |
| | 6 | |
|
| | 7 | | namespace MRA.WebApi.Startup; |
| | 8 | |
|
| | 9 | | public static class AuthenticationStartup |
| | 10 | | { |
| | 11 | | public static void AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration) |
| | 12 | | { |
| 0 | 13 | | var jwtSection = configuration.GetSection("Jwt"); |
| 0 | 14 | | services.Configure<JwtSettings>(jwtSection); |
| | 15 | |
|
| 0 | 16 | | var jwtOptions = jwtSection.Get<JwtSettings>(); |
| | 17 | |
|
| 0 | 18 | | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 0 | 19 | | .AddJwtBearer(options => |
| 0 | 20 | | { |
| 0 | 21 | | options.TokenValidationParameters = new TokenValidationParameters |
| 0 | 22 | | { |
| 0 | 23 | | ValidateIssuer = true, |
| 0 | 24 | | ValidateAudience = true, |
| 0 | 25 | | ValidateLifetime = true, |
| 0 | 26 | | ValidateIssuerSigningKey = true, |
| 0 | 27 | | ValidIssuer = jwtOptions.Issuer, |
| 0 | 28 | | ValidAudience = jwtOptions.Audience, |
| 0 | 29 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.Key)) |
| 0 | 30 | | }; |
| 0 | 31 | | options.Events = new JwtBearerEvents |
| 0 | 32 | | { |
| 0 | 33 | | OnAuthenticationFailed = context => |
| 0 | 34 | | { |
| 0 | 35 | | Console.WriteLine($"Authentication failed: {context.Exception.Message}"); |
| 0 | 36 | | return Task.CompletedTask; |
| 0 | 37 | | }, |
| 0 | 38 | | OnChallenge = context => |
| 0 | 39 | | { |
| 0 | 40 | | Console.WriteLine("Token validation failed."); |
| 0 | 41 | | return Task.CompletedTask; |
| 0 | 42 | | } |
| 0 | 43 | | }; |
| 0 | 44 | | }); |
| | 45 | |
|
| | 46 | | //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) |
| | 47 | | // .AddCookie("Cookies", options => |
| | 48 | | // { |
| | 49 | | // options.Cookie.Name = "CookieMiguelRomeral"; |
| | 50 | | // options.LoginPath = "/Admin/Login"; |
| | 51 | | // }); |
| | 52 | |
|
| 0 | 53 | | services.AddAuthorization(); |
| 0 | 54 | | } |
| | 55 | | } |