123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344 |
- using Autofac;
- using log4net.Config;
- using log4net;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.IdentityModel.Tokens;
- using Microsoft.OpenApi.Models;
- using Newtonsoft.Json;
- using Ropin.Core.Extensions;
- using Ropin.Core.Extensions.Middlewares;
- using Ropin.Core.Extensions.ServiceExtensions;
- using Ropin.Inspection.Api.Common;
- using Ropin.Inspection.Api.Common.Options;
- using Ropin.Inspection.Api.Common.Token;
- using Ropin.Inspection.Api.Filters;
- using Ropin.Inspection.Api.Helper;
- using Ropin.Inspection.Common.Accessor;
- using Ropin.Inspection.Common.Accessor.Interface;
- using Ropin.Inspection.Common.Helper;
- using Ropin.Inspection.Model.Entities;
- using Ropin.Inspection.Repository;
- using Ropin.Inspection.Repository.Interface;
- using Ropin.Inspection.Service;
- using Ropin.Inspection.Service.Interface;
- using Ropin.Inspection.Tasks.QuartzNet;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace Ropin.Inspection.Api
- {
- public class Startup
- {
- public Startup(IConfiguration configuration, IWebHostEnvironment env)
- {
- Configuration = configuration;
- Env = env;
- var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
- XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));
- }
- public IConfiguration Configuration { get; }
- public IWebHostEnvironment Env { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton(new Appsettings(Configuration));
-
- services.AddControllers();
- services.AddHttpClient();
- services.Configure<WXOptions>("WXOptions", Configuration.GetSection("WX"));
- services.Configure<RabbitMQModel>("RabbitMQModel", Configuration.GetSection("RabbitMQ"));
- #region 读取配置信息
- services.AddSingleton<ITokenHelper, TokenHelper>();
- services.Configure<JWTConfig>(Configuration.GetSection("JWT"));
- JWTConfig config = new JWTConfig();
- Configuration.GetSection("JWT").Bind(config);
- #endregion
- #region 启用JWT认证
- services.AddAuthentication(options =>
- {
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- }).
- AddJwtBearer(options =>
- {
- options.TokenValidationParameters = new TokenValidationParameters
- {
-
- ValidateIssuer = true,
- ValidIssuer = config.Issuer,
-
- ValidateAudience = true,
- ValidAudience = config.Audience,
-
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.IssuerSigningKey)),
- ValidateLifetime = true,
- RequireExpirationTime = true,
- };
- options.Events = new JwtBearerEvents
- {
- OnAuthenticationFailed = context =>
- {
-
- if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
- {
- context.Response.Headers.Add("Token-Expired", "true");
- }
- return Task.CompletedTask;
- },
- OnChallenge = async context =>
- {
-
- context.HandleResponse();
- context.Response.ContentType = "application/json;charset=utf-8";
- context.Response.StatusCode = StatusCodes.Status401Unauthorized;
- var result = new ApiResult(ReturnCode.TokenError, "Token失效");
-
-
- await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
-
- }
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- });
- #endregion
- #region 自定义授权
-
-
- services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
- services.AddSingleton<IPrincipalAccessor, PrincipalAccessor>();
- services.AddSingleton<IClaimsAccessor, ClaimsAccessor>();
- #endregion
-
- services.AddAutoMapper(typeof(AutoMapperProfile));
- services.AddScoped<AuthorExistFilterAttribute>();
-
-
-
- services.AddJobSetup();
- services.AddMemoryCacheSetup();
- services.AddRedisCacheSetup();
- services.AddNodeServices();
-
-
-
-
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "Ropin.Inspection.Api", Version = "v1" });
- c.DocInclusionPredicate((docName, description) => true);
- var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
-
- var commentsFileName = "Ropin.Inspection.Api.xml";
- var commentsFile = Path.Combine(baseDirectory, commentsFileName);
- c.IncludeXmlComments(commentsFile);
-
- var securityScheme = new OpenApiSecurityScheme()
- {
- Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
- Name = "Authorization",
-
- In = ParameterLocation.Header,
-
- Type = SecuritySchemeType.Http,
-
- Scheme = "Bearer",
- BearerFormat = "JWT"
- };
-
- var securityRequirement = new OpenApiSecurityRequirement
- {
- {
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type = ReferenceType.SecurityScheme,
- Id = "bearerAuth"
- }
- },
- new string[] {}
- }
- };
-
-
-
-
-
-
- c.AddSecurityDefinition("bearerAuth", securityScheme);
- c.AddSecurityRequirement(securityRequirement);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- });
- var connectionString = Configuration["ConnectionSetting:MySqlConnection"];
-
- ServerVersion serverVersion = ServerVersion.AutoDetect(connectionString);
- services.AddDbContext<InspectionDbContext>(options =>
- options.UseMySql(connectionString, serverVersion));
-
-
-
-
-
-
- services.AddCors(options =>
- {
- options.AddPolicy("CorsPolicy",
- builder => builder.AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader());
- });
- services.AddMvc(options =>
- {
- options.Filters.Add<AuthorExistFilterAttribute>();
- });
-
-
-
-
-
-
-
- services.AddControllers(o =>
- {
-
- o.Filters.Add(typeof(ExceptionFilter));
- })
- .AddNewtonsoftJson(options =>
- {
-
- options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
-
-
-
-
-
- options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
- });
- }
-
- public void ConfigureContainer(ContainerBuilder builder)
- {
- builder.RegisterModule(new AutofacModuleRegister());
-
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env, InspectionDbContext dataDBContext)
- {
-
-
- app.UseCors("CorsPolicy");
-
-
- app.UseDeveloperExceptionPage();
-
- app.UseSwagger();
-
- app.UseSwaggerUI(c => c.SwaggerEndpoint("v1/swagger.json", "Ropin.Inspection.Api v1"));
-
-
- app.UseAuthentication();
- app.UseRouting();
-
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
-
-
-
-
- }
- }
- }
|