public LoginService(IUsuarioRepositorio repositorio, Assinatura assinatura, TokenConfiguracao token, IConfiguration configuration) { _repositorio = repositorio; _assinatura = assinatura; _token = token; _configuration = configuration; }
public object Auntenticar( [FromBody] AutenticarUsuarioRequest request, [FromServices] SigningConfiguracao signingConfiguracao, [FromServices] TokenConfiguracao tokenConfiguracao) { bool credenciaisValidas = false; AutenticarUsuarioResponse response = _serviceUsuario.AutenticarUsuario(request); credenciaisValidas = response != null; if (credenciaisValidas) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(response.Id.ToString(), "Id"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), // captura a resposta "Id e nome" da api coloca em objecto e serializa em um Json para se ler depois de pegar o Token. new Claim("Usuario", JsonConvert.SerializeObject(response)) }); // Controle de data de expiracao do Tken DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(tokenConfiguracao.Seconds); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfiguracao.Issuer, Audience = tokenConfiguracao.Audience, SigningCredentials = signingConfiguracao.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", primeiroNome = response.PrimeiroNome }); } // Credenciais Invalidas else { return(new { authenticated = false, _serviceUsuario.Notifications }); } }
public ObjetoResposta GetDev([FromServices] ChaveConfiguracao chaveConfig, [FromServices] TokenConfiguracao tokenConfigurations) { var usuario = new Usuario() { Id = 3, Nome = "Gabriel 3", Email = "*****@*****.**", Grupo = "Desenvolvedor", Senha = "123" }; return(new Autenticacao().ConstroiJwt(usuario, chaveConfig, tokenConfigurations)); }
public ObjetoResposta GetRh([FromServices] ChaveConfiguracao chaveConfig, [FromServices] TokenConfiguracao tokenConfigurations) { var usuario = new Usuario() { Id = 2, Nome = "Gabriel 2", Email = "*****@*****.**", Grupo = "RH", Senha = "123" }; return(new Autenticacao().ConstroiJwt(usuario, chaveConfig, tokenConfigurations)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var chaveConfig = new ChaveConfiguracao(); services.AddSingleton(chaveConfig); var tokenConfig = new TokenConfiguracao(); new ConfigureFromConfigurationOptions <TokenConfiguracao>(Configuration.GetSection("TokenConfigurations")).Configure(tokenConfig); services.AddSingleton(tokenConfig); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = chaveConfig.Key; paramsValidation.ValidAudience = tokenConfig.Audience; paramsValidation.ValidIssuer = tokenConfig.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.AddMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var connectionString = _configuration["MySqlConnection:MySqlConnectionString"]; services.AddDbContext <JogosContexto>(options => options.UseMySql(connectionString)); var signingConfigurations = new SigningConfiguracao(); services.AddSingleton(signingConfigurations); var tokenConfiguracao = new TokenConfiguracao(); new ConfigureFromConfigurationOptions <TokenConfiguracao>( _configuration.GetSection("TokenConfiguracao") ) .Configure(tokenConfiguracao); services.AddSingleton(tokenConfiguracao); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfigurations.Key; paramsValidation.ValidAudience = tokenConfiguracao.Audience; paramsValidation.ValidIssuer = tokenConfiguracao.Issuer; // Validates the signing of a received token paramsValidation.ValidateIssuerSigningKey = true; // Checks if a received token is still valid paramsValidation.ValidateLifetime = true; // Tolerance time for the expiration of a token (used in case // of time synchronization problems between different // computers involved in the communication process) paramsValidation.ClockSkew = TimeSpan.Zero; }); // Enables the use of the token as a means of // authorizing access to this project's resources services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); services.AddMvc(options => { options.Filters.Add(typeof(ExceptionHandlerFilterAttribute)); options.RespectBrowserAcceptHeader = true; options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("text/xml")); options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json")); }) .AddXmlSerializerFormatters(); //Add Swagger Service services.AddSwaggerGen(s => { s.SwaggerDoc("v1", new OpenApiInfo { Title = "Gerenciar Jogos API", Version = "V1" }); s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below. \r\n\r\nExample: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); s.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); }); services.AddHealthChecks(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddAutoMapper(new Assembly[] { typeof(AutoMapperConfiguration).GetTypeInfo().Assembly }); #region Dependency Injection services.AddScoped <IJogoRepositorio, JogoRepositorio>(); services.AddScoped <IJogoServico, JogoServico>(); services.AddScoped <IAmigoRepositorio, AmigoRepositorio>(); services.AddScoped <IAmigoServico, AmigoServico>(); services.AddScoped <IEmprestimoRepositorio, EmprestimoRepositorio>(); services.AddScoped <IEmprestimoServico, EmprestimoServico>(); services.AddScoped <IUsuarioRepositorio, UsuarioRepositorio>(); services.AddScoped <IUsuarioServico, UsuarioServico>(); services.AddScoped(typeof(IRepositorioBase <>), typeof(RepositorioBase <>)); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureService.ConfigureDependenciaService(services); ConfigureRepositorio.ConfigureDependenciaRepositorio(services); var assinatura = new Assinatura(); services.AddSingleton(assinatura); IdentityModelEventSource.ShowPII = true; var token = new TokenConfiguracao(); new ConfigureFromConfigurationOptions <TokenConfiguracao>( Configuration.GetSection("TokenConfigurations")) .Configure(token); services.AddSingleton(token); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = assinatura.Key; paramsValidation.ValidAudience = token.Publico; paramsValidation.ValidIssuer = token.Emissor; paramsValidation.ValidateIssuerSigningKey = true; paramsValidation.ClockSkew = TimeSpan.Zero; }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); //Swaggwe services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Lar Espiritual Sagrado Coração de Maria", Description = "Documentação das API's REST do LESCM", Contact = new Contact { Name = "Marcos Almeida", Url = "https://www.linkedin.com/in/marcos-almeida-2827a61b/" } }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(opt => { opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); //versionamento para api services.AddApiVersioning(); //cache services.AddResponseCaching(); //Compressão de response services.AddResponseCompression(opt => { opt.Providers.Add <BrotliCompressionProvider>(); opt.EnableForHttps = true; }); }
public void ConfigureServices(IServiceCollection services) { // Adiciona a injecao de dependencia services.AddScoped <YouLearnContext, YouLearnContext>(); // Servicos para infra e suas transacoes services.AddTransient <IUnitOfWork, UnitOfWork>(); // conexao com os SERVICIOS services.AddTransient <IServiceUsuario, ServicosUsuarios>(); services.AddTransient <IServiceCanal, ServicoCanal>(); services.AddTransient <IServiceVideo, ServicoVideo>(); services.AddTransient <IServicePlayList, ServicoPlayList>(); // conexao com os REPOSITORIOS services.AddTransient <IRepositorioUsuario, RepositorioUsuario>(); services.AddTransient <IRepositorioCanal, RepositorioCanal>(); services.AddTransient <IRepositorioVideo, RepositorioVideo>(); services.AddTransient <IRepositorioPlayList, RepositorioPlayList>(); // Configuração do TOKEN var signingConfiguracao = new SigningConfiguracao(); services.AddSingleton(signingConfiguracao); var tokenConfiguracao = new TokenConfiguracao { Audience = AUDIENCE, Issuer = ISSUER, Seconds = int.Parse(TimeSpan.FromDays(2).TotalSeconds.ToString()) }; services.AddSingleton(tokenConfiguracao); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfiguracao.SigningCredentials.Key; paramsValidation.ValidAudience = tokenConfiguracao.Audience; paramsValidation.ValidIssuer = tokenConfiguracao.Issuer; // validacao da assinatura de um token recebido paramsValidation.ValidateIssuerSigningKey = true; // Verifica se o token recebido ainda é válido paramsValidation.ValidateLifetime = true; // Tempo de tolerancia para acabar o tempo do token ultilizado // caso tenha problemas de sicronia entre o tempo exercido atraves das maquinas no processo // de comunicação paramsValidation.ClockSkew = TimeSpan.Zero; }); //Ativa o uso do tokenConfiguracao como forma de autorizar o acesso // ativa os recursos deste Projeto services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); // Para todas as requisicoes serem necessaria o token , para um endpoint nao exigir o token deve colocar o [AllowAnonymous] // caso remova essa linha , para todas as requisiçoes que precisar de token,deve colocar o atributo [Authorize("Bearer")] services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddCors(); services.AddHttpContextAccessor(); // Aplicando documentacao com swagger services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Info { Title = "YouLearn", Version = "V1" }); }); }