示例#1
0
        /// <summary>
        /// 颁发JWT字符串 /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJWT(TokenModel tokenModel)
        {
            var jwtConfig = new JwtAuthConfigModel();
            //过期时间(分钟)
            double exp = 0;

            switch (tokenModel.TokenType)
            {
            case "Web":
                exp = jwtConfig.WebExp;
                break;

            case "App":
                exp = jwtConfig.AppExp;
                break;

            case "Wx":
                exp = jwtConfig.WxExp;
                break;

            case "Other":
                exp = jwtConfig.OtherExp;
                break;
            }
            var dateTime = DateTime.UtcNow;
            var claims   = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid),
                new Claim("UserName", tokenModel.UserName.ToString()),    //用户名
                //new Claim("AppId", tokenModel.AppId.ToString()),//应用id
                //new Claim("AppName", tokenModel.AppName.ToString()),//应用名称
                //new Claim("TokenType", tokenModel.TokenType.ToString()),//TokenType
                //new Claim("Role", tokenModel.Role.ToString()),//角色
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                //这个就是过期时间,目前是过期100秒,可自定义,注意JWT有自己的缓冲过期时间
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(exp)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss, jwtConfig.Issuer),
                new Claim(JwtRegisteredClaimNames.Aud, jwtConfig.Audience),
                //new Claim(ClaimTypes.Role,tokenModel.Role),
                new Claim("GroupId", tokenModel.GroupId),    //群组id
            };
            //秘钥
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt   = new JwtSecurityToken(
                issuer: jwtConfig.Issuer,
                audience: jwtConfig.Audience,
                claims: claims,
                expires: dateTime.AddMinutes(exp),
                signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return(encodedJwt);
        }
示例#2
0
        /// <summary>
        /// 注册服务到[依赖注入容器]
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //注册控制器
            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(WebApiResultFilterAttribute));
                options.RespectBrowserAcceptHeader = true;
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//设置时间格式
            });

            //注册配置管理服务
            services.AddSingleton <IConfiguration>(_configuration);
            services.AddMyOptions();
            services.AddConfigService(_env.ContentRootPath);
            AllConfigModel allConfig = services.GetImplementationInstanceOrNull <AllConfigModel>();

            //注册Swagger
            services.AddSwaggerService();

            //注册授权认证

            JwtAuthConfigModel jwtConfig = allConfig.JwtAuthConfigModel;
            var jwtOption = new JwtOption//todo:使用AutoMapper替换
            {
                Issuer         = jwtConfig.Issuer,
                Audience       = jwtConfig.Audience,
                WebExp         = jwtConfig.WebExp,
                AppExp         = jwtConfig.AppExp,
                MiniProgramExp = jwtConfig.MiniProgramExp,
                OtherExp       = jwtConfig.OtherExp,
                SecurityKey    = jwtConfig.SecurityKey
            };

            services.AddSingleton(jwtOption);
            services.AddRayAuthService(jwtOption);

            //services.AddSecurityService();

            //注册Cors跨域
            services.AddCorsService();

            //注册http上下文访问器
            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

            //注册仓储
            //string connStr = allConfig.ConnectionStringsModel.SqlServerDatabase;
            services.AddMyRepository();

            //注册业务逻辑
            services.AddMyAppServices();

            LogServices(services);
        }
示例#3
0
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJWT(TokenModel tokenModel)
        {
            var dateTime = DateTime.UtcNow;
            var claims   = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //用户Id
                new Claim("Role", tokenModel.Role),                                //身份
                new Claim("Project", tokenModel.Project),                          //项目名称
                new Claim(JwtRegisteredClaimNames.Sub, tokenModel.Uid.ToString()), //用户UserId
                new Claim(JwtRegisteredClaimNames.Iat, dateTime.ToString(), ClaimValueTypes.Integer64)
            };
            //秘钥
            var jwtConfig = new JwtAuthConfigModel();

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //过期时间
            double exp = 0;

            switch (tokenModel.TokenType)
            {
            case "Web":
                exp = jwtConfig.WebExp;
                break;

            case "App":
                exp = jwtConfig.AppExp;
                break;

            case "MiniProgram":
                exp = jwtConfig.MiniProgramExp;
                break;

            case "Other":
                exp = jwtConfig.OtherExp;
                break;
            }
            var jwt = new JwtSecurityToken(
                issuer: "User",
                audience: "User",
                claims: claims, //声明集合
                expires: dateTime.AddHours(exp),
                signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return(encodedJwt);
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region 注册服务
            services.AddTransient <IonlineusersService, onlineusersService>();
            services.AddTransient <ISysUserInfoService, SysUserInfoService>();
            services.AddTransient <ISysmenuService, SysmenuService>();
            #endregion

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/login");
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer              = "FytSos",
                    ValidAudience            = "wr",
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),
                    RequireSignedTokens      = true,
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime    = true,
                    ValidateLifetime         = true
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireApp", policy => policy.RequireRole("App").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
        }
