示例#1
0
 public ContainerOptions()
 {
     Database = new DatabaseSettings();
     Token    = new TokenSettings();
     Caching  = new CachingSettings();
     CORS     = new CorsSettings();
 }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCors();

            var tokenSettings = new TokenSettings();

            new ConfigureFromConfigurationOptions <TokenSettings>(Configuration.GetSection("TokenConfig")).Configure(tokenSettings);


            services.AddSingleton(tokenSettings);
            services.Configure <IISOptions>(options => {
                options.ForwardClientCertificate = false;
            });
            services.AddDbContext <ApiContext>(options => options.UseInMemoryDatabase("InMemoryDatabase"));

            services.AddTransient <IUserService, UserService>();
            services.AddTransient <ITokenService, TokenService>();
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(beare =>
            {
                beare.RequireHttpsMetadata      = false;
                beare.SaveToken                 = true;
                beare.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.Key)),
                    ValidateAudience         = false,
                    ValidateIssuer           = false
                };
            });
        }
        public ApiControllerAuthenticationBase(
            string resource,
            RoleManager <IdentityRole> roleManager,
            UserManager <TUser> userManager,
            SignInManager <TUser> signInManager,
            TokenSettings tokenSettings,
            IUrlHelper urlHelper,
            IEmailService emailSender,
            IMapper mapper,
            PasswordSettings passwordSettings,
            EmailTemplates emailTemplates,
            AppSettings appSettings,
            IAuthorizationService authorizationService)
            : base(resource, mapper, emailSender, urlHelper, appSettings, authorizationService)
        {
            _resetPasswordEmailTemplate = emailTemplates.ResetPassword;

            _roleManager   = roleManager;
            _userManager   = userManager;
            _signInManager = signInManager;

            _privateSymmetricKey               = tokenSettings.Key;
            _privateSigningKeyPath             = tokenSettings.PrivateKeyPath;
            _privateSigningCertificatePath     = tokenSettings.PrivateCertificatePath;
            _privateSigningCertificatePassword = tokenSettings.PrivateCertificatePasword;

            _localIssuer        = tokenSettings.LocalIssuer;
            _tokenExpiryMinutes = tokenSettings.ExpiryMinutes;
        }
示例#4
0
        public ApiClienteController(IMapper mapper, IOptions <AppSettings> appSettings, IOptions <TokenSettings> tokenSettings)
        {
            var configRequest = new MapperConfiguration(cfg =>
            {
                cfg.SourceMemberNamingConvention      = new LowerUnderscoreNamingConvention();
                cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();

                cfg.CreateMap <AlertaRequest, Alerta>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <PessoaRequest, Pessoa>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <ConsequenciaRequest, Consequencia>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <SequenciaRequest, Sequencia>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <VerdadeRequest, Verdade>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <OpcaoRequest, Opcao>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <TipoRequest, Tipo>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <VerdadeConsequenciaTipoRequest, VerdadeConsequenciaTipo>().IgnoreAllPropertiesWithAnInaccessibleSetter();
            });

            var configResponse = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <AlertaRequest, Alerta>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <PessoaRequest, Pessoa>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <ConsequenciaRequest, Consequencia>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <SequenciaRequest, Sequencia>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <VerdadeRequest, Verdade>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <OpcaoRequest, Opcao>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <TipoRequest, Tipo>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <VerdadeConsequenciaTipoRequest, VerdadeConsequenciaTipo>().IgnoreAllPropertiesWithAnInaccessibleSetter();
            });

            _mapperResponse = new Mapper(configResponse);
            _mapperRequest  = new Mapper(configRequest);
            _appSettings    = appSettings.Value;
            _tokenSettings  = tokenSettings.Value;
        }
示例#5
0
        public static IServiceCollection addJWT(this IServiceCollection services, IConfiguration configuration)
        {
            IConfigurationSection jwtSettingsSection = configuration.GetSection("TokenSettings");

            services.Configure <TokenSettings>(jwtSettingsSection);

            TokenSettings jwtSettings = jwtSettingsSection.Get <TokenSettings>();
            var           key         = Encoding.ASCII.GetBytes(jwtSettings.Secret);

            services
            .AddAuthentication(options => {
                //Toda vez que for autenticar alguem, utilizar JWT
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                //Toda vez que for validar o token, utilizar JWT
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options => {
                //Exige que se use https (para evitar o ataque man-in-the-middle)
                options.RequireHttpsMetadata      = true;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),

                    ValidateIssuer = true,
                    ValidIssuer    = jwtSettings.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtSettings.ValidUrl
                };
            });

            return(services);
        } //addJWT
