Example #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)));
        }
Example #2
0
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="claims">需要在登陆的时候配置</param>
        /// <returns></returns>
        public static TokenInfoViewModel BuildJwtToken(Claim[] claims)
        {
            var symmetricKeyAsBase64 = "sdfsdfsrty45634kkhllghtdgdfss345t678fs";
            var keyByteArray         = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey           = new SymmetricSecurityKey(keyByteArray);
            var Issuer   = AppsettingHelper.GetValue(new string[] { "Audience", "Issuer" });
            var Audience = AppsettingHelper.GetValue(new string[] { "Audience", "Audience" });

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var now = DateTime.Now;
            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: Issuer,
                audience: Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(new TimeSpan(60)),
                signingCredentials: signingCredentials
                );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //打包返回前台
            var responseJson = new TokenInfoViewModel
            {
                success    = true,
                token      = encodedJwt,
                expires_in = 60,
                token_type = "Bearer"
            };

            return(responseJson);
        }
Example #3
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)");
                    }
                }
            }
        }
Example #4
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);
        }
Example #5
0
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddCors(c =>
            {
                c.AddPolicy("LimitRequests", policy =>
                {
                    // 支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
                    // 注意,http://127.0.0.1:1818 和 http://localhost:1818 是不一样的,尽量写两个
                    policy
                    .WithOrigins(AppsettingHelper.GetValue(new string[] { "Startup", "Cors", "IPs" }).Split(','))
                    .AllowAnyHeader()//Ensures that the policy allows any header.
                    .AllowAnyMethod();
                });

                // 允许任意跨域请求,也要配置中间件
                //c.AddPolicy("AllRequests",policy=> {
                //    policy.AllowAnyOrigin();
                //    policy.AllowAnyMethod();
                //    policy.AllowAnyHeader();
                //});
            });
        }
Example #6
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            base.OnConfiguring(optionBuilder);
            var open = AppsettingHelper.Get <bool>("EFCoreLog");

            if (open)
            {
                optionBuilder.UseLoggerFactory(MyLoggerFactory);
            }
        }
        public RedisCacheManager()
        {
            string redisConfiguration = AppsettingHelper.GetValue(new string[] { "AppSettings", "RedisCachingAOP", "ConnectionString" });//获取连接字符串

            if (string.IsNullOrWhiteSpace(redisConfiguration))
            {
                throw new ArgumentException("redis config is empty", nameof(redisConfiguration));
            }
            this.redisConnenctionString = redisConfiguration;
            this.redisConnection        = GetRedisConnection();
        }
        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);
        }
Example #9
0
        public static List <MutiDBOperate> MutiInitConn()
        {
            List <MutiDBOperate> listdatabase = AppsettingHelper.GetValue <MutiDBOperate>("DBS")
                                                .Where(i => i.Enabled).ToList();

            foreach (var i in listdatabase)
            {
                // SpecialDbString(i);
            }
            List <MutiDBOperate> listdatabaseSimpleDB = new List <MutiDBOperate>();//单库

            return(listdatabase);
        }
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // 默认添加主数据库连接
            MainDb.CurrentDbConnId = AppsettingHelper.GetValue(new string[] { "MainDB" });
            // 把多个连接对象注入服务,这里必须采用Scope,因为有事务操作
            services.AddScoped <ISqlSugarClient>(o =>
            {
                // 连接字符串
                var listConfig = new List <ConnectionConfig>();
                // 从库
                var listConfig_Slave = new List <SlaveConnectionConfig>();


                BaseDBConfig.MutiConnectionString.ForEach(m =>
                {
                    listConfig.Add(new ConnectionConfig()
                    {
                        ConfigId              = m.ConnId.ObjToString().ToLower(),
                        ConnectionString      = m.Connection,
                        DbType                = (DbType)m.DbType,
                        IsAutoCloseConnection = true,
                        IsShardSameThread     = false,
                        MoreSettings          = new ConnMoreSettings()
                        {
                            IsAutoRemoveDataCache = true
                        },
                        AopEvents = new AopEvents()
                        {
                            // OnLogExecuting = (sql, p) => { Console.WriteLine(sql); },
                            OnLogExecuting = (sql, pars) =>
                            {
                                Console.WriteLine(sql);
                                Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                            },
                        },
                        // 从库
                        SlaveConnectionConfigs = listConfig_Slave,
                        //InitKeyType = InitKeyType.SystemTable
                    }
                                   );
                });
                return(new SqlSugarClient(listConfig));
            });
        }
Example #11
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);
        }
Example #13
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);
        }