示例#5
0
文件: Startup.cs 项目: lament0/RayPI
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //注册MVC
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";    //设置时间格式
            });

            //注册配置管理服务
            services.AddConfigService(_env.ContentRootPath);
            AllConfigModel allConfig = services.GetSingletonInstanceOrNull <AllConfigModel>();

            //注册Swagger
            services.AddSwaggerService();

            //注册授权认证
            JwtAuthConfigModel jwtConfig = allConfig.JwtAuthConfigModel;
            var jwtOption = new JwtOption//todo:使用AutoMapper替换
            {
                WebExp         = jwtConfig.WebExp,
                AppExp         = jwtConfig.AppExp,
                MiniProgramExp = jwtConfig.MiniProgramExp,
                OtherExp       = jwtConfig.OtherExp,
                SecurityKey    = jwtConfig.SecurityKey
            };

            services.AddAuthService(jwtOption);

            //注册Cors跨域
            services.AddCorsService();

            //注册http上下文访问器
            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

            //注册仓储
            string connStr = allConfig.ConnectionStringsModel.SqlServerDatabase;

            services.AddRepository(connStr);

            //注册业务逻辑
            services.AddBusiness();
        }
示例#6
0
        /// <summary>
        /// 注册服务到[依赖注入容器]
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //注册控制器
            services.AddControllers(options =>
            {
                //options.Filters.Add(typeof(WebApiResultFilterAttribute));
                options.RespectBrowserAcceptHeader = true;
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";    //设置时间格式
            });

            //注册配置管理服务
            services.AddConfigService(_env.ContentRootPath);
            AllConfigModel allConfig = services.GetImplementationInstanceOrNull <AllConfigModel>();

            //注册Swagger
            services.AddSwaggerService();

            //注册授权认证
            JwtAuthConfigModel jwtConfig = allConfig.JwtAuthConfigModel;
            var jwtOption = AutoMapperHelper.Map <JwtAuthConfigModel, JwtOption>(jwtConfig);

            services.AddSingleton(jwtOption);
            services.AddRayAuthService(jwtOption);

            //services.AddSecurityService();

            //注册Cors跨域
            services.AddCorsService();

            //注册http上下文访问器
            services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

            //注册业务逻辑
            services.AddMyAppServices(_configuration);
            services.AddMyRepository(_configuration);
        }
