/// <summary>
        /// 注入Token生成器参数,在token生成项目的Startup的ConfigureServices中使用
        /// </summary>
        /// <param name="services">IServiceCollection</param>
        /// <param name="issuer">发行人</param>
        /// <param name="audience">订阅人</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        public static IServiceCollection AddJTokenBuild(this IServiceCollection services, string issuer, string audience, string secret)
        {
            var signingCredentials    = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)), SecurityAlgorithms.HmacSha256);
            var permissionRequirement = new PermissionRequirement(
                issuer,
                audience,
                signingCredentials,
                "True"
                );

            return(services.AddSingleton(permissionRequirement));
        }
        /// <summary>
        /// 注入Ocelot jwt策略,在业务API应用中的Startup的ConfigureServices调用
        /// </summary>
        /// <param name="services">IServiceCollection</param>
        /// <param name="issuer">发行人</param>
        /// <param name="audience">订阅人</param>
        /// <param name="secret">密钥</param>
        /// <param name="defaultScheme">默认架构</param>
        /// <param name="policyName">自定义策略名称</param>
        /// <param name="openJWT">是否开启jwt验证</param>
        /// <param name="isHttps">是否https</param>
        /// <returns></returns>
        public static AuthenticationBuilder AddOcelotPolicyJwtBearer(this IServiceCollection services,
                                                                     string issuer, string audience, string secret, string defaultScheme, string policyName, string openJWT, bool isHttps = false)
        {
            var keyByteArray = Encoding.UTF8.GetBytes(secret);
            var signingKey   = new SymmetricSecurityKey(keyByteArray);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = issuer,   //发行人
                ValidateAudience      = true,
                ValidAudience         = audience, //订阅人
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
                RequireExpirationTime = true,
            };
            var signingCredentials    = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var permissionRequirement = new PermissionRequirement(
                issuer,
                audience,
                signingCredentials,
                openJWT
                );

            //注入授权Handler
            services.AddSingleton <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);
            return(services.AddAuthorization(options =>
            {
                options.AddPolicy(policyName,
                                  policy => policy.Requirements.Add(permissionRequirement));
            })
                   .AddAuthentication(options =>
            {
                options.DefaultScheme = defaultScheme;
            })
                   .AddJwtBearer(defaultScheme, o =>
            {
                //不使用https
                o.RequireHttpsMetadata = isHttps;
                o.TokenValidationParameters = tokenValidationParameters;
            }));
        }
示例#3
0
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="permissionRequirement"></param>
        /// <param name="clientType"></param>
        /// <param name="TokenType">1.token   2 refreshToken</param>
        /// <returns></returns>
        public static dynamic BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement, AuthClientType clientType)
        {
            double expiresIn             = 2 * 60 * 60 * 1000;
            double refreshTokenExpiresIn = 24 * 60 * 60 * 1000;

            switch (clientType)
            {
            case AuthClientType.Web:                        //SAAS后台
                refreshTokenExpiresIn = 8 * 60 * 60 * 1000; //设置成8小时
                break;

            case AuthClientType.Wehcat:                          //小程序
                refreshTokenExpiresIn = 7 * 24 * 60 * 60 * 1000; //设置成7天  用于小程序客户端之类的,能确保一周永久在线
                break;

            default:
                refreshTokenExpiresIn = 7 * 24 * 60 * 60 * 1000;
                break;
            }

            var now       = DateTime.Now;
            var jwt_token = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMilliseconds(expiresIn)),
                //expires: now.Add(TimeSpan.FromMilliseconds(5 * 60 * 1000)),
                signingCredentials: permissionRequirement.SigningCredentials
                );

            //用于refresh使用的 jwt
            var jwt_refreshtoken = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMilliseconds(refreshTokenExpiresIn)),
                //expires: now.Add(TimeSpan.FromMilliseconds(1000 * 60 * 10)),
                signingCredentials: permissionRequirement.SigningCredentials
                );

            var encodedJwt_Token        = new JwtSecurityTokenHandler().WriteToken(jwt_token);
            var encodedJwt_RefreshToken = new JwtSecurityTokenHandler().WriteToken(jwt_refreshtoken);

            var responseTokenJson = new
            {
                access_token = encodedJwt_Token,
                expires      = now.Add(TimeSpan.FromMilliseconds(expiresIn)),
                expires_in   = expiresIn,
                //expires = now.Add(TimeSpan.FromMilliseconds(5 * 60 * 1000)),
                //expires_in = 5 * 60 * 1000,
                token_type           = "Bearer",
                refresh_access_token = new
                {
                    refresh_token = encodedJwt_RefreshToken,
                    expires       = now.Add(TimeSpan.FromMilliseconds(refreshTokenExpiresIn)),
                    expires_in    = refreshTokenExpiresIn
                                    //expires = now.Add(TimeSpan.FromMilliseconds(1000 * 60 * 10)),
                                    //expires_in = 1000 * 60 * 10
                }
            };

            return(responseTokenJson);
        }