示例#1
0
        public void TestCreateAccessToken()
        {
            string uid   = "zhangsan";
            var    token = jwtHelper.CreateAccessToken(uid);

            Console.WriteLine(token);
            Assert.Pass();
        }
示例#2
0
        public async Task <IDataResult <AccessToken> > GetAuthenticatedToken(User user)
        {
            var isUserInRole = await this.IsUserInRole(user, "Writer");

            var userRole = isUserInRole.ResultType == ResultType.Success ? "Writer" : "User";

            //var userRole = await (this.IsUserInRole(user, "Admin").Result.ResultType == ResultType.Success) ? "Admin" : "User";

            var tokenOptions          = _configuration.GetSection("JwtConfiguration").Get <TokenOptions>();
            var accessTokenExpiration = DateTime.Now.AddDays(tokenOptions.AccessTokenExpiration);

            IdentityOptions _options = new IdentityOptions();
            var             claims   = new[]
            {
                new Claim("userId", user.Id.ToString()),
                new Claim("email", user.Email),
                new Claim(ClaimTypes.Role, userRole),
                new Claim("user_role", userRole),

                new Claim("user_picture", user.Picture),
                new Claim("name", $"{user.Name} {user.Lastname}"),
                new Claim("user_birthday", user.BirthDay.ToString()),
                new Claim("user_created", user.Created.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTime.Now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
            };

            var securityKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(tokenOptions.SecurityKey));
            var securityToken = new JwtSecurityToken(
                issuer: tokenOptions.Issuer,
                audience: tokenOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: accessTokenExpiration,
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
                );

            var token = new JwtSecurityTokenHandler().WriteToken(securityToken);

            var accessToken = JwtHelper.CreateAccessToken(token, user, userRole, accessTokenExpiration);

            return(new SuccessDataResult <AccessToken>(accessToken));
        }
示例#3
0
        /// <summary>
        /// 认证id token
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public static async Task AuthIdToken(HttpContext ctx, System.Func <System.Threading.Tasks.Task> next)
        {
            try
            {
                var request  = ctx.Request;
                var response = ctx.Response;

                // 跳过注册登录请求
                if (Regex.IsMatch(request.Path.Value, "/auth-service/(register|auth).+"))
                {
                    await next.Invoke();

                    return;
                }

                // 获取请求来源
                var referer = request.Headers["Referer"].ToString();
                Console.WriteLine(string.Format("request path: {0}; from: {1}", request.Path.Value, referer));

                // 检查是否有 Authorization header
                if (request.Headers["Authorization"].Count == 0)
                {
                    response.ContentType = "application/json";
                    response.StatusCode  = 401;

                    var strResult = authFailed("no authorization header");

                    await response.WriteAsync(strResult);

                    return;
                }

                // 获取 Authorization header
                JwtHelper jwtHelper = new JwtHelper();
                var       token     = request.Headers["Authorization"][0];

                // 验证id token
                var jwtState = jwtHelper.ValidateIdToken(token);

                if (jwtState.Success) // id token jwt 验证成功
                {
                    // 生成access token 替换 authorization header
                    var accessToken = jwtHelper.CreateAccessToken(jwtState.Uid);

                    Console.WriteLine(string.Format("valid id token succes, sub: {0}, uid: {1}, generate access token: {2}",
                                                    jwtState.Subject, jwtState.Uid, accessToken));

                    request.Headers.Remove("Authorization");
                    request.Headers.Add("Authorization", accessToken);

                    await next.Invoke();
                }
                else  // id token jwt 验证失败
                {
                    Console.WriteLine(string.Format("valid id token failed, error: {0}", jwtState.ErrorMessage));

                    response.ContentType = "application/json";
                    response.StatusCode  = 401;

                    var strResult = authFailed(jwtState.ErrorMessage);

                    await response.WriteAsync(strResult);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                await next.Invoke();
            }
        }