コード例 #1
0
        public bool Validate(string encodeJwt, JWTTokenOptions setting)
        {
            var success = true;
            var jwtArr  = encodeJwt.Split('.');
            var header  = JsonConvert.DeserializeObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArr[0]));
            var payLoad = JsonConvert.DeserializeObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArr[1]));

            byte[] buffer = Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1]));

            var hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(setting.SecurityKey));

            //首先验证签名是否正确(必须的)
            //string encode = Base64UrlEncoder.Encode(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1]))));

            string sign = jwtArr[2];

            string path1     = Path.Combine(Directory.GetCurrentDirectory(), "key.public.json");
            string publicKey = File.ReadAllText(path1);

            var  rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, "", publicKey);
            bool bOK = rsa.Verify("", publicKey);

            //success = success && string.Equals(sign, decrypt);
            if (!success)
            {
                return(success);//签名不正确直接返回
            }

            //其次验证是否在有效期内(也应该必须)
            var now = ToUnixEpochDate(DateTime.UtcNow);

            success = success && (now >= long.Parse(payLoad["nbf"].ToString()) && now < long.Parse(payLoad["exp"].ToString()));

            return(success);
        }
コード例 #2
0
        public string GetToken(string userName, string password)
        {
            bool success = ((userName == "user") && (password == "111"));

            if (!success)
            {
                return("");
            }

            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            //创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Sid, userName),
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, "user"),
            };

            //创建令牌
            var token = new JwtSecurityToken(
                issuer: jwtTokenOptions.Issuer,
                audience: jwtTokenOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: jwtTokenOptions.Credentials
                );

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwtToken);
        }
コード例 #3
0
        public IActionResult TokenCustomerValidateTest()
        {
            Dictionary <string, object> payLoad = new Dictionary <string, object>();

            payLoad.Add("sub", "rober");
            payLoad.Add("jti", Guid.NewGuid().ToString());
            payLoad.Add("nbf", null);
            payLoad.Add("exp", null);
            payLoad.Add("iss", "roberIssuer");
            payLoad.Add("aud", "roberAudience");
            payLoad.Add("age", 30);

            var encodeJwt = JWTTokenOptions.CreateToken(payLoad, 30);

            var result = JWTTokenOptions.Validate(encodeJwt, (load) =>
            {
                var success = true;
                //验证是否包含aud 并等于 roberAudience
                success = success && load["aud"]?.ToString() == "roberAudience";

                //验证age>20等
                int.TryParse(load["age"].ToString(), out int age);
                //Assert.IsTrue(age > 30);
                //其他验证 jwt的标识 jti是否加入黑名单等

                return(success);
            });

            //Assert.IsTrue(result);
            return(Content(""));
        }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: SSM416/SSO
        public string GetToken(string UserName = "******")
        {
            JWTTokenOptions jwtModel = new JWTTokenOptions();
            //下面代码自行封装
            //var claims = new List<Claim>();
            //claims.AddRange(new[]
            //{
            //    new Claim("UserName", UserName),
            //    new Claim(JwtRegisteredClaimNames.Sub, UserName),
            //    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            //    new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            //});
            //创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Sid, UserName),
                new Claim(ClaimTypes.Name, UserName),
                new Claim(ClaimTypes.Role, "user"),
            };
            DateTime now = DateTime.UtcNow;
            var      jwtSecurityToken = new JwtSecurityToken(
                issuer: jwtModel.Issuer,
                audience: jwtModel.Audience,
                claims: claims,
                notBefore: now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtModel.SecurityKey)), SecurityAlgorithms.HmacSha256)
                );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return(token);
        }
コード例 #5
0
        public async Task <string> GetToken(string username)
        {
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions(webApiConfig.JWTIssuer, webApiConfig.JWTAudience, webApiConfig.JWTSecurityKey, webApiConfig.JWTExpires);

            //创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Sid, username),
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.Role, "user"),
            };

            //创建令牌
            var token = new JwtSecurityToken(
                issuer: jwtTokenOptions.Issuer,
                audience: jwtTokenOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(webApiConfig.JWTExpires),
                signingCredentials: jwtTokenOptions.Credentials
                );

            string jwtToken = await Task.Run(() => new JwtSecurityTokenHandler().WriteToken(token));

            return(jwtToken);
        }
