Ejemplo n.º 1
0
        public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(model.UserName);

                if (user == null)
                {
                    return(Unauthorized());
                }

                if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) != PasswordVerificationResult.Success)
                {
                    return(Unauthorized());
                }

                var userClaims = await _userManager.GetClaimsAsync(user);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                    // Token ID. We need this to maintain a blacklist for Logout purpose.
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                }.Union(userClaims);

                var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SigningKey));
                var signingCredentials   = new SigningCredentials(symmetricSecurityKey, _jwtOptions.SigningAlgorithm);
                var rememberUser         = model.RememberMe == true;
                var validTo = rememberUser ? DateTime.Now.AddDays(_jwtOptions.RememberMeExpireInDays) : DateTime.Now.AddMinutes(_jwtOptions.ExpireInMinutes);

                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: _jwtOptions.Issuer,
                    audience: _jwtOptions.Audience,
                    claims: claims,
                    expires: validTo,
                    signingCredentials: signingCredentials
                    );

                var jwt = _jwtValidator.WriteToken(jwtSecurityToken);

                if (_jwtOptions.UseCookie)
                {
                    SetTokenInCookie(jwt);
                }

                // Returns token as JSON.
                return(Ok(new
                {
                    token = jwt,
                    expiration = validTo
                }));
            }
            catch (Exception ex)
            {
                Logger.Error($"error while creating token: {ex}");
                return(StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token"));
            }
        }
        public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            try
            {
                //var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

                var user = await _userManager.FindByNameAsync(model.UserName);

                /*if (user != null)
                 * {
                 *  var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
                 *  if (result.Succeeded)
                 *  {
                 *
                 *      var claims = new[]
                 *      {
                 * new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                 * new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                 * };
                 *
                 *      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                 *      var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                 *
                 *      var token = new JwtSecurityToken(_config["Tokens:Issuer"],
                 *        _config["Tokens:Issuer"],
                 *        claims,
                 *        expires: DateTime.Now.AddDays(30),
                 *        signingCredentials: creds);
                 *
                 *      return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
                 *  }
                 * }*/
                if (user == null)
                {
                    await _userManager.AccessFailedAsync(user);

                    return(Unauthorized());
                }

                if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) != PasswordVerificationResult.Success)
                {
                    await _userManager.AccessFailedAsync(user);

                    return(Unauthorized());
                }

                var userClaims = await _userManager.GetClaimsAsync(user);

                var validTo = model.RememberMe == true
                    ? new DateTimeOffset(DateTime.Now.AddDays(_jwtOptions.RememberMeExpireInDays)).ToUnixTimeSeconds().ToString()
                    : new DateTimeOffset(DateTime.Now.AddMinutes(_jwtOptions.ExpireInMinutes)).ToUnixTimeSeconds().ToString();


                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Iss, _jwtOptions.Issuer),
                    new Claim(JwtRegisteredClaimNames.Aud, _jwtOptions.Audience),
                    new Claim(JwtRegisteredClaimNames.Email, user.UserName),
                    new Claim(ClaimTypes.Name, user.UserName),

                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                    // Token ID. We need this to maintain a blacklist for Logout purpose.
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Exp, validTo),
                }.Union(userClaims);

                foreach (var c  in claims)
                {
                    Console.WriteLine(c.Issuer + "--" + c.Type + "--" + c.Value);
                }


                /*var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SigningKey));
                 * var creds = new SigningCredentials(key, _jwtOptions.SigningAlgorithm);
                 * var jwtSecurityToken = new JwtSecurityToken(
                 *  issuer: _jwtOptions.Issuer,
                 *  audience: _jwtOptions.Audience,
                 *  claims: claims,
                 *  expires: model.RememberMe == true
                 *      ? DateTime.Now.AddDays(_jwtOptions.RememberMeExpireInDays)
                 *      : DateTime.Now.AddMinutes(_jwtOptions.ExpireInMinutes),
                 *  signingCredentials: creds
                 * );*/

                var jwt = _jwtValidator.WriteToken(_jwtValidator.CreateToken(claims, _jwtOptions));

                if (_jwtOptions.UseCookie)
                {
                    SetTokenInCookie(jwt);
                }
                // Returns token as JSON.
                return(Ok(new
                {
                    token = jwt,
                    expiration = validTo
                }));
            }
            catch (Exception ex)
            {
                //Logger.Error($"error while creating token: {ex}");
                return(StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token: " + ex.Message));
            }
        }