示例#6
0
        public CryptoService(IConfiguration configuration)
        {
            _config = configuration;

            var globalSaltString       = configuration["CryptoService:GlobalSalt"];
            var tokenSecurityKeyString = configuration["CryptoService:TokenSecurityToken"];

            if (globalSaltString == String.Empty || tokenSecurityKeyString == String.Empty)
            {
                //TODO
            }

            _globalSaltBytes  = Encoding.UTF8.GetBytes(globalSaltString);
            _tokenSecurityKey = Encoding.UTF8.GetBytes(tokenSecurityKeyString);

            _tokenSettings = new TokenSettings();
            var tokenSettingsSection = configuration.GetSection("CryptoService").GetSection("TokenSettings");

            tokenSettingsSection.Bind(_tokenSettings);

            _validationParameters = new TokenValidationParameters()
            {
                ValidIssuer   = _tokenSettings.Issuer,
                ValidAudience = _tokenSettings.Audience
            };
        }
示例#7
0
        public ApiControllerAuthenticationBase(
            RoleManager <IdentityRole> roleManager,
            UserManager <TUser> userManager,
            SignInManager <TUser> signInManager,
            TokenSettings tokenSettings,
            LinkGenerator linkGenerator,
            IEmailService emailSender,
            IMapper mapper,
            PasswordSettings passwordSettings,
            EmailTemplates emailTemplates,
            AppSettings appSettings)
            : base(mapper, emailSender, linkGenerator, appSettings)
        {
            _resetPasswordEmailTemplate = emailTemplates.ResetPassword;

            _passwordResetCallbackUrl = passwordSettings.PasswordResetCallbackUrl;

            _roleManager   = roleManager;
            _userManager   = userManager;
            _signInManager = signInManager;

            _privateSymmetricKey               = tokenSettings.Key;
            _privateSigningKeyPath             = tokenSettings.PrivateKeyPath;
            _privateSigningCertificatePath     = tokenSettings.PrivateCertificatePath;
            _privateSigningCertificatePassword = tokenSettings.PrivateCertificatePasword;

            _localIssuer        = tokenSettings.LocalIssuer;
            _tokenExpiryMinutes = tokenSettings.ExpiryMinutes;
        }
示例#8
0
        public ApiControllerAuthenticationBase(
            ControllerServicesContext context,
            RoleManager <IdentityRole> roleManager,
            UserManager <TUser> userManager,
            SignInManager <TUser> signInManager,
            TokenSettings tokenSettings,
            PasswordSettings passwordSettings,
            EmailTemplates emailTemplates)
            : base(context)
        {
            _resetPasswordEmailTemplate = emailTemplates.ResetPassword;

            _passwordResetCallbackUrl = passwordSettings.PasswordResetCallbackUrl;

            _roleManager   = roleManager;
            _userManager   = userManager;
            _signInManager = signInManager;

            _privateSymmetricKey               = tokenSettings.Key;
            _privateSigningKeyPath             = tokenSettings.PrivateKeyPath;
            _privateSigningCertificatePath     = tokenSettings.PrivateCertificatePath;
            _privateSigningCertificatePassword = tokenSettings.PrivateCertificatePasword;

            _localIssuer        = tokenSettings.LocalIssuer;
            _audience           = tokenSettings.Audiences.Split(",").First().Trim();
            _tokenExpiryMinutes = tokenSettings.ExpiryMinutes;
        }
示例#9
0
 public TokenClaimsHandler(AppDbContext appDbContext, IHttpContextAccessor httpContextAccessor, IOptions <TokenSettings> options, IWebHostEnvironment env)
 {
     _appDbContext  = appDbContext;
     _httpContext   = httpContextAccessor.HttpContext;
     _tokenSettings = options.Value;
     _env           = env;
 }
示例#10
0
        /// <summary>
        /// Obtiene los parametros de validacion del token, los cuales deben coincidir con
        /// los de la api
        /// </summary>
        /// <param name="secretKey">Secret key que debe coincidir con la api</param>
        /// <returns>Devuelve TokenValidationParameters</returns>
        public static TokenValidationParameters GetTokenValidationParameters(TokenSettings tokenSettings)
        {
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenSettings.SecretKey));

            return(new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = tokenSettings.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudiences = tokenSettings.Audiences,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero,

                SaveSigninToken = true
            });
        }
示例#11
0
 public AuthController(SignInManager <IdentityUser> signInManager, UserManager <IdentityUser> userManager, IOptions <TokenSettings> appSettings, SigningConfigurations signingConfigurations)
 {
     _signInManager         = signInManager;
     _userManager           = userManager;
     _appSettings           = appSettings.Value;
     _signingConfigurations = signingConfigurations;
 }
示例#12
0
        public static string GenerateToken(User user, TokenSettings tokenSettings)
        {
            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();

            var key           = Encoding.ASCII.GetBytes(tokenSettings.Secret);
            var expiryMinutes = tokenSettings.ExpiryMinutes;

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("Id", user.Id.ToString()),
                    new Claim("Email", user.Email),
                    new Claim("Username", user.UserName),
                    new Claim(ClaimTypes.Role, user.Role)
                }),
                Expires            = DateTime.UtcNow.AddMinutes(expiryMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
示例#13
0
        /// <summary>
        /// Uses the configuration to get the token settings to congifure the jwt validation
        /// </summary>
        /// <param name="config"></param>
        private TokenValidationParameters _getTokenValidationParams(IConfigurationRoot config)
        {
            var tokenSettings = TokenSettings.parseFromConfig(config);

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = tokenSettings.SigningKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = tokenSettings.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = tokenSettings.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                //Authentication Roles
                RoleClaimType = "Permissions"
            };

            return(tokenValidationParameters);
        }
示例#14
0
 public AutenticacaoService(SignInManager <IdentityUser> signInManager,
                            UserManager <IdentityUser> userManager, IOptions <GBChallengeSettings> gbChallengeSettings)
 {
     _signInManager = signInManager;
     _userManager   = userManager;
     _tokenSettings = gbChallengeSettings.Value.TokenSettings;
 }
示例#15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // uncomment one of these for database migrations
            //services.AddDbContext<HybridCryptoAppContext>(options => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HybridCryptoDB;Integrated Security=True;"), ServiceLifetime.Transient);

            services.AddControllers();

            services.AddDbContext <HybridCryptoAppContext>(options =>
            {
                if (Configuration.GetValue <bool>("Database:UseInMemory", false))
                {
                    options.UseInMemoryDatabase(Guid.NewGuid().ToString());
                }
                else
                {
                    options.UseMySql(Configuration.GetValue <string>("Database:ConnectionString"));
                }
            }, ServiceLifetime.Singleton);

            services.AddIdentity <User, Role>(options =>
            {
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequiredLength         = 8;

                options.SignIn.RequireConfirmedEmail       = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddEntityFrameworkStores <HybridCryptoAppContext>()
            .AddDefaultTokenProviders();

            // injecteer voor TokenSettings altijd de sectie Token uit de configuratie
            services.Configure <TokenSettings>(Configuration.GetSection("Token"));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;     // string value: "Bearer"
            })
            .AddJwtBearer(options =>
            {
                var tokenSettings = new TokenSettings();
                Configuration.Bind("Token", tokenSettings);     // injection doesn't work yet, force manually
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = tokenSettings.Issuer,
                    ValidAudience    = tokenSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key))
                };
            });

            services.AddSingleton <IPasswordHasher <User>, SCryptPasswordHasher <User> >(s => new SCryptPasswordHasher <User>(SCryptBlockSize, SCryptIterationCount, SCryptThreadCount));

            // Repositories
            services.AddScoped <IEncryptedPacketRepository, EncryptedPacketRepository>();
            services.AddScoped <IUserContactRepository, UserContactRepository>();
            services.AddScoped <IUserRepository, UserRepository>();
        }
示例#16
0
 public AuthRepository(DataContext context, IMailService mailService, IOptions <TokenSettings> tokenSettings, IOptions <AppSettings> appSettings)
 {
     this.context       = context;
     this.mailService   = mailService;
     this.tokenSettings = tokenSettings.Value;
     this.appSettings   = appSettings.Value;
 }