コード例 #6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="services"></param>
 /// <param name="_tokenOptions"></param>
 private static void _AddJwt(IServiceCollection services, JWTTokenOptions _tokenOptions)
 {
     services.AddSingleton(_tokenOptions);
     services.AddSingleton <IJWTFactory, JWTFactory>();
     services.AddAuthentication(x =>
     {
         x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
         x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
     }).AddJwtBearer(jwtOptions =>
     {
         jwtOptions.TokenValidationParameters = new TokenValidationParameters
         {
             IssuerSigningKey = _tokenOptions.Key,
             ValidAudience    = _tokenOptions.Audience,
             ValidIssuer      = _tokenOptions.Issuer,
             ValidateLifetime = true
         };
         jwtOptions.Events = new JwtBearerEvents()
         {
             OnMessageReceived = context =>
             {
                 context.Token = context.HttpContext.Request.Headers[_tokenOptions.TokenName];
                 return(Task.CompletedTask);
             }
         };
     });
 }
コード例 #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Filter
            services.AddControllers(o =>
            {
                o.Filters.Add(typeof(CustomExceptionFilterAttribute));
                o.Filters.Add(typeof(LogActionFilterAttribute));
            });
            #endregion
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Zhaoxi.MSACommerce.UserMicroservice", Version = "v1"
                });
            });
            #region  务注入
            services.AddTransient <OrangeContext, OrangeContext>();
            services.AddTransient <CacheClientDB, CacheClientDB>();
            services.AddTransient <IUserService, UserService>();
            #endregion

            #region 配置文件注入
            services.Configure <MySqlConnOptions>(this.Configuration.GetSection("MysqlConn"));
            services.Configure <RedisConnOptions>(this.Configuration.GetSection("RedisConn"));
            #endregion

            #region jwt校验  HS
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            Configuration.Bind("JWTTokenOptions", tokenOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //JWT有一些默认的属性,就是给鉴权时就可以筛选了
                    ValidateIssuer           = true,                  //是否验证Issuer
                    ValidateAudience         = true,                  //是否验证Audience
                    ValidateLifetime         = false,                 //是否验证失效时间
                    ValidateIssuerSigningKey = true,                  //是否验证SecurityKey
                    ValidAudience            = tokenOptions.Audience, //
                    ValidIssuer      = tokenOptions.Issuer,           //Issuer,这两项和前面签发jwt的设置一致
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))
                };
            });
            #endregion
            #region 跨域
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("default", policy =>
            //    {
            //        policy.AllowAnyOrigin()
            //            .AllowAnyHeader()
            //            .AllowAnyMethod();
            //    });
            //});
            #endregion
        }
コード例 #8
0
 public JWTTokenController(JWTTokenOptions tokenOptions
                           , JwtTokenHelper jwtTokenHelper
                           , IUserService userService)
 {
     this.tokenOptions   = tokenOptions;
     this.jwtTokenHelper = jwtTokenHelper;
     this.userService    = userService;
 }
コード例 #9
0
 public JWTHSAuthorizeMiddleware(RequestDelegate next,
                                 DBRouteValueDictionary routeDict,
                                 MyConfig myConfig)
 {
     this._next      = next;
     this.routeDict  = routeDict;
     jWTTokenOptions = myConfig.JWTTokenOptions;
 }
コード例 #10
0
ファイル: TokenController.cs プロジェクト: SAMLITS/ECP.B2B
 public TokenController(
     JWTTokenOptions tokenOptions,
     IUserClient _userClient,
     IUserFunctionClient _userFunctionClient)
 {
     _tokenOptions      = tokenOptions;
     userClient         = _userClient;
     userFunctionClient = _userFunctionClient;
 }
