using HL_FristAidPlatform_Token; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System; using System.Text; using System.Threading.Tasks; namespace APPUpgradeAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { //builder.AllowAnyOrigin("http://47.112.158.86:4999").AllowAnyHeader().AllowAnyMethod().AllowCredentials(); //, "http://112.53.108.22:51001", "http://112.53.108.22:51002", "https://api.map.baidu.com/geocoder", "http://47.112.158.86:5000" builder.WithOrigins("http://47.112.158.86:4998", "http://47.112.158.86:51002", "http://47.112.158.86:5004", "http://47.112.158.86:51001") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); })); services.AddControllers(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel(); o.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = "wr",//Audience ValidIssuer = "API",//Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey)),//拿到SecurityKey }; o.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return Task.CompletedTask; } }; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "APPUpgradeAPI", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { } app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "APPUpgradeAPI v1"); c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); }); app.UseRouting(); //使用跨域 app.UseCors("CorsPolicy"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }