StableVersion4.3/APPUpgradeAPI/Startup.cs

103 lines
3.9 KiB
C#

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();
});
}
}
}