コード例 #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <ICustomJWTService, CustomHSJWTService>();
            services.Configure <ConfigInformation>(Configuration.GetSection("ConfigInformation"));

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "authwebapi", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description  = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme       = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            #region jwt校验  HS
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            Configuration.Bind("JWTTokenOptions", tokenOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //JWT有一些默认的属性,就是给鉴权时就可以筛选了
                    ValidateIssuer           = true,                                                              //是否验证Issuer
                    ValidateAudience         = true,                                                              //是否验证Audience
                    ValidateLifetime         = true,                                                              //是否验证失效时间
                    ValidateIssuerSigningKey = true,                                                              //是否验证SecurityKey
                    ValidAudience            = tokenOptions.Audience,                                             //
                    ValidIssuer      = tokenOptions.Issuer,                                                       //Issuer,这两项和前面签发jwt的设置一致
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)) //拿到SecurityKey
                };
            });
            #endregion
        }
コード例 #12
0
 public TokenProviderMiddleware(
     RequestDelegate next,
     IOptions <JWTTokenOptions> options,
     IAuthenticationSchemeProvider schemes
     )
 {
     _next    = next;
     _options = options.Value;
     Schemes  = schemes;
 }
コード例 #13
0
        public int SaveAuthorize(string SecurityKey)
        {
            JWTTokenOptions jWTTokenOptions = new JWTTokenOptions();

            jWTTokenOptions.Audience    = myConfig.JWTTokenOptions.Audience;
            jWTTokenOptions.Issuer      = myConfig.JWTTokenOptions.Issuer;
            jWTTokenOptions.SecurityKey = SecurityKey;
            jsonFileHelper.Write <JWTTokenOptions>("JWTTokenOptions", jWTTokenOptions);
            myConfig.JWTTokenOptions = jWTTokenOptions;
            return(100);
        }
コード例 #14
0
ファイル: Startup.cs プロジェクト: SSM416/SSO
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            services.AddControllers();
            // 注册Swagger服务
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "SSOServiceAPI", Version = "v1"
                });
            });
            //注册数据库连接
            services.AddScoped <DbContext, LeoGXGDBContext>();
            string LeoGXGDB_base_connection = Configuration.GetConnectionString("LeoGXGDBContextReadDataBase");

            services.AddDbContext <LeoGXGDBContext>(options => options.UseSqlServer(LeoGXGDB_base_connection));


            //cookies
            services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", options =>
            {
                options.Cookie.Name    = "myCookie";            //设置统一的Cookie名称
                options.LoginPath      = "/Home/Index";
                options.Cookie.Domain  = "localhost";           //设置Cookie的域为根域,这样所有子域都可以发现这个Cookie
                options.ExpireTimeSpan = new TimeSpan(1, 0, 0); //默认14天
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenOptions.Key,

                    ValidateIssuer = true,
                    ValidIssuer    = jwtTokenOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtTokenOptions.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(5)
                };
            });
            //services.Configure<JwtConfig>(Configuration.GetSection("Authentication:JwtBearer"));
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
        }
コード例 #15
0
ファイル: Startup.cs プロジェクト: SAMLITS/ECP.B2B
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // 从文件读取密钥
            string keyDir = PlatformServices.Default.Application.ApplicationBasePath;

            if (RSAUtils.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
            {
                keyParams = RSAUtils.GenerateAndSaveKey(keyDir);
            }
            JWTTokenOptions _tokenOptions = new JWTTokenOptions();

            _tokenOptions.Key         = new RsaSecurityKey(keyParams);
            _tokenOptions.Issuer      = "EcpB2bIssuer"; // 签发者名称
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);
            // 添加到 IoC 容器  有可能报错  改为不是单例
            services.AddSingleton(_tokenOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = _tokenOptions.Key,
                    ValidAudience    = _tokenOptions.Audience,
                    ValidIssuer      = _tokenOptions.Issuer,
                    ValidateLifetime = true
                };
            });

            services.AddDataProtection(options =>
            {
                options.ApplicationDiscriminator = "localhost";
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Domain = "localhost";
                options.Cookie.Name   = ".AspNetCore.Cookies";
            });

            services.AddMvc();


            return
                (Util.AutofacIoc.AutofacHelp.AutofacProviderBuilderCore(
                     services,
                     ApplicationContainer,
                     new B2b.ClientRegisterModuleIoc.GrpcClientModule()
                     ));
        }
