Esempio n. 1
0
        public async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            var token = ObterTokenFormatado(resposta.AccessToken);

            var claims = new List <Claim>
            {
                new Claim("JWT", resposta.AccessToken),
                new Claim("RefreshToken", resposta.RefreshToken)
            };

            claims.AddRange(token.Claims);

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddHours(8),
                IsPersistent = true
            };

            await _authenticationService.SignInAsync(
                _user.ObterHttpContext(),
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
Esempio n. 2
0
        private async Task <UsuarioRespostaLogin> GerarJwt(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var claims = await _userManager.GetClaimsAsync(user);

            var userRoles = await _userManager.GetRolesAsync(user);

            string encodedToken = EncodeToken(user, claims, userRoles);

            var response = new UsuarioRespostaLogin
            {
                AccessToken = encodedToken,
                ExpiresIn   = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UserToken   = new UsuarioToken
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(c => new UsuarioClaim {
                        Type = c.Type, Value = c.Value
                    })
                }
            };

            return(response);
        }
Esempio n. 3
0
        private async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            // Obtendo token formatado em JwtSecurityToken
            var token = ObterTokenFormatado(resposta.AccessToken);

            var claims = new List <Claim>();

            claims.Add(new Claim("JWT", resposta.AccessToken)); // Armazenando token na claim em "JWT"
            claims.AddRange(token.Claims);                      // Adicionando minha lista de claims que venho formatada em outra lsita

            // Gera claims dentro do Cookie, em formatado de cookies
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            // Propriedades do cookie
            var authProperties = new AuthenticationProperties()
            {
                ExpiresUtc   = DateTime.UtcNow.AddMinutes(60), // O Cookie expira depois de quantos minutos
                IsPersistent = true                            // Se é persistente
            };

            // Logando
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme, // Formato Cookie
                new ClaimsPrincipal(claimsIdentity),               // Claims usuario
                authProperties                                     // propriedades do cookie
                );
        }
        private async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            var token = ObterTokenFormatado(resposta.AccessToken);

            var claims = new List <Claim>
            {
                new Claim("JWT", resposta.AccessToken)
            };

            claims.AddRange(token.Claims);// adicionado uma lista

            //claimsIdentity:
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true
            };
            //pegar o cookie de autenticacao
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
Esempio n. 5
0
        private async Task RealizarLogin(UsuarioRespostaLogin usuarioRespostaLogin)
        {
            // Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.10

            var token = ObterTokenFormatado(usuarioRespostaLogin.AccessToken);

            var claims = new List <Claim>
            {
                new Claim("JWT", usuarioRespostaLogin.AccessToken)
            };

            claims.AddRange(token.Claims);

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
        private async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            var token = ObterTokenFormatado(resposta.AccessToken);

            var claims = new List <Claim>();

            claims.Add(new Claim(type: "JWT", value: resposta.AccessToken));
            claims.AddRange(token.Claims);

            // e necessario este novo objeto pq precisamos dos claims no schema correto para armazenamento em um cookie
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true // cookie vai ser mantido por varios requests, respeitando a expiracao acima
            };

            // SignInAsync e um metodo do proprio .NET Core (Microsoft.AspNetCore.Authentication) - nao esta associado ao Identity diretamente
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties
                );
        }
Esempio n. 7
0
        private async Task <UsuarioRespostaLogin> GerarJwt(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var claims = await _userManager.GetClaimsAsync(user);

            var userRoles = await _userManager.GetRolesAsync(user);

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim("role", userRole));
            }

            var identityClaims = new ClaimsIdentity();

            identityClaims.AddClaims(claims);

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var token        = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = _appSettings.Emissor,
                Audience           = _appSettings.ValidoEm,
                Subject            = identityClaims,
                Expires            = DateTime.UtcNow.AddHours(_appSettings.ExpiracaoHoras),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            });

            var encodedToken = tokenHandler.WriteToken(token);

            var refreshToken = await GerarRefreshToken(email);

            var response = new UsuarioRespostaLogin
            {
                AccessToken  = encodedToken,
                RefreshToken = refreshToken.Token,
                ExpiresIn    = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UsuarioToken = new UsuarioToken
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(c => new UsuarioClaim {
                        Type = c.Type, Value = c.Value
                    })
                }
            };

            return(response);
        }
Esempio n. 8
0
        private async Task RealizarLogin(UsuarioRespostaLogin respostaLogin)
        {
            var token  = ObterTokenFomatado(respostaLogin.AccessToken);
            var claims = new List <Claim>();

            claims.Add(new Claim("JWT", respostaLogin.AccessToken));
            claims.AddRange(token.Claims);

            var identityClain = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authPropertis = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true
            };
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identityClain), authPropertis);
        }
Esempio n. 9
0
        private UsuarioRespostaLogin ObterRespostaToken(string encodedToken, IdentityUser user, IEnumerable <Claim> claims)
        {
            var response = new UsuarioRespostaLogin
            {
                AccessToken  = encodedToken,
                ExpiresIn    = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UsuarioToken = new UsuarioToken
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(x => new UsuarioClaim {
                        Type = x.Type, Value = x.Value
                    })
                }
            };

            return(response);
        }