示例#7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSkyApmExtensions();//add track


            services.AddHorizonORM(Configuration);//add orm


            //跨域
            services.AddCors();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });

            //注入jwt,添加JWT Scheme
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                var jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,                  //是否验证Issuer
                    ValidateAudience         = true,                  //是否验证Audience
                    ValidateIssuerSigningKey = true,                  //是否验证SecurityKey
                    ValidateLifetime         = true,                  //是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew
                    ClockSkew             = TimeSpan.FromSeconds(30), //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ValidAudience         = jwtConfig.Audience,       //Audience
                    ValidIssuer           = jwtConfig.Issuer,         //Issuer,这两项和前面签发jwt的设置一致
                    RequireExpirationTime = true,
                    IssuerSigningKey      =
                        new SymmetricSecurityKey(
                            Encoding.UTF8.GetBytes(Configuration["JwtAuth:SecurityKey"])) //拿到SecurityKey
                };
                o.Events = new JwtBearerEvents
                {
                    //验证失败后停止响应
                    OnChallenge = p =>
                    {
                        p.HandleResponse();


                        var payload = "{\"Success\":false,\"Msg\":\"很抱歉,您无权访问该接口\",\"StatusCode\":401}";
                        //自定义返回的数据类型
                        p.Response.ContentType = "application/json";
                        //自定义返回状态码,默认为401 我这里改成 200
                        p.Response.StatusCode = 200;
                        //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        //输出Json数据结果
                        p.Response.WriteAsync(payload);
                        return(Task.FromResult(0));
                    },
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }
示例#8
0
 public Startup(IConfiguration configuration)
 {
     Configuration = configuration;
     JwtAuthConfigModel.CreateInstance(configuration);
 }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            AddAssembly(services, "BookingTest.Service");
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtAuthorizeAttribute.JwtAuthenticationScheme, x =>
            {
                var jwtConfig = new JwtAuthConfigModel();

                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true, //是否验证Issuer
                    ValidateAudience         = true, //是否验证Audience
                    ValidateIssuerSigningKey = true, //是否验证SecurityKey
                    //ValidateLifetime = true,//是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew
                    //ClockSkew = TimeSpan.FromSeconds(30),//注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    //RequireExpirationTime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JwtAuth:SecurityKey"])), //拿到SecurityKey
                    ValidIssuer      = jwtConfig.Issuer,                                                                        //Issuer,这两项和前面签发jwt的设置一致
                    ValidAudience    = jwtConfig.Audience                                                                       //Audience
                };
                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            //注册 Swagger
            services.AddSwaggerGen(c =>
            {
                //Locate the XML file being generated by ASP.NET...
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);

                //... and tell Swagger to use those XML comments.
                c.IncludeXmlComments(xmlPath);
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v5.0.0",
                    Title          = "一体化预约平台PC后端 api",
                    Description    = "基于.net core 3.1  开发工具VS2019",
                    TermsOfService = new Uri("http://cnblogs.com/microfisher"),
                    Contact        = new OpenApiContact {
                        Name = "卓健科技", Email = "*****@*****.**", Url = new Uri("http://www.zhuojianchina.com/")
                    }
                });
                var bearerScheme = new OpenApiSecurityScheme
                {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                };
                // 开启加权小锁
                c.OperationFilter <AddResponseHeadersFilter>();
                c.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();
                // 在header中添加token,传递到后台
                c.OperationFilter <SecurityRequirementsOperationFilter>();
                c.AddSecurityDefinition("oauth2", bearerScheme);
            });

            //配置文件大小限制
            services.Configure <Microsoft.AspNetCore.Http.Features.FormOptions>(options =>
            {
                options.ValueLengthLimit            = int.MaxValue;
                options.MultipartBodyLengthLimit    = int.MaxValue;// 60000000;
                options.MultipartHeadersLengthLimit = int.MaxValue;
                options.ValueLengthLimit            = int.MaxValue;
            });
            services.AddControllers(configure =>
            {
                configure.Filters.Add <LogFilterAttribute>();
                configure.Filters.Add <HospitalUserFilterAttribute>();//全局过滤器,不用添加特性头
            }).AddNewtonsoftJson(options =>
            {
                //修改属性名称的序列化方式,首字母小写
                //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();//json字符串大小写原样输出
                //修改时间的序列化方式
                options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy/MM/dd HH:mm:ss"
                });
            });


            #region CORS
            services.AddCorsSetup();
            #endregion
        }