コード例 #16
0
        /// <summary>
        /// 启用Jwt验证
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hosting"></param>
        public static void AddJwt(this IServiceCollection services, IWebHostEnvironment hosting)
        {
            // 从文件读取密钥
            string keyDir = hosting.ContentRootPath;

            if (!EncryptorHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams))
            {
                keyParams = EncryptorHelper.GenerateRSAKeysAndSave(keyDir);
            }
            JWTTokenOptions _tokenOptions = new JWTTokenOptions();

            _tokenOptions.Key         = new RsaSecurityKey(keyParams);
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);

            _AddJwt(services, _tokenOptions);
        }
コード例 #17
0
 public static void ConfigureJwt(this IServiceCollection services, JWTTokenOptions tokenOptions)
 {
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
     {
         opt.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateAudience = true,
             ValidAudience    = tokenOptions.Audience,
             ValidateIssuer   = true,
             ValidIssuer      = tokenOptions.Issuer,
             ValidateLifetime = true,
             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),
             ClockSkew        = TimeSpan.Zero,
         };
     });
 }
コード例 #18
0
        public string Validate(string encodeJwt, JWTTokenOptions setting)
        {
            string msg = "";

            try
            {
                var success = true;
                var jwtArr  = encodeJwt.Split('.');
                var header  = JsonConvert.DeserializeObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArr[0]));
                var payLoad = JsonConvert.DeserializeObject <Dictionary <string, string> >(Base64UrlEncoder.Decode(jwtArr[1]));

                //首先验证签名是否正确(必须的)
                var    hs256  = new HMACSHA256(Encoding.ASCII.GetBytes(setting.SecurityKey));
                byte[] buffer = Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1]));
                string encode = Base64UrlEncoder.Encode(hs256.ComputeHash(buffer));
                string sign   = jwtArr[2];

                success = string.Equals(sign, encode);
                if (!success)
                {
                    msg = "签名不正确";
                    return(msg);//签名不正确直接返回
                }

                //其次验证是否在有效期内(也应该必须)
                var now = ToUnixEpochDate(DateTime.UtcNow);
                success = (now < long.Parse(payLoad["exp"].ToString()));
                if (!success)
                {
                    msg = "授权码不在有效期内";
                    return(msg);//签名不正确直接返回
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }

            return(msg);
        }
コード例 #19
0
        public static void AddSiteRegisterJwt(this IServiceCollection services, string Issuer, string audience)
        {
            // 从文件读取密钥
            JWTTokenOptions _tokenOptions = new JWTTokenOptions();
            string          keyDir        = PlatformServices.Default.Application.ApplicationBasePath;

            if (RSAUtils.TryGetKeyParameters(keyDir, false, out RSAParameters keyparams) == false)
            {
                _tokenOptions.Key = default(RsaSecurityKey);
            }
            else
            {
                _tokenOptions.Key = new RsaSecurityKey(keyparams);
            }
            _tokenOptions.Issuer      = Issuer;   // 设置签发者
            _tokenOptions.Audience    = audience; // 设置签收者,也就是这个应用服务器的名称
            _tokenOptions.Credentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               //.AddRequirements(new ValidJtiRequirement()) // 添加上面的验证要求
                               .Build());
            });
            // 注册验证要求的处理器,可通过这种方式对同一种要求添加多种验证
            //services.AddSingleton<IAuthorizationHandler, ValidJtiHandler>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = _tokenOptions.Key,
                    ValidAudience    = _tokenOptions.Audience,
                    ValidIssuer      = _tokenOptions.Issuer,
                    ValidateLifetime = true
                };
            });
        }
コード例 #20
0
ファイル: Startup.cs プロジェクト: zhimaxu/MixAuth
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                //认证失败,会自动跳转到这个地址
                options.LoginPath = "/Home/Login";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenOptions.Key,

                    ValidateIssuer = true,
                    ValidIssuer    = jwtTokenOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtTokenOptions.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(5)
                };
            });

            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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
