using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; //Builder configuration var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddControllers(); builder.Services.AddControllersWithViews(); builder.Services.AddCors(options => { options.AddPolicy("AllowAllOrigins", corsBuilder => { corsBuilder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // JWT Configuration var jwtSettings = builder.Configuration.GetSection("Jwt"); var key = jwtSettings["Key"]; var issuer = jwtSettings["Issuer"]; var audience = jwtSettings["Audience"]; if (string.IsNullOrEmpty(key)) { return; } builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = issuer, ValidAudience = audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) }; }); // Build var app = builder.Build(); // App configuration app.MapControllers(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseCors("AllowAllOrigins"); app.Run();