using JwtAuth.Api.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Scalar.AspNetCore; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Configure JWT Authentication builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { //options.RequireHttpsMetadata = false; //options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? Guid.NewGuid().ToString("N"))) }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { Console.WriteLine("Authentication failed: " + context.Exception.Message); return Task.CompletedTask; } }; }); builder.Services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi //builder.Services.AddOpenApi(); builder.Services.AddOpenApi(opt => { opt.AddDocumentTransformer<BearerSecuritySchemeTransformer>(); }); builder.Services.AddSingleton<JwtService>(); builder.Services.AddControllers(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.MapOpenApi(); app.MapScalarApiReference(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("AllowAllOrigins"); app.UseAuthentication(); // 启用认证 app.UseAuthorization(); // 启用授权 app.MapControllers(); app.Run();
标签:builder,openapi,net9,Services,using,app,true,options From: https://www.cnblogs.com/zengfeng1013/p/18650686