Esempio n. 10
0
        public async Task <IActionResult> Login(UsuarioLogin usuarioLogin)
        {
            if (!ModelState.IsValid)
            {
                return(View(usuarioLogin));
            }

            UsuarioRespostaLogin resposta = await _autenticacaoService.Login(usuarioLogin);

            if (ResponsePossuiErros(resposta.ResponseResult))
            {
                return(View(usuarioLogin));
            }

            await RealizarLogin(resposta);

            return(RedirectToAction("Index", "Home"));
        }
        private async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            var token  = ObterTokenFormatado(resposta.AccessToken);
            var claims = new List <Claim> {
                new Claim("JWT", resposta.AccessToken)
            };

            claims.AddRange(token.Claims);

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(resposta.ExpiresIn),
                IsPersistent = true //vai durar vários requests
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
Esempio n. 12
0
        private async Task RealizarLogin(UsuarioRespostaLogin respostaLogin)
        {
            JwtSecurityToken token = ObterTokenFormatado(respostaLogin.AccessToken);

            List <Claim> claims = new List <Claim>
            {
                new Claim("JWT", respostaLogin.AccessToken)
            };

            claims.AddRange(token.Claims);

            ClaimsIdentity claimsIdentity =
                new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            AuthenticationProperties authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true
            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity), authProperties);
        }
Esempio n. 13
0
        private async Task RealizarLogin(UsuarioRespostaLogin resposta)
        {
            var token = ObterTokenFormatado(resposta.AccessToken);

            var claims = new List <Claim>();

            claims.Add(new Claim("JWT", resposta.AccessToken));
            claims.AddRange(token.Claims);

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true
            };

            ///<summary>
            ///Configura que o HttpContext vai trabalhar no esquema de autenticação de usuários utilizando Cookies.
            ///</summary>
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity), authProperties);
        }
        private async Task <UsuarioRespostaLogin> GerarJwt2(string email)
        {
            /*Método GerarJwt acima refatorado*/
            //recuperando dados do user identity para colocar no token
            var user = await _userManager.FindByEmailAsync(email);

            var claims = await _userManager.GetClaimsAsync(user);

            var userRoles = await _userManager.GetRolesAsync(user);

            //add em uma lista de clamis
            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64));

            //add como claim cada um das roles
            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim("role", userRole));
            }

            //add dentro do IdentityClaims
            var identityClaims = new ClaimsIdentity();

            identityClaims.AddClaims(claims);

            //passando dados para o token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var token        = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = _appSettings.Emissor,
                Audience           = _appSettings.ValidoEm,
                Subject            = identityClaims, //dados do usuário fornecido acima
                Expires            = DateTime.UtcNow.AddHours(_appSettings.ExpiracaoHoras),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            });

            //gera token codificado com base na key
            var encodedToken = tokenHandler.WriteToken(token);

            //preparando o dados para o response
            var response = new UsuarioRespostaLogin
            {
                AccessToken  = encodedToken,
                ExpiresIn    = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UsuarioToken = new UsuarioToken
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(c => new UsuarioClaim {
                        Type = c.Type, Value = c.Value
                    })
                }
            };

            //response
            return(response);
        }
        private async Task <UsuarioRespostaLogin> GerarJwt(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var claims = await _userManager.GetClaimsAsync(user);

            var userRoles = await _userManager.GetRolesAsync(user);

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            // O Nbf é sobre quando o token vai expirar;
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString()));
            // O Iat é sobre quando o token foi emitido;
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64));

            foreach (var userRole in userRoles)
            {
                // Uma Role é um papel;
                // Uma Claim é um dado aberto, ele pode representar tanto uma permissão
                // quanto um dado do usuário; Só que como Claims e Roles são diferentes, mas
                // ao mesmo tempo você vê da mesma forma, eu estou adicionado as roles como claim,
                // apesar do Identity ver diferença, estamos tratanto tudo da mesma forma;
                claims.Add(new Claim("role", userRole));
            }

            // O ClaimsIdentity é o objeto real, da coleção de Claims que aquele usuário vai ter na representação dele;
            var identityClaims = new ClaimsIdentity();

            identityClaims.AddClaims(claims);

            // Esse JwtSecurityTokenHandler ele vai pegar com base na chave que temos, e gerar o nosso token;
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);

            var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = _appSettings.Emissor,
                Audience           = _appSettings.ValidoEm,
                Subject            = identityClaims,
                Expires            = DateTime.UtcNow.AddHours(_appSettings.ExpiracaoHoras),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            });

            var encodedToken = tokenHandler.WriteToken(token);

            var response = new UsuarioRespostaLogin
            {
                AccessToken  = encodedToken,
                ExpiresIn    = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UsuarioToken = new UsuarioToken
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(c => new UsuarioClaim {
                        Type = c.Type, Value = c.Value
                    })
                }
            };

            return(response);
        }