- using System.Collections.Generic;
- using System.IO;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.PlatformAbstractions;
- using Swashbuckle.AspNetCore.Swagger;
- using RayPI.Model.ConfigModel;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.IdentityModel.Tokens;
- using System.Text;
- using RayPI.AuthHelp;
- namespace RayPI
- {/// <summary>
- ///
- /// </summary>
- public class Startup
- {
- /// <summary>
- ///
- /// </summary>
- /// <param name="env"></param>
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
- this.Configuration = builder.Build();
- BaseConfigModel.SetBaseConfig(Configuration);
- }
- /// <summary>
- ///
- /// </summary>
- public IConfiguration Configuration { get; }
- /// <summary>
- /// This method gets called by the runtime. Use this method to add services to the container.
- /// </summary>
- /// <param name="services"></param>
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().AddJsonOptions(options =>
- {
- options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";// 设置时间格式
- });
- #region Swagger
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info
- {
- Version = "v1.1.0",
- Title = "Ray webAPI",
- Description = "框架集合",
- TermsOfService = "None",
- Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "RayWang", Email = "2271272653@qq.com", Url = "http://www.cnblogs.com/RayWang" }
- });
- // 添加注释服务
- var basePath = PlatformServices.Default.Application.ApplicationBasePath;
- var apiXmlPath = Path.Combine(basePath, "APIHelp.xml");
- var entityXmlPath = Path.Combine(basePath, "EntityHelp.xml");
- c.IncludeXmlComments(apiXmlPath, true);// 控制器层注释 (true 表示显示控制器注释)
- c.IncludeXmlComments(entityXmlPath);
- // 添加控制器注释
- //c.DocumentFilter<SwaggerDocTag>();
- // 添加 header 验证信息
- //c.OperationFilter<SwaggerHeader>();
- var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
- c.AddSecurityRequirement(security);// 添加一个必须的全局安全信息, 和 AddSecurityDefinition 方法指定的方案名称要一致, 这里是 Bearer.
- c.AddSecurityDefinition("Bearer", new ApiKeyScheme
- {
- Description = "JWT 授权 (数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
- Name = "Authorization",//jwt 默认的参数名称
- In = "header",//jwt 默认存放 Authorization 信息的位置 (请求头中)
- Type = "apiKey"
- });
- });
- #endregion
- #region 认证
- services.AddAuthentication(x =>
- {
- x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- })
- .AddJwtBearer(o =>
- {
- JwtAuthConfigModel jwtConfig=new JwtAuthConfigModel();
- o.TokenValidationParameters = new TokenValidationParameters
- {
- ValidIssuer = "RayPI",
- ValidAudience = "wr",
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),
- /***********************************TokenValidationParameters 的参数默认值 ***********************************/
- RequireSignedTokens = true,
- // SaveSigninToken = false,
- // ValidateActor = false,
- // 将下面两个参数设置为 false, 可以不验证 Issuer 和 Audience, 但是不建议这样做.
- ValidateAudience = false,
- ValidateIssuer = true,
- ValidateIssuerSigningKey = true,
- // 是否要求 Token 的 Claims 中必须包含 Expires
- RequireExpirationTime = true,
- // 允许的服务器时间偏移量
- // ClockSkew = TimeSpan.FromSeconds(300),
- // 是否验证 Token 有效期, 使用当前时间与 Token 的 Claims 中的 NotBefore 和 Expires 对比
- ValidateLifetime = true
- };
- });
- #endregion
- #region 授权
- services.AddAuthorization(options =>
- {
- options.AddPolicy("RequireClient", policy => policy.RequireRole("Client").Build());
- options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
- options.AddPolicy("RequireAdminOrClient", policy => policy.RequireRole("Admin,Client").Build());
- });
- #endregion
- #region CORS
- services.AddCors(c =>
- {
- c.AddPolicy("Any", policy =>
- {
- policy.AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader()
- .AllowCredentials();
- });
- c.AddPolicy("Limit", policy =>
- {
- policy
- .WithOrigins("localhost:8083")
- .WithMethods("get", "post", "put", "delete")
- //.WithHeaders("Authorization");
- .AllowAnyHeader();
- });
- });
- #endregion
- }
- /// <summary>
- /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- /// </summary>
- /// <param name="app"></param>
- /// <param name="env"></param>
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- #region Swagger
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
- });
- #endregion
- // 认证
- app.UseAuthentication();
- // 授权
- app.UseMiddleware<JwtAuthorizationFilter>();
- app.UseMvc();
- app.UseStaticFiles();// 用于访问 wwwroot 下的文件
- }
- }
- }
来源: https://www.cnblogs.com/RayWang/p/9536524.html