示例#10
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// 第一次请求时配置各个实例对象(bean)
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(o =>
            {
                o.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.Configure <MvcOptions>(options =>
            {
                //给全局路由添加统一前缀
                options.Conventions.Insert(0, new RouteConvention(new RouteAttribute("services/v1/")));
            });

            #region swagger
            services.AddSwaggerGen(c =>
            {
                //文档左上角的描述
                var swaggerInfo = new Info
                {
                    Version        = "v1.0.0",
                    Title          = "hepeng's dotnetcore test",
                    Description    = "路漫漫其修远兮 吾将上下而求索<br />愿你出走半生 归来仍是少年",
                    TermsOfService = "http://www.baidu.com",
                    License        = new License()
                    {
                        Name = "license", Url = "http://www.baidu.com"
                    },
                    Contact = new Contact()
                    {
                        Name = "hepeng", Email = "*****@*****.**", Url = "https://www.cnblogs.com/hepeng/"
                    }
                };
                c.SwaggerDoc("v1", swaggerInfo);
                //读取注释用于显示
                c.IncludeXmlComments(AppDomain.CurrentDomain.BaseDirectory + "CoreTest.xml", true);

                //在swagger中显示JWT信息
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } }
                };
                c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
            });
            #endregion

            #region 认证
            //bearer “持票人”约定俗成
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = "CoreTest",//发行人
                    ValidAudience    = "wr",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = true,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                //此处与控制器中的[Authorize(Roles = "Admin,hepeng")]对应
                //可通过读取数据角色动态添加
                options.AddPolicy("RequireClient", policy => policy.RequireRole("Client").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrClient", policy => policy.RequireRole("Admin,Client").Build());
            });
            #endregion

            #region CORS 启用跨域请求
            //同源三要素: 协议 域名 端口  不同的资源的这三个要素同时相同才叫同源
            //https://i.cnblogs.com/EditLinks.aspx?catid=1357952
            services.AddCors(c =>
            {
                //添加策略
                //此处与控制器中的[EnableCors("Any")]对应
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:8083")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion
        }
示例#11
0
        public void ConfigureServices(IServiceCollection services)
        {
            //自定注册
            AddAssembly(services, "FytSoa.Service");

            //解决视图输出内容中文编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/fytadmin/login");
            })
            //新增一个新的方案
            .AddCookie(BbsUserAuthorizeAttribute.BbsUserAuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/bbs/nologin");
            })
            .AddJwtBearer(JwtAuthorizeAttribute.JwtAuthenticationScheme, o =>
            {
                var jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,                                                                               //是否验证Issuer
                    ValidateAudience         = true,                                                                               //是否验证Audience
                    ValidateIssuerSigningKey = true,                                                                               //是否验证SecurityKey
                    ValidateLifetime         = true,                                                                               //是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew
                    ClockSkew             = TimeSpan.FromSeconds(30),                                                              //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ValidAudience         = jwtConfig.Audience,                                                                    //Audience
                    ValidIssuer           = jwtConfig.Issuer,                                                                      //Issuer,这两项和前面签发jwt的设置一致
                    RequireExpirationTime = true,
                    IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtAuth:SecurityKey"])) //拿到SecurityKey
                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("App", policy => policy.RequireRole("App").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            #endregion

            #region 缓存配置
            services.AddMemoryCache();
            services.AddSingleton <ICacheService, MemoryCacheService>();
            RedisHelper.Initialization(new CSRedis.CSRedisClient(Configuration["Cache:Configuration"]));
            #endregion

            services.AddMvc().AddJsonOptions(option => {
                option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            services.AddSingleton(GetScheduler());

            #region Swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "FytSoa API",
                    Contact = new Contact {
                        Name = "feiyit", Email = "*****@*****.**", Url = ""
                    }
                });
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath       = Path.Combine(basePath, "FytSoa.Web.xml");
                var entityXmlPath = Path.Combine(basePath, "FytSoa.Core.xml");
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(entityXmlPath);
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT-Test: \"Authorization: Bearer {token}\"",
                    //jwt默认的参数名称
                    Name = "Authorization",
                    //jwt默认存放Authorization信息的位置(请求头中)
                    In   = "header",
                    Type = "apiKey"
                });
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:4909")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion

            #region 性能 压缩
            services.AddResponseCompression();
            #endregion

            //NLog 数据库配置
            //NLog.LogManager.Configuration.FindTargetByName<NLog.Targets.DatabaseTarget>("db").ConnectionString = Configuration.GetConnectionString("LogConnectionString");
        }
