Exemple #1
0
        public static void ConfigureAUTH(this IServiceCollection services, IConfiguration configuration)
        {
            JwtSettings jwtSettings = new JwtSettings();

            configuration.GetSection("JwtSettings").Bind(jwtSettings);

            services
            .AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(configuration =>
            {
                configuration.RequireHttpsMetadata      = false;
                configuration.SaveToken                 = true;
                configuration.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = jwtSettings.Issuer,   // site that makes the token
                    ValidateIssuer           = true,                 // TODO: change this to avoid forwarding attacks
                    ValidAudience            = jwtSettings.Audience, // site that consumes the token
                    ValidateAudience         = true,                 // TODO: change this to avoid forwarding attacks
                    IssuerSigningKey         = new SymmetricSecurityKey(TokenStoreSecurityService.GetSha256Hash(jwtSettings.Key)),
                    ValidateIssuerSigningKey = true,                 // verify signature to avoid tampering
                    ValidateLifetime         = true,                 // validate the expiration
                    ClockSkew = TimeSpan.Zero                        // tolerance for the expiration date
                };
                configuration.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        ITokenValidatorService tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService <ITokenValidatorService>();
                        return(tokenValidatorService.ValidateAsync(context));
                    },
                    OnMessageReceived = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    }
                };
            });
        }
Exemple #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <BearerTokensOptions>(options => Configuration.GetSection("BearerTokens").Bind(options));
            services.Configure <AppSettings>(options => Configuration.Bind(options));

            //Enable GZip Compression
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
            });
            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                // You Can use fastest compression
                options.Level = CompressionLevel.Optimal;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddOptions();
            //services.Configure<IHelperServices.Models.AppSettings>(options => Configuration.Bind(options));

            services.AddCors();
            // Using Cache with ServerState option
            services.AddDistributedMemoryCache();
            // Default IdleTimeout 20 Minutes
            services.AddSession();
            services.AddAutoMapper();

            services.AddSwaggerGen(action =>
            {
                action.EnableAnnotations();
                action.SwaggerGeneratorOptions = new Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions()
                {
                    OperationIdSelector = x => x.ActionDescriptor.AttributeRouteInfo.Template.Replace('{', '_').Replace('}', '_')
                };
                action.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info {
                    Title = "eCommerce WebApi", Version = "v1"
                });
            });

            services.AddEntityFrameworkSqlServer().AddDbContext <MainDbContext>(options =>
            {
                options.UseLazyLoadingProxies(true)
                .UseSqlServer(Configuration.GetConnectionString("MainConnectionString"), serverDbContextOptionsBuilder =>
                {
                    int minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                    serverDbContextOptionsBuilder.CommandTimeout(minutes);
                    serverDbContextOptionsBuilder.EnableRetryOnFailure();
                });
            });

            services.AddSingleton(typeof(DbContextOptionsBuilder <MainDbContext>), new DbContextOptionsBuilder <MainDbContext>().UseSqlServer(Configuration.GetConnectionString("MainConnectionString")));
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped(typeof(IStringLocalizer), typeof(DbStringLocalizer));

            services.AddHelperServices();
            services.AddBusinessServices();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            //services.AddAuthorization(options =>
            //{
            //    options.AddPolicy("HasPermissionPolicy", policy =>
            //        policy.Requirements.Add(new HasPermissionRequirment()));
            //    options.AddPolicy("AuthenticatedOnlyPolicy", policy =>
            //        policy.Requirements.Add(new AuthenticatedOnlyRequirment()));
            //});

            services.AddScoped <IAuthorizationHandler, AuthenticatedOnlyFilter>();
            //services.AddScoped<IAuthorizationHandler, AuthHandler>();

            services
            .AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = Configuration["BearerTokens:Issuer"],   // site that makes the token
                    ValidateIssuer           = false,                                  // TODO: change this to avoid forwarding attacks
                    ValidAudience            = Configuration["BearerTokens:Audience"], // site that consumes the token
                    ValidateAudience         = false,                                  // TODO: change this to avoid forwarding attacks
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["BearerTokens:Key"])),
                    ValidateIssuerSigningKey = true,                                   // verify signature to avoid tampering
                    ValidateLifetime         = true,                                   // validate the expiration
                    ClockSkew = TimeSpan.FromMinutes(5)                                // tolerance for the expiration date
                };
                cfg.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        ILogger logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        ITokenValidatorService tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService <ITokenValidatorService>();
                        return(tokenValidatorService.ValidateAsync(context));
                    },
                    OnChallenge = context =>
                    {
                        ILogger logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    },
                    //OnMessageReceived = context =>
                    //{
                    //    Microsoft.Extensions.Primitives.StringValues accessToken = context.Request.Query["access_token"];

                    //    // If the request is for our hub...
                    //    PathString path = context.HttpContext.Request.Path;
                    //    if (!string.IsNullOrEmpty(accessToken) &&
                    //        (path.StartsWithSegments("/SignalR")))
                    //    {
                    //        // Read the token out of the query string
                    //        context.Token = accessToken;
                    //    }
                    //    return Task.CompletedTask;
                    //}
                };
            });

            //services.AddAntiforgery(x => x.HeaderName = "X-XSRF-TOKEN");
            //services.AddMvc(options =>
            //    {
            //        options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            //    })

            services.AddMvc()
            .AddDataAnnotationsLocalization()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.ContractResolver           = new DefaultContractResolver();
            });

            //services.AddSignalR(options => options.EnableDetailedErrors = true);
            // To use Username instead of ConnectionId in Communication
            services.AddSingleton <IUserIdProvider, CustomUserIdProvider>();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot";
            });

            services.Configure <RequestLocalizationOptions>(options =>
            {
                CultureInfo[] supportedCultures = new[] { new CultureInfo("ar"), new CultureInfo("en") };
                options.DefaultRequestCulture   = new RequestCulture("ar");
                options.SupportedCultures       = supportedCultures;
                options.SupportedUICultures     = supportedCultures;
            });
        }
