Ejemplo n.º 1
0
        public JwtOutput GetJwtToken(JwtInput input)
        {
            string userName = input.UserName;
            var    claims   = new[]
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Authentication, "Zero.Code")
            };
            //读取jwt 配置
            var jwt = AppsettingHelper.Get <JwtToken>("JWT");
            //获取密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecurityKey));
            //生成凭证 ,根据密钥生成
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var time  = DateTime.Today.AddDays(jwt.Time);
            //写入token配置
            var token = new JwtSecurityToken(
                issuer: jwt.ValidIssuer,
                audience: jwt.ValidAudience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: time,
                signingCredentials: creds
                );
            //生成 token
            string access_token = new JwtSecurityTokenHandler().WriteToken(token);

            return(new JwtOutput(access_token, userName, TimeSpan.FromDays(jwt.Time)));
        }
Ejemplo n.º 2
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            int time  = AppsettingHelper.Get <int>("IpLimit", "WihtinTime");
            int count = AppsettingHelper.Get <int>("IpLimit", "LimitCount");
            //获取此次的ip请求
            string ipAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString();

            if (!string.IsNullOrEmpty(ipAddress))
            {
                var value = RedisHelper.StringGet <int>(ipAddress);
                if (value == 0)
                {
                    RedisHelper.StringSet(ipAddress, 1, TimeSpan.FromSeconds(time));
                }
                else
                {
                    value++;
                    RedisHelper.StringSet(ipAddress, value, TimeSpan.FromSeconds(time));
                    if (value >= count)
                    {
                        context.Result = AjaxHelper.Seed(Ajax.Bad, "ip limit (every ip has 10 limit)");
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public async Task Invoke(HttpContext httpContext)
        {
            int time  = AppsettingHelper.Get <int>("IpLimit", "WihtinTime");
            int count = AppsettingHelper.Get <int>("IpLimit", "LimitCount");
            //获取此次的ip请求
            string ipAddress = httpContext.Connection.RemoteIpAddress?.ToString();

            if (!string.IsNullOrEmpty(ipAddress))
            {
                var value = await RedisHelper.StringGetAsync <int>(ipAddress);

                if (value == 0)
                {
                    await RedisHelper.StringSetAsync(ipAddress, 1, TimeSpan.FromSeconds(time));
                }
                else
                {
                    value++;
                    await RedisHelper.StringSetAsync(ipAddress, value, TimeSpan.FromSeconds(time));

                    if (value >= count)
                    {
                        throw new Exception("ip limit (every ip has 10 limit)");
                    }
                }
            }
            await _next(httpContext);
        }
Ejemplo n.º 4
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            base.OnConfiguring(optionBuilder);
            var open = AppsettingHelper.Get <bool>("EFCoreLog");

            if (open)
            {
                optionBuilder.UseLoggerFactory(MyLoggerFactory);
            }
        }
        public static IServiceCollection AddEfDbContext(this IServiceCollection services)
        {
            var conStr = AppsettingHelper.Get("DataConnection", "SqlServer");

            services.AddDbContext <EfCoreDbContext>(option =>
            {
                option.UseSqlServer(conStr);
            });

            //services.AddScoped<EfCoreDbContext>();
            return(services);
        }
Ejemplo n.º 6
0
        public static IServiceCollection AddJwtToken(this IServiceCollection services)
        {
            //使用jwt 定义的规则,禁用.net core
            //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            var jwt = AppsettingHelper.Get <JwtToken>("JWT");

            if (jwt == null)
            {
                Console.WriteLine("appsetting.json文件没有 JWT相关配置,请检查!");
                return(services);
            }
            if (string.IsNullOrEmpty(jwt.ValidAudience) ||
                string.IsNullOrEmpty(jwt.ValidIssuer) ||
                string.IsNullOrEmpty(jwt.SecurityKey))
            {
                Console.WriteLine("Jwt配置错误错误,请检查appsetting.json文件!");
                return(services);
            }

            //添加jwt验证:
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,                                                     //是否验证Issuer
                    ValidateAudience         = true,                                                     //是否验证Audience
                    ValidateLifetime         = true,                                                     //是否验证失效时间
                    RequireExpirationTime    = true,                                                     //必须具有“过期”值。
                    ValidateIssuerSigningKey = true,                                                     //是否验证SecurityKey
                    ClockSkew        = TimeSpan.FromDays(jwt.Time),                                      //设置时间
                    ValidAudience    = jwt.ValidAudience,                                                //Audience
                    ValidIssuer      = jwt.ValidIssuer,                                                  //Issuer,这两项和前面签发jwt的设置一致
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecurityKey)) //拿到SecurityKey
                };
            });

            //swagger 替换 core 内置 system.text.json
            services.AddSwaggerGenNewtonsoftSupport();
            return(services);
        }
        public static IServiceCollection AddEfDbContext(this IServiceCollection services)
        {
            string dbType = AppsettingHelper.Get("DataConnection", "DbType");
            var    conStr = AppsettingHelper.Get("DataConnection", dbType);

            services.AddDbContext <EfCoreDbContext>(option =>
            {
                if (dbType == "SqlServer")
                {
                    option.UseSqlServer(conStr);
                }
                else
                {
                    option.UseMySQL(conStr);
                }
            });

            //services.AddScoped<EfCoreDbContext>();
            return(services);
        }
Ejemplo n.º 8
0
        public static IServiceCollection AddSwaggerDocs(this IServiceCollection services)
        {
            services.AddSwaggerGen(i =>
            {
                i.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "Zero.Core.WebApi Docs",
                    Description    = "WebApi",
                    TermsOfService = new Uri("https://www.baidu.com"),
                    Contact        = new OpenApiContact {
                        Name = "Zero", Email = "*****@*****.**"
                    },                                                                          //联系我
                    License = new OpenApiLicense {
                        Name = "博客园", Url = new Uri("https://www.cnblogs.com/aqgy12138/")
                    }                                                                                                 //许可
                });

                //排序规则
                i.OrderActionsBy((apiDesc) => $"{apiDesc.ActionDescriptor.RouteValues["controller"]}_{apiDesc.HttpMethod}");
                //i.ResolveConflictingActions(o => o.First());//控制器允许同名重载方法
                i.EnableAnnotations();//注释

                // 开启加权小锁
                i.OperationFilter <AddResponseHeadersFilter>();
                i.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();
                #region Tip2 二选一
                // 在header中添加token,传递到后台
                i.OperationFilter <SecurityRequirementsOperationFilter>();
                #endregion
                // 添加Header验证消息
                i.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
                {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token(注意Bearer和Token之间的空格):Bearer Token",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                });
                #region Tip2 二选一
                //i.AddSecurityRequirement(new OpenApiSecurityRequirement
                //{
                //   {
                //      new OpenApiSecurityScheme
                //      {
                //        Reference = new OpenApiReference {
                //        Type = ReferenceType.SecurityScheme,
                //        Id = "Bearer"
                //       }
                //    },
                //     new string[] { }
                //   }
                //});
                #endregion
                //设置swagger备注
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                var xmls     = AppsettingHelper.Get <string[]>("SwaggerXml");
                for (int x = 0; x < xmls.Length; x++)
                {
                    var xmlPath = Path.Combine(basePath, xmls[x]);
                    i.IncludeXmlComments(xmlPath);//文档中文提示
                }
            });
            services.AddSwaggerGenNewtonsoftSupport();
            return(services);
        }