public object Post( [FromBody] Usuario usuario, [FromServices] UsuarioDao usersDAO, [FromServices] ConfiguracoesAssinatura configuracoesAssinatura, [FromServices] ConfiguracoesToken configuracoesToken) { //var credenciaisValidas = false; var retorno = new { authenticated = false, message = "Falha ao autenticar" }; if (usuario == null || string.IsNullOrWhiteSpace(usuario.Id)) { return(retorno); } var userBase = usersDAO.BuscaId(usuario.Id); var credenciaisValidas = userBase?.Senha == usuario.Senha; if (!credenciaisValidas) { return(retorno); } var identity = new ClaimsIdentity( new GenericIdentity(usuario.Id, "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, usuario.Id) } ); var dataCriacao = DateTime.Now; var dataExpiracao = dataCriacao + TimeSpan.FromSeconds(configuracoesToken.Segundos); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor { Issuer = configuracoesToken.Emissor, Audience = configuracoesToken.Espectador, SigningCredentials = configuracoesAssinatura.Credenciais, 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, message = "OK" }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var dbCtx = new MeuConviteContexto(new DbContextOptionsBuilder().UseInMemoryDatabase("MeuConviteDb").Options); //services.AddDbContext<MeuConviteContext>(); services.AddScoped(provider => new UsuarioDao(dbCtx)); services.AddScoped(provider => new ContatoDao(dbCtx)); var configuracoesAssinatura = new ConfiguracoesAssinatura(); var configuracoesToken = new ConfiguracoesToken(); new ConfigureFromConfigurationOptions <ConfiguracoesToken>( Configuration.GetSection("ConfiguracoesToken") ).Configure(configuracoesToken); services.AddSingleton(configuracoesAssinatura); services.AddSingleton(configuracoesToken); services .AddAuthentication(authOptions => { authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = configuracoesAssinatura.Chave; paramsValidation.ValidAudience = configuracoesToken.Espectador; paramsValidation.ValidIssuer = configuracoesToken.Emissor; //Validar a assinatura do token recebido paramsValidation.ValidateIssuerSigningKey = true; //Verificar se o token 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; }); //Ativar o token para os recursos do projeto services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build()); }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddDbContext <ContextDb>(options => options.UseSqlServer(Configuration.GetSection("ConnectionDevelopment").Value)); services.AddIdentity <UsuarioAplicativo, IdentityRole>() .AddEntityFrameworkStores <ContextDb>() .AddDefaultTokenProviders(); var configuracoesAssinatura = new ConfiguracoesAssinatura(); services.AddSingleton(configuracoesAssinatura); var tokenConfigurations = new ConfiguracaoToken(); new ConfigureFromConfigurationOptions <ConfiguracaoToken>( Configuration.GetSection("ConfiguracaoToken")) .Configure(tokenConfigurations); services.AddSingleton(tokenConfigurations); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = configuracoesAssinatura.Key; paramsValidation.ValidAudience = tokenConfigurations.Audience; paramsValidation.ValidIssuer = tokenConfigurations.Issuer; paramsValidation.ValidateIssuerSigningKey = true; paramsValidation.ValidateLifetime = true; paramsValidation.ClockSkew = TimeSpan.Zero; }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "PalmSoft Swagger", Version = "v1", }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "Utilizar a autenticação para geração do token em Token/Get e adicionar a chave conforme exemplo Example: Bearer {chave gerada pelo endpoint token/get}", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() } }); var xmlFile = Path.ChangeExtension(typeof(Startup).Assembly.Location, ".xml"); c.IncludeXmlComments(xmlFile); }); services.AddMvc(); }
public object Post([FromBody] Usuario usuario, [FromServices] UserManager <UsuarioAplicativo> userManager, [FromServices] SignInManager <UsuarioAplicativo> signInManager, [FromServices] ConfiguracoesAssinatura signingConfigurations, [FromServices] ConfiguracaoToken tokenConfigurations) { bool credenciaisValidas = false; if (usuario != null && !String.IsNullOrWhiteSpace(usuario.Email)) { var userIdentity = userManager.FindByNameAsync(usuario.Email).Result; if (userIdentity != null) { var resultadoLogin = signInManager.CheckPasswordSignInAsync(userIdentity, usuario.Senha, false).Result; if (resultadoLogin.Succeeded) { credenciaisValidas = userManager.IsInRoleAsync(userIdentity, Funcoes.Role_Fotos).Result; } } } if (credenciaisValidas) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(usuario.Email, "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, usuario.Email) } ); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(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, message = "OK" }); } else { return(new { authenticated = false, message = "Falha ao autenticar" }); } }