Exemple #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AppSettings>(options => Configuration.Bind(options));
            services.AddAutoMapper(typeof(Startup));

            services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
            });

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                // You Can use fastest compression
                options.Level = CompressionLevel.Optimal;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddOptions();
            services.AddCors();
            services.InjectDependancies();
            services.AddAutoMapperProfiles();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerGeneratorOptions = new Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions()
                {
                    OperationIdSelector = x => x.ActionDescriptor.AttributeRouteInfo.Template.Replace('{', '_').Replace('}', '_')
                };
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "WeAreReading", Version = "v1"
                });
            });

            services.AddEntityFrameworkSqlServer().AddDbContext <MainDbContext>(options =>
            {
                options.UseLazyLoadingProxies(true)
                .UseSqlServer(Configuration.GetConnectionString("MainConnectionString"), serverDbContextOptionsBuilder =>
                {
                    int minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                    serverDbContextOptionsBuilder.CommandTimeout(minutes);
                    serverDbContextOptionsBuilder.EnableRetryOnFailure();
                });
            });

            services.AddSingleton(typeof(DbContextOptionsBuilder <MainDbContext>), new DbContextOptionsBuilder <MainDbContext>().UseSqlServer(Configuration.GetConnectionString("MainConnectionString")));

            services
            .AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = Configuration["BearerTokensSettings:Issuer"],   // site that makes the token
                    ValidateIssuer           = true,                                           // TODO: change this to avoid forwarding attacks
                    ValidAudience            = Configuration["BearerTokensSettings:Audience"], // site that consumes the token
                    ValidateAudience         = false,                                          // TODO: change this to avoid forwarding attacks
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["BearerTokensSettings:Key"])),
                    ValidateIssuerSigningKey = true,                                           // verify signature to avoid tampering
                    ValidateLifetime         = false,                                          // validate the expiration
                    ClockSkew = TimeSpan.FromMinutes(5)                                        // tolerance for the expiration date
                };
                cfg.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        ILogger logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        ITokenValidatorService tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService <ITokenValidatorService>();
                        tokenValidatorService.Validate(context);
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        ILogger logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    },
                    //OnMessageReceived = context =>
                    //{
                    //    Microsoft.Extensions.Primitives.StringValues accessToken = context.Request.Query["access_token"];

                    //    // If the request is for our hub...
                    //    PathString path = context.HttpContext.Request.Path;
                    //    if (!string.IsNullOrEmpty(accessToken) &&
                    //        (path.StartsWithSegments("/SignalR")))
                    //    {
                    //        // Read the token out of the query string
                    //        context.Token = accessToken;
                    //    }
                    //    return Task.CompletedTask;
                    //}
                };
            });

            services.AddControllers().AddFluentValidation();
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Exemple #4
0
 public TokenFunctions(ITokenService tokenService, ITokenValidatorService tokenValidatorService)
 {
     _tokenService          = tokenService;
     _tokenValidatorService = tokenValidatorService;
 }