コード例 #21
0
        public string GetToken(string UserName = "******")
        {
            JWTTokenOptions jwtModel = new JWTTokenOptions();

            //创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Sid, UserName),
                new Claim(ClaimTypes.Name, UserName),
                new Claim(ClaimTypes.Role, "user"),
            };
            DateTime now = DateTime.UtcNow;
            var      jwtSecurityToken = new JwtSecurityToken(
                issuer: jwtModel.Issuer,
                audience: jwtModel.Audience,
                claims: claims,
                notBefore: now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtModel.SecurityKey)), SecurityAlgorithms.HmacSha256)
                );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return(token);
        }
コード例 #22
0
ファイル: JWTHSService.cs プロジェクト: wangpeng81/ApiDoc
 public JWTHSService(MyConfig myConfig)
 {
     this.jwtTokenOptions = myConfig.JWTTokenOptions;
 }
コード例 #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c => c.AddPolicy("any", p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()));

            services.AddControllers();

            // 注入动态api
            services.AddDynamicWebApi();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Zhaoxi.AglieFramework.BBS", Version = "v1"
                });
                c.DocInclusionPredicate((docName, description) => true);
            });

            #region jwt校验  HS
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            Configuration.Bind("JWTTokenOptions", tokenOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)            //Scheme
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    //JWT有一些默认的属性,就是给鉴权时就可以筛选了
                    ValidateIssuer           = true,                                                               //是否验证Issuer
                    ValidateAudience         = true,                                                               //是否验证Audience
                    ValidateLifetime         = true,                                                               //是否验证失效时间
                    ValidateIssuerSigningKey = true,                                                               //是否验证SecurityKey
                    ValidAudience            = tokenOptions.Audience,                                              //
                    ValidIssuer      = tokenOptions.Issuer,                                                        //Issuer,这两项和前面签发jwt的设置一致
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)), //拿到SecurityKey
                };
            });
            //定义了一个权限策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("LevelPolicy",
                                  policyBuilder => policyBuilder.RequireAssertion(context =>
                                                                                  int.Parse(context.User.Claims.First(c => c.Type.Equals("UserLevel")).Value) >= 4//UserLevel属性大于3
                                                                                  ));
            });
            #endregion
            #region HS256
            services.AddScoped <IJWTService, JWTHSService>();
            services.Configure <JWTTokenOptions>(this.Configuration.GetSection("JWTTokenOptions"));

            services.Configure <MySqlConnOptions>(this.Configuration.GetSection("MySqlConn"));

            #endregion

            #region MyRegion
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IPostsService, PostsService>();
            services.AddScoped <IPostTypeService, PostTypeService>();
            services.AddScoped <IReplyService, ReplyService>();
            services.AddScoped <IDbService, DbService>();


            #endregion

            #region redis
            services.Configure <RedisConnOptions>(this.Configuration.GetSection("RedisConn"));
            // 依赖注入   这个地方不太好
            services.AddScoped <CacheClientDB, CacheClientDB>();

            services.Configure <MySqlConnOptions>(this.Configuration.GetSection("MySqlConn"));
            services.AddSingleton <DBConnectFactory, DBConnectFactory>();
            #endregion
        }
