Program cs that allows authentication in cart&wishlist
Sat Jul 20 2024 12:29:24 GMT+0000 (Coordinated Universal Time)
Saved by @iamkatmakhafola
using av_motion_api.Data; using av_motion_api.Factory; using av_motion_api.Models; using av_motion_api.Interfaces; using av_motion_api.Services; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); // Configure the app environment ConfigurationManager configuration = builder.Configuration; builder.Configuration.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: false); builder.Host.ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); config.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true); }); // Configure logging builder.Logging.ClearProviders(); builder.Logging.AddConsole(); builder.Logging.AddDebug(); // CORS if (builder.Environment.IsDevelopment()) { builder.Services.AddCors(options => { options.AddPolicy("AllowAll", policy => { policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); } // Add services to the container builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve; }); // SQL builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddScoped<IRepository, Repository>(); builder.Services.AddIdentity<User, Role>(options => { options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = true; options.User.RequireUniqueEmail = true; }) .AddRoles<Role>() .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddCookie() .AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { context.Response.Headers.Add("Authentication-Failed", context.Exception.Message); return Task.CompletedTask; }, OnTokenValidated = context => { var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<StartupBase>>(); logger.LogInformation("Token validated for user: {0}", context.Principal.Identity.Name); return Task.CompletedTask; } }; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["Tokens:Issuer"], ValidAudience = builder.Configuration["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Tokens:Key"])) }; }); // Configure FormOptions for file uploads builder.Services.Configure<FormOptions>(o => { o.ValueLengthLimit = int.MaxValue; o.MultipartBodyLengthLimit = int.MaxValue; o.MemoryBufferThreshold = int.MaxValue; }); builder.Services.AddScoped<IUserClaimsPrincipalFactory<User>, AppUserClaimsPrincipalFactory>(); builder.Services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(3)); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { // Add JWT Authentication to Swagger c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\nExample: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List<string>() } }); }); var app = builder.Build(); // Configure the HTTP request pipeline if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } // Use CORS app.UseCors("AllowAll"); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Use(async (context, next) => { var logger = app.Services.GetRequiredService<ILogger<Program>>(); logger.LogInformation("Handling request: " + context.Request.Path); await next.Invoke(); logger.LogInformation("Finished handling request."); }); app.Run();
Comments