示例#17
0
        public ApiClienteController(IMapper mapper, IOptions <AppSettings> appSettings, IOptions <TokenSettings> tokenSettings)
        {
            var configRequest = new MapperConfiguration(cfg =>
            {
                cfg.SourceMemberNamingConvention      = new LowerUnderscoreNamingConvention();
                cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();

                cfg.CreateMap <EnderecoRequest, Endereco>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <PessoaRequest, Pessoa>().IgnoreAllPropertiesWithAnInaccessibleSetter();
            });

            var configResponse = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Cidade, CidadeResponse>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <Estado, EstadoResponse>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <Endereco, EnderecoResponse>().IgnoreAllPropertiesWithAnInaccessibleSetter();
                cfg.CreateMap <Pessoa, PessoaResponse>().IgnoreAllPropertiesWithAnInaccessibleSetter();

                //cfg.CreateMap<Pessoa, PessoaResponse>()
                //.ForMember(dest => dest.foto_perfil_link, opts => opts.MapFrom(src => appSettings.Value.ApiPresenca + "/File/" + "/Perfil/" + src.FotoPerfil));
            });

            _mapperResponse = new Mapper(configResponse);
            _mapperRequest  = new Mapper(configRequest);
            _appSettings    = appSettings.Value;
            _tokenSettings  = tokenSettings.Value;
        }
        public static void HandleJWT(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException();
            }

            IConfigurationSection tokenSettingsSection = configuration.GetSection("TokenSettings");

            services.Configure <TokenSettings>(tokenSettingsSection);
            TokenSettings tokenSettings = tokenSettingsSection.Get <TokenSettings>();

            byte[] key = Encoding.ASCII.GetBytes(tokenSettings.PrivateKey);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
示例#19
0
        private static TokenSettings GetAuthTokenSettings(IConfiguration configuration)
        {
            var tokenSettings = new TokenSettings();

            configuration.Bind("AuthToken", tokenSettings);
            return(tokenSettings);
        }
示例#20
0
 public AuthController(IAuthRepository authRepo, IMailService mailService, IFacebookAuthRepository facebookAuth, IOptions <TokenSettings> tokenSettings)
 {
     this.authRepo      = authRepo;
     this.mailService   = mailService;
     this.facebookAuth  = facebookAuth;
     this.tokenSettings = tokenSettings.Value;
 }
示例#21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(); //voegt MVC services toe zo dat ge een web api kunt maken
            services.AddDbContext <ChatAppContext>(
                options =>
            {
                var connectionString = Configuration["ConnectionString"];
                options.UseSqlServer(connectionString);
            }, ServiceLifetime.Transient);
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });
            services.AddIdentity <User, Role>(options =>
            {
                options.Lockout.DefaultLockoutTimeSpan     = TimeSpan.FromMinutes(5); // aantal keren fout wachtwoord moet ge 5 min wachten
                options.Lockout.MaxFailedAccessAttempts    = 5;
                options.Password.RequiredLength            = 8;
                options.SignIn.RequireConfirmedEmail       = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
                options.User.RequireUniqueEmail            = true;
            })
            .AddEntityFrameworkStores <ChatAppContext>()
            .AddDefaultTokenProviders();
            services.Configure <TokenSettings>(Configuration.GetSection("Token"));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var tokenSettings = new TokenSettings();
                Configuration.Bind("Token", tokenSettings);
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = tokenSettings.Issuer,
                    ValidAudience    = tokenSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key))
                };
            })
            //Code for adding google in an later stadium

            /*.AddGoogle(options =>
             * {
             *  IConfigurationSection googleAuthNSection =
             *      Configuration.GetSection("Authentication:Google");
             *
             *  options.ClientId = googleAuthNSection["ClientId"];
             *  options.ClientSecret = googleAuthNSection["ClientSecret"];
             * });*/;
            services.AddScoped(typeof(SqlConversationData), typeof(SqlConversationData));
            services.AddScoped(typeof(SqlUserKeyData), typeof(SqlUserKeyData));
            services.AddScoped(typeof(MessageService), typeof(MessageService));
            services.AddScoped(typeof(FileService), typeof(FileService));
        }
示例#22
0
 public BaseTests()
 {
     _httpTest          = new HttpTest();
     _apiFilmesSettings = ConfigManager.ApiFilmesSettings;
     _signingSettings   = ConfigManager.SigningSettings;
     _tokenSettings     = ConfigManager.TokenSettings;
     _systemSettings    = ConfigManager.SystemSettings;
 }
 public LoginController(SignInManager <IdentityUser> signInManager, UserManager <IdentityUser> userManager,
                        IOptions <TokenSettings> tokenSettings, IEmailServices emailServices)
 {
     _signInManager = signInManager;
     _userManager   = userManager;
     _tokenSettings = tokenSettings.Value;
     _emailServices = emailServices;
 }
示例#24
0
 public AstNode Read(string s, TokenSettings settings = default)
 {
     if (!TryRead(s.Tokenize(settings).ToArray(), out var node, out var error))
     {
         throw new Exception(error.ToString());
     }
     return(node);
 }
