コード例 #1
0
 public LoginService(ILoginRepository loginRepository,
                     SignInConfigurations signInConfigurations,
                     TokenConfigurations tokenConfigurations,
                     IConfiguration configuration)
 {
     _loginRepository      = loginRepository;
     _signInConfigurations = signInConfigurations;
     _tokenConfigurations  = tokenConfigurations;
     _configuration        = configuration;
 }
コード例 #2
0
ファイル: Startup.cs プロジェクト: joao2391/RESTApi
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            SignInConfigurations signInConfigurations = new SignInConfigurations();

            services.AddSingleton(signInConfigurations);

            TokenConfigurations tokenConfigurations = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                TokenValidationParameters paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey          = signInConfigurations.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 Swashbuckle.AspNetCore.Swagger.Info {
                    Title = "APIRest", Version = "v1"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
コード例 #3
0
        public object GerarToken([FromBody] object obj,
                                 [FromServices] SignInConfigurations signingConfigurations,
                                 [FromServices] TokenConfigurations tokenConfigurations)
        {
            if (!obj.IsObjectNull())
            {
                serializedObject = obj.SerializeObject();

                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(serializedObject, "Login"),
                    new [] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N"))
                }
                    );

                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"
                });
            }
        }
コード例 #4
0
ファイル: Startup.cs プロジェクト: war-man/CLERP
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            var currentAssembly = GetType().Assembly;

            // load custom settings
            var settingsSection = Configuration.GetSection(nameof(AppSettings));
            var settings        = settingsSection.Get <AppSettings>();

            var jwtSection = Configuration.GetSection(nameof(JwtOptions));
            var jwtOptions = jwtSection.Get <JwtOptions>();

            services.Configure <AppSettings>(settingsSection);
            services.Configure <JwtOptions>(jwtSection);

            services.AddDbContext <ClerpContext>(options => options.UseSqlServer(settings.ConnectionstringLocal));

            var signInConfigurations = new SignInConfigurations();

            services.AddSingleton(signInConfigurations);

            // register custom authorization policies and handler
            services.AddSingleton <IAuthorizationHandler, IpCheckHandler>();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("MatchingIpPolicy", policy => policy.Requirements.Add(new IpCheckRequirement()));
            });

            // configure jwt auth
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signInConfigurations.Key,
                    ClockSkew           = TimeSpan.Zero,
                    RequireSignedTokens = true
                };

                jwtBearerOptions.RequireHttpsMetadata = true;
            });

            services.AddMvc(options =>
            {
                options.Conventions.Add(new GroupByApiRootConvention());

                // add auth policy globally so every reqest has to be authenticated, unless the controller is decorated with the "AllowAnonymous" attribute
                var authPolicy = new AuthorizationPolicyBuilder()
                                 .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                 .RequireAuthenticatedUser()
                                 .Build();
                options.Filters.Add(new AuthorizeFilter(authPolicy));

                // apply MatchingIpPolicy globally for all controllers, only if the current ip and the ip registered in the token match access will be granted
                options.Filters.Add(new AuthorizeFilter("MatchingIpPolicy"));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            })
            .AddFluentValidation(config =>
            {
                config.RegisterValidatorsFromAssemblyContaining <Startup>();
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0); // v1
                options.ReportApiVersions = true;
            });

            services.AddCors();

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(settings.HSTSMaxAge);
            });

            services.AddHttpsRedirection(options =>
            {
                options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                options.HttpsPort          = 5001;
            });

            services.AddSwagger();

            // Register MediatR and custom behavior for pipeline
            services.AddMediatR(currentAssembly);
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(PerformanceProfilerPipelineBehaviour <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(DBContextTransactionPipelineBehavior <,>));

            // Add Automapper and scan assembly automatically for mapping profiles
            services.AddAutoMapper(currentAssembly);
            Mapper.Initialize(cfg => cfg.AddMaps(currentAssembly));

            services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); // Disable built in validation error response

            services.AddScoped <IPasswordHasher, PasswordHasher>();                                                  // Register hashing implentation for password hashing within the application
            services.AddScoped <IJwtTokenGenerator, JwtTokenGenerator>();
            services.AddSingleton <ICurrentUserAccessor, CurrentUserAccessor>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.RegisterInterface();
            services.AddAutoMapper(typeof(CoreProfile));
            ConfigureRepository.ConfigureDepedenciesRepository(services);

            services.AddControllers().AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            var singinConfigurations = new SignInConfigurations();

            services.AddSingleton(singinConfigurations);

            var tokenConfiguration = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfigurations")).Configure(tokenConfiguration);
            services.AddSingleton(tokenConfiguration);

            services.AddAuthentication(authOp =>
            {
                authOp.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOp.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOp =>
            {
                var paramsValidation = bearerOp.TokenValidationParameters;
                paramsValidation.IssuerSigningKey         = singinConfigurations.Key;
                paramsValidation.ValidAudience            = tokenConfiguration.Audience;
                paramsValidation.ValidIssuer              = tokenConfiguration.Isseur;
                paramsValidation.ValidateIssuerSigningKey = true;
                paramsValidation.ValidateLifetime         = true;
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            services.AddAuthorization(authOp =>
            {
                authOp.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                                 .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                                 .RequireAuthenticatedUser().Build());
            });


            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Teste Luby",
                    Description = "Projeto desenvolvido com arquitetura DDD.",
                    Contact     = new Microsoft.OpenApi.Models.OpenApiContact
                    {
                        Name  = "Ronaldo Bruno de Souza Santos",
                        Email = "*****@*****.**"
                    }
                });

                var xmlApiPath          = Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml");
                var xmlDataContractPath = Path.Combine(AppContext.BaseDirectory, $"{typeof(BaseReponse).Assembly.GetName().Name}.xml");

                s.IncludeXmlComments(xmlApiPath);
                s.IncludeXmlComments(xmlDataContractPath);

                s.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                {
                    Description = "Enter the token",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });

                s.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        }, new List <string>()
                    }
                });
            });
        }