Beispiel #1
0
        public static void AddService(this IServiceCollection services, SysConfig systemConfig)
        {
            WebApiCompatShimMvcBuilderExtensions.AddWebApiConventions(services.AddMvc(opt =>
            {
                opt.UseCentralRoutePrefix(new RouteAttribute(systemConfig.Name));
            }))
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(x =>
            {
                //设置时间格式
                x.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //设置转换属性
                //x.SerializerSettings.ContractResolver = new ContractResolverOverload();
            });

            services.AddCors(opt =>
            {
                opt.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//指定处理cookie
                });
            });
            #region JWT认证
            //JWT配置注入
            services.Configure <JwtSettings>(opt =>
            {
                opt.Audience   = systemConfig.JwtSettings.Audience;
                opt.Expires    = systemConfig.JwtSettings.Expires;
                opt.Issuer     = systemConfig.JwtSettings.Issuer;
                opt.PrivateKey = systemConfig.JwtSettings.PrivateKey;
                opt.PublicKey  = systemConfig.JwtSettings.PublicKey;
                opt.Secretkey  = systemConfig.JwtSettings.Secretkey;
            });
            SysConfig systemConfig2 = systemConfig;
            services.AddMicroService(systemConfig2);

            //TODO 令牌过期后刷新,以及更改密码后令牌未过期的处理问题
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opts =>
            {
                opts.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        var header    = context.Request.Headers["Authorization"].FirstOrDefault();
                        var jwtEntity = JwtEntity.GetJwtEntity(header);
                        if (jwtEntity != null)
                        {
                            if (DateTime.Now > DateTimeExtension.ConvertToCsharpTime(jwtEntity.Exp))
                            {
                                context.Fail("token已过期");
                            }
                        }
                        return(Task.CompletedTask);
                    }
                };

                opts.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(systemConfig.JwtSettings.Secretkey)),
                    ValidateIssuer           = true,
                    ValidIssuer      = systemConfig.JwtSettings.Issuer,
                    ValidateAudience = true,
                    ValidAudience    = systemConfig.JwtSettings.Audience,
                };
            });
            #endregion
        }
Beispiel #2
0
 public static IApplicationBuilder UseService(this IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, SysConfig systemConfig)
 {
     MicroServiceExtension.UseMicroService(app, env, lifetime, systemConfig);
     app.UseMiddleware <PermissionMiddleware>();
     app.UseMiddleware <ExceptionMiddleware>();
     return(app);
 }
Beispiel #3
0
        public static void UseMicroService(this IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, SysConfig serviceInfo)
        {
            new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
            string serviceId = $" {serviceInfo.Name}-{serviceInfo.LocalAddress}";
            string address   = serviceInfo.LocalAddress.Split(new char[] { ':' }, StringSplitOptions.None)[0];
            string s         = serviceInfo.LocalAddress.Split(new char[] { ':' }, StringSplitOptions.None)[1];

            if (!string.IsNullOrEmpty(serviceInfo.ServiceDiscoveryAddress))
            {
                using (ConsulClient consulClient = new ConsulClient(x =>
                {
                    x.Address = new Uri(serviceInfo.ServiceDiscoveryAddress);
                }))
                {
                    var agentServiceRegistration = new AgentServiceRegistration
                    {
                        Address = address,
                        Port    = int.Parse(s),
                        ID      = serviceId,
                        Name    = serviceInfo.Name,
                        Check   = new AgentServiceCheck
                        {
                            DeregisterCriticalServiceAfter = new TimeSpan?(TimeSpan.FromSeconds(5.0)),
                            HTTP     = "http://" + serviceInfo.LocalAddress + "/healthcheck",
                            Interval = new TimeSpan?(TimeSpan.FromSeconds(2.0)),
                            Timeout  = new TimeSpan?(TimeSpan.FromSeconds(1.0))
                        }
                    };
                    agentServiceRegistration.Tags = new string[]
                    {
                        serviceInfo.DisplayName
                    };
                    consulClient.Agent.ServiceRegister(agentServiceRegistration, default(CancellationToken)).Wait();
                }
                lifetime.ApplicationStopped.Register(() =>
                {
                    using (ConsulClient consulClient2 = new ConsulClient(x =>
                    {
                        x.Address = new Uri(serviceInfo.ServiceDiscoveryAddress);
                    }))
                    {
                        consulClient2.Agent.ServiceDeregister(serviceId, default(CancellationToken)).Wait();
                    }
                });
                app.Map("/healthcheck", delegate(IApplicationBuilder ab)
                {
                    ab.Run(async delegate(HttpContext context)
                    {
                        await context.Response.WriteAsync("ok", default(CancellationToken));
                    });
                });
            }
            //if (!env.IsProduction())
            //{
            app.UseSwagger(opt =>
            {
                opt.RouteTemplate = "{documentName}/swagger.json";
            });
            //app.UseSwagger();
            app.UseSwaggerUI(delegate(SwaggerUIOptions opt)
            {
                opt.SwaggerEndpoint("/" + serviceInfo.Name.ToLower() + "/swagger.json", serviceInfo.DisplayName);
                opt.RoutePrefix = string.Empty;//开启默认swagger/index.html路径
                opt.DocExpansion(DocExpansion.None);
            });
            //}
            app.UseAuthentication();
        }