Example #1
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            services.AddIdentityUser <int, LoginAuthModel>((user, principal) =>
            {
                if (!principal.Identity.IsAuthenticated)
                {
                    return;                                         // 未授权返回
                }
                string sub           = principal.FindFirstValue(JwtRegisteredClaimNames.Sub);
                LoginAuthModel model = System.Text.Json.JsonSerializer.Deserialize <LoginAuthModel>(sub);
                user.Name            = model.NickName;
                user.Account         = model.Account;
                user.Avatar          = model.Avatar;
                user.Id = Convert.ToInt32(principal.FindFirstValue("id"));
            });

            // Services
            var types      = typeFinder.FindClassesOfType <IDependency>(false);
            var interfaces = types.Where(t => t.IsInterface && t != typeof(IDependency)).ToList();
            var impements  = types.Where(t => !t.IsAbstract).ToList();
            var didatas    = interfaces
                             .Select(t =>
            {
                return(new
                {
                    serviceType = t,
                    implementationType = impements.FirstOrDefault(c => t.IsAssignableFrom(c))
                });
            }
                                     ).ToList();

            didatas.ForEach(t =>
            {
                if (t.implementationType != null)
                {
                    services.AddScoped(t.serviceType, t.implementationType);
                }
            });

            // AutoMapper
            services.AddAutoMapper(typeof(AutomapperProfiler).Assembly);

            // MiniProfiler
            if (env.IsDevelopment())
            {
                services.AddMiniProfiler(options =>
                {
                    options.SqlFormatter = new SqlServerFormatter()
                    {
                        IncludeParameterValues = true
                    };
                    options.RouteBasePath = "/profiler";
                }).AddEntityFramework();
            }

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
        }
Example #2
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            services.AddMemoryCache();  // 内存缓存
            services.AddStackExchangeRedisCache(option =>
            {
                option.Configuration = calamusOptions.Redis.Configuration;
                option.InstanceName  = calamusOptions.Redis.KeyPrefix;
            });

            services.AddSingleton <IConnectionMultiplexer>(serviceProvider =>
            {
                var connection = ConnectionMultiplexer.Connect(calamusOptions.Redis.Configuration, null);
                connection.ConnectionFailed   += (sender, args) => { };
                connection.ConnectionRestored += (sender, args) => { };
                connection.InternalError      += (sender, args) => { };
                return(connection);
            });
            services.AddTransient <IDatabase>(serviceProvider =>
            {
                IConnectionMultiplexer connection = serviceProvider.GetRequiredService <IConnectionMultiplexer>();
                IDatabase db = connection.GetDatabase().WithKeyPrefix(calamusOptions.Redis.KeyPrefix);
                return(db);
            });
        }
Example #3
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            // Services
            var types      = typeFinder.FindClassesOfType <IDependency>(false);
            var interfaces = types.Where(t => t.IsInterface && t != typeof(IDependency)).ToList();
            var impements  = types.Where(t => !t.IsAbstract).ToList();
            var didatas    = interfaces
                             .Select(t =>
            {
                return(new
                {
                    serviceType = t,
                    implementationType = impements.FirstOrDefault(c => t.IsAssignableFrom(c))
                });
            }
                                     ).ToList();

            didatas.ForEach(t =>
            {
                if (t.implementationType != null)
                {
                    services.AddScoped(t.serviceType, t.implementationType);
                }
            });
        }
Example #4
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     //services.AddRabbitMessager<TextJsonSerializer>("amqp://*****:*****@101.132.140.8:5672/oms", "Calamus.Messager", queues =>
     //{
     //    queues.Add(new RabbitQueueBindingEntry { Queue = "queue1", RoutingKey = "queue1" });
     //    queues.Add(new RabbitQueueBindingEntry { Exchange = DefaultExchangeName.AMQ_DIRECT, ExchangeType = "direct", Queue = "queue2", RoutingKey = "queue2" });
     //});
     //services.AddHostedService<RabbitConsumerHostService>();
 }
Example #5
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Youle.Sys接口", Version = "v1"
                });

                /********XML文档注释*******/
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                //var basePath = AppContext.BaseDirectory ;
                //var xmlPath = Path.Combine(basePath, "Calamus.HostDemo.xml");
                //c.IncludeXmlComments(xmlPath, true);

                //xmlPath = Path.Combine(basePath, "Calamus.Models.xml");
                //c.IncludeXmlComments(xmlPath);

                /********JWT 授权请求头*******/
                var security = new OpenApiSecurityRequirement();
                var scheme   = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Id   = "jwt",
                        Type = ReferenceType.SecurityScheme
                    },
                    Description = "json web token授权请求头,在下方输入Bearer {token} 即可,注意两者之间有空格",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                };
                security.Add(scheme, new string[] { });
                c.AddSecurityRequirement(security);
                c.AddSecurityDefinition("jwt", scheme);

                c.AddFluentValidationRules(); // 支持FluentValidation 验证格式 MicroElements.Swashbuckle.FluentValidation
            });
        }