示例#12
0
文件: Startup.cs 项目: uvaa/ytjkb
        public void ConfigureServices(IServiceCollection services)
        {
            //自定注册
            AddAssembly(services, "FytSoa.Service");

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath         = new PathString("/fytadmin/login");
                o.SlidingExpiration = true;
                o.ExpireTimeSpan    = TimeSpan.FromHours(config.GetValue(KeyHelper.LOGINCOOKIEEXPIRES, 0.5D));
            })
            .AddJwtBearer(JwtAuthorizeAttribute.JwtAuthenticationScheme, o =>
            {
                var jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,                                                                        //是否验证Issuer
                    ValidateAudience         = true,                                                                        //是否验证Audience
                    ValidateIssuerSigningKey = true,                                                                        //是否验证SecurityKey
                    ValidateLifetime         = true,                                                                        //是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew
                    ClockSkew             = TimeSpan.FromSeconds(30),                                                       //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ValidAudience         = jwtConfig.Audience,                                                             //Audience
                    ValidIssuer           = jwtConfig.Issuer,                                                               //Issuer,这两项和前面签发jwt的设置一致
                    RequireExpirationTime = true,
                    IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JwtAuth:SecurityKey"])) //拿到SecurityKey
                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services
            .AddDataProtection(p => p.ApplicationDiscriminator = "ytjbk")
            .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(config["Cache:Configuration"]));

            services
            .AddAuthorization(options =>
            {
                options.AddPolicy("App", policy => policy.RequireRole("App").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            })
            .AddStackExchangeRedisCache(p => p.Configuration = config["Cache:Configuration"])
            .AddSingleton(HtmlEncoder.Create(UnicodeRanges.All))
            .AddSingleton(GetScheduler())
            .AddResponseCompression()
            .AddHttpClient()
            .AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.SetIsOriginAllowed(p => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            })
            .AddMvc(p =>
            {
                p.EnableEndpointRouting = false;
            })
            .AddNewtonsoftJson();


            services.Configure <KestrelServerOptions>(option => option.AllowSynchronousIO = true);
            services.Configure <IISServerOptions>(option => option.AllowSynchronousIO     = true);
        }
示例#13
0
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJWT(TokenModel tokenModel)
        {
            var dateTime = DateTime.UtcNow;
            var claims   = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()), //用户Id
                new Claim("Role", tokenModel.Role),                                //身份
                new Claim("Project", tokenModel.Project),                          //项目名称
                new Claim(JwtRegisteredClaimNames.Iat, dateTime.ToString(), ClaimValueTypes.Integer64)
            };
            //秘钥
            var jwtConfig = new JwtAuthConfigModel();
            var key       = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey));
            var creds     = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //过期时间
            int exp = 0;

            switch (tokenModel.TokenType.ToLower())
            {
            case "web":
                exp = jwtConfig.WebExp;
                break;

            case "app":
                exp = jwtConfig.AppExp;
                break;

            case "miniprogram":
                exp = jwtConfig.MiniProgramExp;
                break;

            case "other":
                exp = jwtConfig.OtherExp;
                break;
            }
            DateTime expires = DateTime.Now;

            switch (tokenModel.EffectiveTimeType)
            {
            case "year":
                expires = expires.AddYears(exp);
                break;

            case "month":
                expires = expires.AddMonths(exp);
                break;

            case "day":
                expires = expires.AddDays(exp);
                break;

            case "hours":
                expires = expires.AddHours(exp);
                break;

            case "min":
                expires = expires.AddMinutes(exp);
                break;

            case "sec":
                expires = expires.AddSeconds(exp);
                break;
            }
            var jwt = new JwtSecurityToken(
                issuer: "CoreApi",
                claims: claims, //声明集合
                expires: expires,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return(encodedJwt);
        }
示例#14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v0.1.0",
                    Title          = "学习Swagger",
                    Description    = "框架说明文档",
                    TermsOfService = "None",
                    Contact        = new Swashbuckle.AspNetCore.Swagger.Contact {
                        Name = "Learn.Swagger", Email = "*****@*****.**", Url = "https://www.facai.com"
                    }
                });
                //如果不加入以下两个xml 也是可以的 但是不会对api有中文说明,使用了一下两个xml 就需要对成员使用///注释
                //本webapi的xml
                var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "CoreApiSwagger.xml"); //这个就是刚刚配置的xml文件名
                c.IncludeXmlComments(xmlPath, true);                         //默认的第二个参数是false,这个是controller的注释,记得修改
                //如果不引用别的类库项目,那么以上就是一个webapi项目添加swagger服务的全部
                //webapi引用model的xml
                var xmlModelPath = Path.Combine(basePath, "CoreApiSwagger.xml"); //这个就是Model层的xml文件名
                c.IncludeXmlComments(xmlPath, true);                             //默认的第二个参数是false,这个是controller的注释,记得修改
                c.IncludeXmlComments(xmlModelPath);

                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
            });

            #endregion
            #region 认证
            services.AddAuthentication(x =>
            {
                //2、Authentication
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = jwtConfig.Issuer,
                    ValidAudience    = jwtConfig.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = true,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion
            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrClient", policy => policy.RequireRole("Admin", "Client").Build());
            });
            services.AddDefaultIdentity <IdentityUser>().AddRoles <IdentityRole>();
            #endregion
            #region CORS 跨域
            services.AddCors(c =>
            {
                c.AddPolicy("AllowAnyOrigin", policy =>
                {
                    policy.AllowAnyOrigin() //允许任何源
                    .AllowAnyMethod()       //允许任何方式
                    .AllowAnyHeader()       //允许任何头
                    .AllowCredentials();    //允许cookie
                });
                c.AddPolicy("AllowSpecificOrigin", policy =>
                {
                    policy.WithOrigins("http://localhost:8083")
                    .WithMethods("GET", "POST", "PUT", "DELETE")
                    .WithHeaders("authorization");
                });
            });
            #endregion
            #region Redis
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = BaseConfigModel.Configuration["Redis:ConnectionString"];
            });
            #endregion
            #region WebSockets
            services.AddSingleton <ICustomWebSocketFactory, CustomWebSocketFactory>();
            services.AddSingleton <ICustomWebSocketMessageHandler, CustomWebSocketMessageHandler>();
            #endregion
        }