示例#25
0
 public AuthService(UserManager <User> userManager,
                    IOptions <TokenSettings> tokenSettings,
                    IMapper mapper)
 {
     _userManager   = userManager;
     _tokenSettings = tokenSettings.Value;
     _mapper        = mapper;
 }
示例#26
0
 public TokenAuthenticationService(
     IUserManagementService userManagementService,
     IOptions <TokenSettings> tokenOptions
     )
 {
     _userManagementService = userManagementService;
     _tokenSettings         = tokenOptions.Value;
 }
示例#27
0
        public void ConfigureServices(IServiceCollection services)
        {
            // MVC
            services
            .AddMvc()
            .AddJsonOptions(c => c.SerializerSettings.NullValueHandling = NullValueHandling.Ignore)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Auth JWT
            var tokenSettings = new TokenSettings();

            new ConfigureFromConfigurationOptions <TokenSettings>(
                Configuration.GetSection("TokenSettings")).Configure(tokenSettings);
            services.AddSingleton(tokenSettings);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "Jwt";
                options.DefaultChallengeScheme    = "Jwt";
            }).AddJwtBearer("Jwt", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ValidAudience            = tokenSettings.Audience,
                    ValidIssuer      = tokenSettings.Issuer,
                    IssuerSigningKey =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key)),
                    ClockSkew = TimeSpan.FromMinutes(5)
                };
            });

            // Cors
            services.AddCors(o => o.AddPolicy("CorsHabilitado", builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            // Gzip
            services.Configure <GzipCompressionProviderOptions>(c => c.Level = System.IO.Compression.CompressionLevel.Fastest);
            services.AddResponseCompression(c => c.Providers.Add <GzipCompressionProvider>());

            // Injeções
            services.AddTransient <IPerguntaDAL, PerguntaDAL>();
            services.AddTransient <IPerguntaBLL, PerguntaBLL>();
            services.AddTransient <IRespostaDAL, RespostaDAL>();
            services.AddTransient <IRespostaBLL, RespostaBLL>();
            services.AddTransient <IUsuarioDAL, UsuarioDAL>();
            services.AddTransient <IUsuarioBLL, UsuarioBLL>();
            services.AddTransient <ITagDAL, TagDAL>();
            services.AddTransient <ITagBLL, TagBLL>();
        }
示例#28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(_allowedSpecificOrigins, builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });

            services.Configure <TokenSettings>(Configuration.GetSection("Token"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext <ChessContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("ChessConnection"));
            });

            services.AddIdentityCore <User>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequireUppercase       = true;
                options.Password.RequireNonAlphanumeric = false;

                options.SignIn.RequireConfirmedEmail       = false; //To be true later
                options.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddEntityFrameworkStores <ChessContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var tokenSettings = new TokenSettings();
                Configuration.Bind("Token", tokenSettings);

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = tokenSettings.Issuer,
                    ValidAudience    = tokenSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key)),
                };
            });

            //Adding Custom Services
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddSingleton <IChessService, ChessService>();
            services.AddScoped <IUserService, UserService>();

            //Adding Custom Repositories
            services.AddScoped <IRepository <User>, UserRepository>();
        }
示例#29
0
 public AuthController(CampContext context, ILogger <AuthController> logger, IOptions <TokenSettings> optionsAccessor, IPasswordHasher <CampUser> passwordHasher, SignInManager <CampUser> signInManager, UserManager <CampUser> userManager)
 {
     this.context        = context;
     this.logger         = logger;
     this.passwordHasher = passwordHasher;
     this.signInManager  = signInManager;
     tokenSettings       = optionsAccessor.Value;
     this.userManager    = userManager;
 }
示例#30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TokenHelper"/> class.
 /// Helps generating custom token, validating custom token and generate AADv1 user access token for given resource.
 /// </summary>
 /// <param name="oAuthClient">Instance of the Microsoft Bot Connector OAuthClient class.</param>
 /// <param name="optionsAccessor">A set of key/value application configuration properties jwt access token.</param>
 /// <param name="logger">Instance to send logs to the Application Insights service.</param>
 public TokenHelper(OAuthClient oAuthClient, IOptionsMonitor <TokenSettings> optionsAccessor, ILogger <TokenHelper> logger)
 {
     this.options        = optionsAccessor.CurrentValue;
     this.oAuthClient    = oAuthClient;
     this.appBaseUri     = this.options.AppBaseUri;
     this.securityKey    = this.options.SecurityKey;
     this.connectionName = this.options.ConnectionName;
     this.logger         = logger;
 }