コード例 #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            #region 跨域
            var isTrueStr  = configuration["HttpKYUrls:isTrue"];
            var httpUrlStr = configuration["HttpKYUrls:urlStr"];
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSameDomainHttp", builder =>
                {
                    if (isTrueStr.Equals("true") && !string.IsNullOrWhiteSpace(httpUrlStr))
                    {
                        this.logger.LogInformation("注册跨域请求,指定路由为:" + httpUrlStr);
                        builder.WithOrigins(httpUrlStr.Split(','))
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();      //允许处理cookie
                    }
                    else
                    {
                        this.logger.LogInformation("注册跨域请求,允许所有主机访问");
                        builder.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin() //允许所有来源的主机访问
                        .AllowCredentials();
                    }
                });
            });


            #endregion


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddOptions();
            services.Configure <WebApiConfig>(configuration.GetSection("WebApiConfig"));
            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(connStr,
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());
            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
            // services.AddSingleton<IEventBus, PassThroughEventBus>();
            services.AddDbContext <WebApiDbContext>(options => options.UseSqlServer(connStr));


            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };
            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IEventHandlerExecutionContext>(),
                                                                         RMQ_EXCHANGE,
                                                                         queueName: RMQ_QUEUE));

            #region 用户登录验证
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions(
                configuration["WebApiConfig:JWTIssuer"],
                configuration["WebApiConfig:JWTAudience"],
                configuration["WebApiConfig:JWTSecurityKey"],
                Convert.ToInt32(configuration["WebApiConfig:JWTExpires"])
                );

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                //认证失败,会自动跳转到这个地址
                options.LoginPath = "/Home/Login";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenOptions.Key,

                    ValidateIssuer = true,
                    ValidIssuer    = jwtTokenOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtTokenOptions.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(Convert.ToInt32(configuration["WebApiConfig:JWTClockSkew"]))
                };
            });

            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;
            });
            #endregion

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
コード例 #25
0
 public TokenController(JWTTokenOptions tokenOptions, AuthDbContext dbContext)
 {
     _tokenOptions = tokenOptions;
     _dbContext    = dbContext;
 }
コード例 #26
0
ファイル: JWTRSService.cs プロジェクト: wangpeng81/ApiDoc
 public JWTRSService(MyConfig myConfig)
 {
     this._JWTTokenOptions = myConfig.JWTTokenOptions;
 }
コード例 #27
0
        //private readonly ILogger _logger;
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            /*
             * ********************RateLimit***********************
             */
            // needed to load configuration from appsettings.json
            services.AddOptions();

            // needed to store rate limit counters and ip rules
            services.AddMemoryCache();

            //load general configuration from appsettings.json
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            //load ip rules from appsettings.json
            services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

            // inject counter and rules stores
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            services.Configure <RedisSetting>(Configuration);
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.Secure = CookieSecurePolicy.None;
            });
            //HealthyChecks
            //具体信息参照源码 https://github.com/xabaril/AspNetCore.Diagnostics.HealthChecks
            //services.AddHealthChecks()
            //    .AddMySql(Configuration.GetConnectionString("DefaultConnection"))
            //    .AddRedis(Configuration.GetConnectionString("RedisConnection")
            //);
            //services.AddHealthChecksUI();

            //mysql
            //多个数据库上下文可以使用池减少开销,略微增加性能
            services.AddDbContext <BaseEduContext>(options =>
                                                   options.UseLazyLoadingProxies().UseMySql(
                                                       Configuration.GetConnectionString("DefaultConnection"),
                                                       //弹性连接,命令超时
                                                       mySqlOptions => mySqlOptions.EnableRetryOnFailure().CommandTimeout(3)));
            //PostGre
            //services.AddDbContextPool<BaseEduContext>(options =>
            //    options.UseLazyLoadingProxies().UseNpgsql(
            //        Configuration.GetConnectionString("PostGreSQLConnection"),
            //        //弹性连接,命令超时
            //        mySqlOptions => mySqlOptions.EnableRetryOnFailure().CommandTimeout(3)));

            //
            services.AddTransient(typeof(IAsyncRepository <>), typeof(SugarRepository <>));
            services.AddTransient(typeof(IRepository <>), typeof(SugarRepository <>));
            services.AddScoped <IAccount, Account>();
            services.AddScoped <IRabbitMQDealJanus, RabbitMQDealJanus>();
            services.AddSingleton <IEsClientProvider, EsClientProvider>();
            services.AddMediatR(typeof(PingHandler).Assembly,
                                typeof(Pong1).Assembly, typeof(Pong2).Assembly);
            //services.AddSingleton<RpcClient>();
            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings = sp.GetRequiredService <IOptions <RedisSetting> >().Value;
                //也可以直接使用Configuration获取redis连接信息
                var configuration        = ConfigurationOptions.Parse(settings.RedisConnectionString, true);
                configuration.ResolveDns = true;
                return(ConnectionMultiplexer.Connect(configuration));
            });
            //services.AddHostedService<TimedHostedService>();
            //services.AddHostedService<RabbitHostedService>();

            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(x =>
            {
                x.LoginPath      = new PathString("/Account/Login");
                x.ExpireTimeSpan = new TimeSpan(0, 0, 30, 0, 0);
                //x.CookieSecure = CookieSecurePolicy.None;
                x.Cookie.SecurePolicy = CookieSecurePolicy.None;
                //x.AccessDeniedPath = "";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,

                    //颁发机构
                    ValidIssuer = "https://localhost:44343/",
                    //颁发给谁
                    ValidAudience = "api",
                    //签名秘钥
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Consts.Secret))
                };
            });

            //
            services.AddControllersWithViews(options =>
            {
                //options.RespectBrowserAcceptHeader = true; // false by default

                //options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());

                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                options.Filters.Add(typeof(ValidateModelStateFilter));
            })
            //忽略循环引用
            //.AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
            .SetCompatibilityVersion(CompatibilityVersion.Latest);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
            //services.AddSwaggerGenNewtonsoftSupport();
            services.AddCors(options =>
            {
                options.AddPolicy("janus", p => p.AllowAnyOrigin());
            });

            // https://github.com/aspnet/Hosting/issues/793
            // the IHttpContextAccessor service is not registered by default.
            // the clientId/clientIp resolvers use it.
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // configuration (resolvers, counter key builders)
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            services.AddSignalR();
            //使用autofac替换容器后,启动速度会慢很多。
            services.AddOptions();
            //var container = new ContainerBuilder();
            //container.Populate(services);
            ////向容器注入服务示例
            ////container.RegisterType<Account>().AsSelf().As<IAccount>().InstancePerLifetimeScope();
            ////container.RegisterGeneric(typeof(SugarRepository<>)).As(typeof(IRepository<>));
            //return new AutofacServiceProvider(container.Build());
        }