Example #6
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     //services.AddConsul(options =>
     //{
     //    options.Address = new Uri(calamusOptions.Consul.Address);
     //    options.Datacenter = calamusOptions.Consul.Datacenter;
     //    options.Token = calamusOptions.Consul.Token;
     //    options.WaitTime = calamusOptions.Consul.WaitTime > 0 ? TimeSpan.FromSeconds(calamusOptions.Consul.WaitTime) : (TimeSpan?)null;
     //})
     //.AddConsulServiceRegistration(options =>
     //{
     //    options.ID = calamusOptions.Consul.ServiceId;
     //    options.Name = calamusOptions.Consul.ServiceName;
     //    options.Address = calamusOptions.Consul.ServiceIP;
     //    options.Port = calamusOptions.Consul.ServicePort;
     //    options.Tags = new string[] { "SysApi" };
     //    options.Check = new AgentServiceCheck
     //    {
     //        HTTP = $"http://{calamusOptions.Consul.ServiceIP}:{calamusOptions.Consul.ServicePort}{calamusOptions.Consul.HealthCheckPath}",
     //        Interval = TimeSpan.FromSeconds(5),
     //        Timeout = TimeSpan.FromSeconds(60),
     //        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(300)
     //    };
     //});
 }
Example #7
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     //services.AddHealthChecks()
     //    .AddDbContextCheck<YouleDbContext>();   // EF Core 连接检查
 }
Example #8
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     //services.AddDbContext<YouleDbContext>(options =>
     //{
     //    options.UseSqlServer(calamusOptions.Databases["YouleDb"].Master);
     //});
 }
Example #9
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     //services.AddAutoMapper(typeof(DemoProfile).Assembly);
 }
Example #10
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                SecurityKey securityKey;
                if (calamusOptions.Jwt.SecurityType == 1)
                {
                    RSA rsa = RSA.Create();
                    rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(calamusOptions.Jwt.RsaPublicKey), out int reads);  // pkcs 8
                    //rsa.ImportRSAPublicKey(Convert.FromBase64String(calamusOptions.Jwt.RsaPublicKey), out int reads);   // pkcs 1
                    securityKey = new RsaSecurityKey(rsa);
                }
                else
                {
                    securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(calamusOptions.Jwt.SymmetricSecurityKey));
                }

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = calamusOptions.Jwt.ValidateIssuer,
                    ValidIssuer              = calamusOptions.Jwt.ValidIssuer,
                    ValidateAudience         = calamusOptions.Jwt.ValidateAudience,
                    ValidAudience            = calamusOptions.Jwt.ValidAudience,
                    ValidateLifetime         = calamusOptions.Jwt.ValidateLifetime,                //是否验证失效时间
                    ClockSkew                = TimeSpan.FromSeconds(calamusOptions.Jwt.ClockSkew), // 允许时间偏差,
                    ValidateIssuerSigningKey = calamusOptions.Jwt.ValidateIssuerSigningKey,
                    IssuerSigningKey         = securityKey
                };
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = (context) =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = (context) =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = (context) =>
                    {
                        //var jtiClaims = context.Principal.Claims.FirstOrDefault(item => item.Type == JwtRegisteredClaimNames.Jti);

                        //if (cache.TryGetValue(jtiClaims.Value, out object value))   // 缓存中存在,说明token 已注销,已失效
                        //{
                        //    context.Fail("授权已失效");
                        //}
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options => {
            });
        }
Example #11
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     services.AddDbContext <SnsdbContext>(options =>
     {
         options.UseMySql(calamusOptions.Databases["MySql"].Master, mysql =>
         {
             mysql.CharSet(CharSet.Utf8Mb4);
         });
     });
 }
Example #12
0
 public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
 {
     // Note .AddMiniProfiler() returns a IMiniProfilerBuilder for easy intellisense
     services.AddMiniProfiler(options =>
     {
         options.RouteBasePath = "/profiler";
         //options.Storage = new RedisStorage(calamusOptions.Redis.Configuration);
     }).AddEntityFramework();
 }
Example #13
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            //services.AddIdentityUser<int, AuthUserModel>((user, principal) =>
            //{
            //    user.Name = string.Empty;
            //    user.Account = string.Empty;
            //    user.Id = Convert.ToInt32(principal.Claims.First(x => x.Type == "id").Value);

            //    var userJson = principal.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //    AuthUserModel userInfo = userJson.Deserialize<AuthUserModel>();
            //    user.UserInfo = userInfo;
            //});
        }