示例#15
0
        public void ConfigureServices(IServiceCollection services)
        {
            AddAssembly(services, "FytSoa.Service");

            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <ITaskSchedulingService, TaskSchedulingService>();

            #region
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/fytadmin/login");
            })
            .AddCookie(BbsUserAuthorizeAttribute.BbsUserAuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/bbs/nologin");
            })
            .AddJwtBearer(JwtAuthorizeAttribute.JwtAuthenticationScheme, o =>
            {
                var jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ClockSkew             = TimeSpan.FromSeconds(30),
                    ValidAudience         = jwtConfig.Audience,
                    ValidIssuer           = jwtConfig.Issuer,
                    RequireExpirationTime = true,
                    IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtAuth:SecurityKey"]))
                };
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
            #endregion

            #region
            services.AddAuthorization(options =>
            {
                options.AddPolicy("App", policy => policy.RequireRole("App").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            #endregion

            #region
            services.AddMemoryCache();
            services.AddSingleton <ICacheService, MemoryCacheService>();
            RedisHelper.Initialization(new CSRedis.CSRedisClient(Configuration["Cache:Configuration"]));
            #endregion

            services.AddMvc().AddJsonOptions(option => {
                option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            #region Swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "FytSoa API",
                    Contact = new Contact {
                        Name = "feiyit", Email = "*****@*****.**", Url = ""
                    }
                });
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath       = Path.Combine(basePath, "FytSoa.Web.xml");
                var entityXmlPath = Path.Combine(basePath, "FytSoa.Core.xml");
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(entityXmlPath);
                //c.OperationFilter<SwaggerHeader>();

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT-Test: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:4909")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion

            #region
            services.AddResponseCompression();
            #endregion
        }
示例#16
0
        /// <summary>
        /// 服务注册配置应用程序的服务This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            #region 添加Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1.1.0",
                    Title   = "UIDP WebAPI",
                    //Description = "框架集合",
                    //TermsOfService = "None",
                    //Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Maverick", Email = "*****@*****.**", Url = "http://www.cnblogs.com/" }
                });
                //添加读取注释服务
                var basePath   = AppDomain.CurrentDomain.BaseDirectory;
                var apiXmlPath = Path.Combine(basePath, "UIDP.WebAPI.xml");
                c.IncludeXmlComments(apiXmlPath, true);
                var entityXmlPath = Path.Combine(basePath, "UIDP.Entity.xml");
                c.IncludeXmlComments(entityXmlPath, true);//控制器层注释(true表示显示控制器注释)
                //添加对控制器的标签(描述)
                //c.DocumentFilter<SwaggerDocTag>();
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
            });
            #endregion

            #region 认证
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = "UIDP",
                    ValidAudience    = "wr",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = true,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireClient", policy => policy.RequireRole("Client").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrClient", policy => policy.RequireRole("Admin,Client").Build());
            });
            #endregion

            #region 跨域CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
                c.AddPolicy("AllowSpecificOrigin", policy =>
                {
                    policy.WithOrigins("http://localhost:8083")//运行跨越访问的请求地址么,有多个的话用逗号隔开
                    .WithMethods("GET", "POST", "PUT", "DELETE")
                    .WithHeaders("authorization");
                });
            });
            #endregion
        }