コード例 #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();
            services.AddCors(
                option => option.AddPolicy("cors",
                                           policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials()
                                           //地址最后不要加斜杠“/”(((φ(◎ロ◎;)φ)))
                                           .WithOrigins(Configuration.GetSection("SiteSetting:CorsOrigin").Get <string[]>())));
            //services.AddControllersWithViews().AddControllersAsServices()
            //    .AddRazorRuntimeCompilation();
            services.AddCustomMvc();


            services.Configure <FileManagerOptions>(options => Configuration.GetSection("FileOptions").Bind(options));

            services.AddAutoMapper(
                configAction =>
            {
                configAction.AddAutoMaperConfig(typeof(UserDto).Assembly, typeof(PluginInfoDto).Assembly);
            },
                new Assembly[] { });

            services.AddEFCore(Configuration, option =>
            {
                switch (option.FactoryName)
                {
                case "sfdb":
                    {
                        option.EntityAssemblies.Add(typeof(User).Assembly);
                        option.EntityAssemblies.Add(typeof(PluginInfo).Assembly);
                        break;
                    }
                }
            });

#if DEBUG
            //services.AddServices(new Assembly[] { typeof(Docker.Crawler.CrawlerOptions).Assembly });
#endif
            services.AddServices(new Assembly[] { typeof(UserService).Assembly });


            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();
            services.AddSingleton <JWTTokenOptions>(provider => jwtTokenOptions);
            //cookies登陆
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.Cookie.Name     = "qystack.top";
                o.Cookie.HttpOnly = false;

                //o.LoginPath = new PathString("/Home/Index");
                //o.LogoutPath = new PathString("/Account/Login");
                //开启跨域cookie
                o.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // 是否验证颁发者
                    ValidateIssuer = true,
                    // 是否验证访问群体
                    ValidateAudience = true,
                    // 是否验证生存期
                    ValidateLifetime = true,
                    // 验证Token的时间偏移量
                    ClockSkew = TimeSpan.FromSeconds(30),
                    // 是否验证安全密钥
                    ValidateIssuerSigningKey = true,
                    // 访问群体
                    ValidAudience = jwtTokenOptions.Audience,
                    // 颁发者
                    ValidIssuer = jwtTokenOptions.Issuer,
                    // 安全密钥
                    IssuerSigningKey = jwtTokenOptions.Key,
                };
            });
            //.AddQQ(options =>
            //{
            //    options.ClientId = Configuration["OAuths:QQ:ClientId"];
            //    options.ClientSecret = Configuration["OAuths:QQ:ClientSecret"];
            //});

            services.AddCache(config => config.UseInMemory());;
            services.AddScoped <IEnviromentContext, EnviromentContext>();
            services.AddAutoMigration(options =>
            {
                options.MigrationPath  = Path.Combine("app_data", "Migrations");
                options.BackupBasePath = Path.Combine("app_data", "MigrationsBackup");
#if DEBUG
                options.PgDumpPath = @"E:\Program Files\PostgreSQL\10\bin";
#endif
            });
            services.AddSearchEngine(new LuceneIndexerOptions()
            {
                Path = Path.Combine("app_data", "lucene_index")
            });
            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] {
                UnicodeRanges.All
            }));
            services.ConfigureDynamicProxy(
                config => config.AddInterceptor(Configuration)
                );


            services.PluginSetup(Configuration);
            services.AddHangFire(Configuration);
            services.AddCapWithRabbitMQ(Configuration, options => { options.UseDashboard(); });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddIpRateLimitings(Configuration);
        }
