コード例 #1
0
        private async Task <object> GerarTokenUsuario(LoginViewModel login)
        {
            var user = await _userManager.FindByEmailAsync(login.Email);

            var userClaims = await _userManager.GetClaimsAsync(user);

            userClaims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, await _jwtTokenOptions.JtiGenerator()));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtTokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));

            var jwt = new JwtSecurityToken(
                issuer: _jwtTokenOptions.Issuer,
                audience: _jwtTokenOptions.Audience,
                claims: userClaims,
                notBefore: _jwtTokenOptions.NotBefore,
                expires: _jwtTokenOptions.Expiration,
                signingCredentials: _jwtTokenOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_jwtTokenOptions.ValidFor.TotalSeconds,
                user         = user
            };

            return(response);
        }
コード例 #2
0
        private async Task <object> GerarTokenUsuario(LoginViewModel login)
        {
            var user = await _userManager.FindByEmailAsync(login.Email);

            var userClaims = await _userManager.GetClaimsAsync(user);

            userClaims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));                                                                          // Defiição, no caso o User ID
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));                                                                     // Email do usuario
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, await _jwtTokenOptions.JtiGenerator()));                                            // Gerado através do JwtTokenOptions
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtTokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64)); // Iat -> IssuerAtToken -> Quando o Token foi gerado

            // Gerando de fato uma instância do Token
            var jwt = new JwtSecurityToken(
                issuer: _jwtTokenOptions.Issuer,
                audience: _jwtTokenOptions.Audience,
                claims: userClaims,
                notBefore: _jwtTokenOptions.NotBefore,
                expires: _jwtTokenOptions.Expiration,
                signingCredentials: _jwtTokenOptions.signingCredentials
                );

            // Codificando o Token para String
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new {
                access_token = encodedJwt,
                expires_in   = (int)_jwtTokenOptions.ValidFor.TotalSeconds,
                user         = user
            };

            return(Response);
        }
コード例 #3
0
        public async Task <IActionResult> Post([FromForm] AutenticarCommand command)
        {
            if (command == null)
            {
                return(BadRequest("Usuário ou Senha inválidos."));
            }

            var identity = await ObterClaims(command);

            if (identity == null)
            {
                return(BadRequest("Usuário ou Senha inválidos."));
            }

            var userClaims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, _usuario.Nome.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, _usuario.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, await _tokenOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, _tokenOptions.ToUnixEpochDate().ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst("JwtValidation")
            };

            var jwt = new JwtSecurityToken(
                issuer: _tokenOptions.Issuer,
                audience: _tokenOptions.Audience,
                claims: userClaims,
                notBefore: _tokenOptions.NotBefore,
                expires: _tokenOptions.Expiration,
                signingCredentials: _tokenOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                token   = encodedJwt,
                expires = _tokenOptions.Expiration,
                usuario = new
                {
                    id   = _usuario.Id,
                    nome = _usuario.Nome
                }
            };

            return(new OkObjectResult(
                       JsonConvert.SerializeObject(response)));
        }
コード例 #4
0
        private async Task <object> GenerateUserToken(LoginViewModel login)
        {
            var user = await _userManager.FindByNameAsync(login.UserName);

            var userClaims = await _userManager.GetClaimsAsync(user);

            userClaims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.NameId, user.Id));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.GivenName, user.NormalizedUserName));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, await _jwtTokenOptions.JtiGenerator()));
            userClaims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtTokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));

            var claimsUser = new List <Claim>(); //TODO: Implementar após refactory: CarregarPermissoes(_usuarioService.ObterPorAspNetUserId(user.Id));

            foreach (var claim in claimsUser)
            {
                userClaims.Add(claim);
            }

            var jwt = new JwtSecurityToken(
                issuer: _jwtTokenOptions.Issuer,
                audience: _jwtTokenOptions.Audience,
                claims: userClaims,
                notBefore: _jwtTokenOptions.NotBefore,
                expires: _jwtTokenOptions.Expiration,
                signingCredentials: _jwtTokenOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = DateTimeOffset.UtcNow.AddHours((_jwtTokenOptions.Expiration - DateTime.Now).TotalHours),//(int)_jwtTokenOptions.ValidFor.TotalSeconds,
                user         = new { Usuario = user.UserName, Email = user.Email, FirstPass = user.FirstPass }
            };

            return(response);
        }
コード例 #5
0
ファイル: JwtTokenController.cs プロジェクト: nuriu/ahval
        public async Task <IActionResult> Get([FromBody] User user)
        {
            var identity = await GetClaimsIdentity(user);

            if (identity == null)
            {
                logger.LogInformation($"Invalid username ({user.Username}) or password ({user.Password})");
                return(BadRequest("Invalid credentials"));
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Username),
                new Claim(JwtRegisteredClaimNames.Jti, await jwtTokenOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat,
                          ToUnixEpochDate(jwtTokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst("DisneyCharacter")
            };

            var jwt = new JwtSecurityToken(
                issuer: jwtTokenOptions.Issuer,
                audience: jwtTokenOptions.Audience,
                claims: claims,
                notBefore: jwtTokenOptions.NotBefore,
                expires: jwtTokenOptions.Expiration,
                signingCredentials: jwtTokenOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)jwtTokenOptions.ValidFor.TotalSeconds
            };

            var json = JsonConvert.SerializeObject(response, serializerSettings);

            return(new OkObjectResult(json));
        }
コード例 #6
0
        private async Task <object> GerarTokenUsuario(LoginViewModel login)
        {
            Usuario usuario = _usuarioRepository.BuscarPorEmailSenha(login.Email, login.Senha);

            var identity = await GetClaims(usuario);

            if (identity == null)
            {
                await _mediator.PublicarEvento(new DomainNotification("Identity", "Usuário não encontrado."));

                return(Response());
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, usuario.NomeRazaoSocial),
                new Claim(JwtRegisteredClaimNames.Email, usuario.Email),
                new Claim(JwtRegisteredClaimNames.Sub, usuario.Empresa != null ? usuario.EmpresaId.ToString() : usuario.ClienteId.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtTokenOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtTokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst("EventFinder")
            };



            var jwt = new JwtSecurityToken(
                issuer: _jwtTokenOptions.Issuer,
                audience: _jwtTokenOptions.Audience,
                claims: claims.AsEnumerable(),
                notBefore: _jwtTokenOptions.NotBefore,
                expires: _jwtTokenOptions.Expiration,
                signingCredentials: _jwtTokenOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            if (usuario.EmpresaId != null)
            {
                var empresa = _empresaRepository.BuscarPorEmail(login.Email);

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_jwtTokenOptions.ValidFor.TotalSeconds,
                    user         = new
                    {
                        id     = empresa.Id,
                        nome   = empresa.RazaoSocial,
                        email  = empresa.Email,
                        claims = claims.Select(x => new { x.Type, x.Value })
                    }
                };
                return(response);
            }
            else
            {
                var cliente = _clienteRepository.ObterPorId(usuario.ClienteId.Value);

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_jwtTokenOptions.ValidFor.TotalSeconds,
                    user         = new
                    {
                        id     = cliente.Id,
                        nome   = cliente.Nome,
                        email  = cliente.Email,
                        claims = claims.Select(x => new { x.Type, x.Value })
                    }
                };
                return(response);
            }
        }