示例#17
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//设置时间格式
            });

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1.1.0",
                    Title          = "Ray WebAPI",
                    Description    = "框架集合",
                    TermsOfService = "None",
                    Contact        = new Swashbuckle.AspNetCore.Swagger.Contact {
                        Name = "RayWang", Email = "*****@*****.**", Url = "http://www.cnblogs.com/RayWang"
                    }
                });
                //添加注释服务
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var apiXmlPath    = Path.Combine(basePath, "APIHelp.xml");
                var entityXmlPath = Path.Combine(basePath, "EntityHelp.xml");
                c.IncludeXmlComments(apiXmlPath, true);//控制器层注释(true表示显示控制器注释)
                c.IncludeXmlComments(entityXmlPath);

                //添加控制器注释
                //c.DocumentFilter<SwaggerDocTag>();

                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
            });
            #endregion

            #region 认证
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = "RayPI",
                    ValidAudience    = "wr",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = true,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireClient", policy => policy.RequireRole("Client").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrClient", policy => policy.RequireRole("Admin,Client").Build());
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:8083")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion
        }
示例#18
0
        public void ConfigureServices(IServiceCollection services)
        {
            //自定注册
            AddAssembly(services, "FytSoa.Service");

            //解决视图输出内容中文编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //services.AddAuthentication(options =>
            //{
            //    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            //    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            //})
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/fytadmin/login");
            })
            //新增一个新的方案
            .AddCookie(CompanyAuthorizeAttribute.CompanyAuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/company/login");
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
            {
                JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
                o.TokenValidationParameters  = new TokenValidationParameters
                {
                    ValidIssuer      = "FytSos",
                    ValidAudience    = "wr",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),

                    /***********************************TokenValidationParameters的参数默认值***********************************/
                    RequireSignedTokens = true,
                    // SaveSigninToken = false,
                    // ValidateActor = false,
                    // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    // 是否要求Token的Claims中必须包含 Expires
                    RequireExpirationTime = false,
                    // 允许的服务器时间偏移量
                    // ClockSkew = TimeSpan.FromSeconds(300),
                    // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
            });
            #endregion

            #region 授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireApp", policy => policy.RequireRole("App").Build());
                options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("RequireAdminOrApp", policy => policy.RequireRole("Admin,App").Build());
            });
            #endregion

            #region 缓存 读取配置是否使用哪种缓存模式
            services.AddMemoryCache();
            if (Convert.ToBoolean(Configuration["Cache:IsUseRedis"]))
            {
                services.AddSingleton <ICacheService, RedisCacheService>();
            }
            else
            {
                services.AddSingleton <ICacheService, MemoryCacheService>();
            }
            #endregion

            #region 缓存 RedisCache
            //将Redis分布式缓存服务添加到服务中
            services.AddDistributedRedisCache(options =>
            {
                //用于连接Redis的配置
                options.Configuration = Configuration["Cache:Configuration"];
                //Redis实例名RedisDistributedCache
                options.InstanceName = Configuration["Cache:RedisInstance"];
            });
            #endregion

            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/web/index", "/");
            });

            #region Swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "FytSoa API",
                    Contact = new Contact {
                        Name = "feiyit", Email = "*****@*****.**", Url = "http://www.feiyit.com"
                    }
                });
                var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath       = Path.Combine(basePath, "FytSoa.Web.xml");
                var entityXmlPath = Path.Combine(basePath, "FytSoa.Core.xml");
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(entityXmlPath);
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", new string[] { } },
                };
                //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                options.AddSecurityRequirement(security);
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    //jwt默认的参数名称
                    Name = "Authorization",
                    //jwt默认存放Authorization信息的位置(请求头中)
                    In   = "header",
                    Type = "apiKey"
                });
            });
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                c.AddPolicy("Any", policy =>
                {
                    policy.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });

                c.AddPolicy("Limit", policy =>
                {
                    policy
                    .WithOrigins("localhost:4909")
                    .WithMethods("get", "post", "put", "delete")
                    //.WithHeaders("Authorization");
                    .AllowAnyHeader();
                });
            });
            #endregion

            #region 性能 压缩
            services.AddResponseCompression();
            #endregion

            //NLog 数据库配置
            //NLog.LogManager.Configuration.FindTargetByName<NLog.Targets.DatabaseTarget>("db").ConnectionString = Configuration.GetConnectionString("LogConnectionString");
        }