public async Task <IActionResult> Post([FromForm] AuthenticateUserCommand command) { if (command == null) { return(null); } var identity = await GetClaims(command); if (identity == null) { return(null); } var claims = new[] { new Claim(JwtRegisteredClaimNames.UniqueName, command.Username), new Claim(JwtRegisteredClaimNames.NameId, command.Username), new Claim(JwtRegisteredClaimNames.Email, command.Username), new Claim(JwtRegisteredClaimNames.Sub, command.Username), new Claim(JwtRegisteredClaimNames.Jti, await _tokenOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_tokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("NomeAplicacao") }; var jwt = new JwtSecurityToken( issuer: _tokenOptions.Issuer, audience: _tokenOptions.Audience, claims: claims.AsEnumerable(), notBefore: _tokenOptions.NotBefore, expires: _tokenOptions.Expiration, signingCredentials: _tokenOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { token = encodedJwt, expires = (int)_tokenOptions.ValidFor.TotalSeconds, user = new { id = _customer.Id, name = _customer.Name.ToString(), email = _customer.Email.Address, username = _customer.User.Username } }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
//Pode Implementar assim private Task <ClaimsIdentity> GetClaims(AuthenticateUserCommand command) { var customer = _repository.GetByUserName(command.Username); if (customer == null) { return(Task.FromResult <ClaimsIdentity>(null)); } if (!customer.User.Authenticate(command.Username, command.Password)) { return(Task.FromResult <ClaimsIdentity>(null)); } _customer = customer; return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(customer.User.Username, "Token"), new[] { //new Claim("TES", customer.User.Role.ToString()) new Claim("NomeAplicacao", "User"), //Mesmo valor que demos às Policies new Claim("NomeAplicacao", "Admin") //Mesmo valor que demos às Policies }))); }