Esempio n. 1
0
        public void ConfigureServices(IServiceCollection services)
        {
            //读取配置文件
            var audienceConfig            = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64      = audienceConfig["Secret"];
            var keyByteArray              = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey                = new SymmetricSecurityKey(keyByteArray);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = audienceConfig["Issuer"],   //发行人
                ValidateAudience      = true,
                ValidAudience         = audienceConfig["Audience"], //订阅人
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero,
                RequireExpirationTime = true,
            };
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //这个集合模拟用户权限表,可从数据库中查询出来
            var permission = new List <Permission> {
                new Permission {
                    Url = "/Goods.Goodser/GetGoods", Name = "admin"
                },
                new Permission {
                    Url = "systemapi", Name = "system"
                }
            };
            //如果第三个参数,是ClaimTypes.Role,上面集合的每个元素的Name为角色名称,如果ClaimTypes.Name,即上面集合的每个元素的Name为用户名
            var permissionRequirement = new PermissionRequirement(
                "/api/denied", permission,
                ClaimTypes.Role,
                audienceConfig["Issuer"],
                audienceConfig["Audience"],
                signingCredentials,
                expiration: TimeSpan.FromSeconds(10000)//设置Token过期时间
                );

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policy => policy.AddRequirements(permissionRequirement));
            }).
            AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
            {
                //不使用https
                o.RequireHttpsMetadata      = true;
                o.TokenValidationParameters = tokenValidationParameters;
            });
            //注入授权Handler
            services.AddSingleton <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);
            services.AddGrpc();
        }
Esempio n. 2
0
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static dynamic BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)
        {
            var now = DateTime.UtcNow;
            var jwt = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(permissionRequirement.Expiration),
                signingCredentials: permissionRequirement.SigningCredentials
                );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var response   = new
            {
                Status       = true,
                access_token = encodedJwt,
                expires_in   = permissionRequirement.Expiration.TotalMilliseconds,
                token_type   = "Bearer"
            };

            return(response);
        }
 public GoodsService(ILogger <GoodsService> logger, PermissionRequirement requirement)
 {
     _requirement = requirement;
     _logger      = logger;
 }