コード例 #29
0
ファイル: Startup.cs プロジェクト: Lio98/BlogManagement
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Appsettings(Configuration));
            services.AddSingleton <BlogActionFilter>();
            services.AddScoped(typeof(IUser), typeof(UserDal));
            services.AddSingleton(typeof(ILog), typeof(LogDal));


            services.AddControllers(option =>
            {
                option.Filters.Add <BlogExceptionFilter>();
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver(); //使用驼峰
                options.SerializerSettings.DateTimeZoneHandling  = DateTimeZoneHandling.Local;
                options.SerializerSettings.DateFormatString      = "yyyy-MM-dd HH:mm:ss";                        //设置时间格式
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;                 //忽略循环引用
                //options.SerializerSettings.Converters.Add(new UnixTimeStampConverter());
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 跨域

            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.WithOrigins("*");
                });
            });

            #endregion

            #region JWTToken
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();
            services.Configure <JWTTokenOptions>(this.Configuration.GetSection("JWTToken"));
            jwtTokenOptions = this.Configuration.GetSection("JWTToken").Get <JWTTokenOptions>();
            //configuration.Bind("JWTToken", jwtTokenOptions);
            services.AddSingleton <JWTTokenOptions>(jwtTokenOptions);

            services.AddAuthentication(option =>
            {
                //认证middleware配置
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    //获取或设置要使用的Microsoft.IdentityModel.Tokens.SecurityKey用于签名验证
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenOptions.Secret)),
                    //获取或设置一个string,它表示将使用的有效发行者检查代币的发行者
                    ValidIssuer = jwtTokenOptions.Issuer,
                    //获取或设置一个字符串,该字符串表示将用于检查的有效受众反对令牌的观众
                    ValidAudience    = jwtTokenOptions.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false,
                    //允许的服务器时间偏移量
                    ClockSkew = TimeSpan.Zero,
                    //是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true
                };
                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            #endregion

            #region Swagger

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("V1", new OpenApiInfo
                {
                    Version     = "V1",
                    Title       = "BlogManagement API Doc-V1",
                    Description = "BlogManagement API接口文档-V1版",
                    Contact     = new OpenApiContact {
                        Name = "BlogSystem", Email = "*****@*****.**"
                    },
                });
                options.OrderActionsBy(x => x.RelativePath);

                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "BlogManagement.xml"));

                options.OperationFilter <AddResponseHeadersFilter>();
                options.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();
                options.OperationFilter <SecurityRequirementsOperationFilter>();

                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
                {
                    Description  = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer",
                    Type         = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference()
                            {
                                Id = "Bearer", Type = ReferenceType.SecurityScheme
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });

            #endregion
        }
コード例 #30
0
 public LoginController(JWTTokenOptions jwtTokenOptions, IUser user)
 {
     this._jwtTokenOptions = jwtTokenOptions;
     this._user            = user;
 }