public IActionResult Post([FromBody] VisaoModeloUsuario usuario, [FromServices] SegurancaJWT signingConfigurations, [FromServices] ConfiguracaoToken tokenConfigurations) { try { _autorizarUsuarioVisaoModelo.ValidarUsuarioAutorizado(usuario.Login, usuario.Senha); return(Ok(GetToken(usuario, signingConfigurations, tokenConfigurations))); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
protected object GetToken([FromBody] VisaoModeloUsuario usuario, [FromServices] SegurancaJWT signingConfigurations, [FromServices] ConfiguracaoToken tokenConfigurations) { try { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(usuario.Login, "login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, usuario.Login) } ); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromMinutes(tokenConfigurations.Seconds); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = dataCriacao, Expires = dataExpiracao }); var token = handler.WriteToken(securityToken); return(new { authenticated = true, created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token }); } catch (Exception ex) { throw ex; } }
public static void ConfigurarComponentesSeguranca(IServiceCollection service, IConfiguration configuration) { var seguranca = new SegurancaJWT(); service.AddSingleton(seguranca); RegistrarChavesAppSettings(service, configuration); var authAdded = service.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }); authAdded.AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = seguranca.Key; paramsValidation.ValidAudience = _configuracaoToken.Audience; paramsValidation.ValidIssuer = _configuracaoToken.Issuer; // Valida a assinatura de um token recebido paramsValidation.ValidateIssuerSigningKey = true; // Verifica se um token recebido ainda é válido paramsValidation.ValidateLifetime = true; // Tempo de tolerância para a expiração de um token (utilizado // caso haja problemas de sincronismo de horário entre diferentes // computadores envolvidos no processo de comunicação) paramsValidation.ClockSkew = TimeSpan.Zero; }); // Ativa o uso do token como forma de autorizar o acesso // a recursos deste projeto service.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); _service = service.BuildServiceProvider(); }