コード例 #1
0
        /// <summary>
        /// ConfigureServices
        /// </summary>
        /// <param name="services"></param>
        // 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)
        {
            if (_env.IsDevelopment())
            {
                services.AddCors();
            }

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                options.Filters.Add(typeof(ApiExceptionFilter));
                options.Filters.Add(new AuthorizeFilter(policy));
                options.Filters.Add(new ProducesAttribute("application/json"));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                // todo options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Something API",
                    Description    = "API for Something application",
                    TermsOfService = "None",
                    Contact        = new Contact {
                        Name = "", Email = ""
                    },
                });
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);

                //Set the comments path for the swagger json and ui.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });



            // configure dependency injection
            services.AddScoped <ApiExceptionFilter>();

            // configure automapper and dependanc injection ** For Something.Infrastructure and Something.ApplicationCore
            var appSettings = Byui.Something.Infrastructure.Common.ConfigurationFacade.Configure(services, Configuration, _env.IsDevelopment(), _env.ContentRootFileProvider);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(o =>
            {
                if (_env.IsDevelopment())
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        RequireExpirationTime    = false,
                        RequireSignedTokens      = false,
                        ValidateAudience         = false,
                        ValidateIssuer           = false,
                        ValidateIssuerSigningKey = false,
                        ValidateLifetime         = false
                    };
                }
                else
                {
                    o.IncludeErrorDetails       = true;
                    o.MetadataAddress           = appSettings.MetadataAddress;
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience      = false,
                        RequireExpirationTime = true,
                        ValidateLifetime      = true,
                        ClockSkew             = TimeSpan.FromMinutes(5)
                    };
                }
                o.TokenValidationParameters.NameClaimType = Constants.Sub;
                o.TokenValidationParameters.RoleClaimType = Constants.Role;
            });

            // add authorization policies
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Constants.Admin, policy =>
                {
                    policy.RequireRole(Constants.Admins);
                });
                options.AddPolicy(Constants.Employee, policy =>
                {
                    policy.RequireRole(Constants.Employee);
                });
            });
        }
コード例 #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 <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                // Handling SameSite cookie according to https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1
                options.HandleSameSiteCookieCompatibility();
            });

            services.AddOptions();

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddSignIn("AzureAd", Configuration, options => Configuration.Bind("AzureAd", options));

            // Token acquisition service based on MSAL.NET
            // and chosen token cache implementation
            services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { Constants.ScopeUserRead })
            .AddInMemoryTokenCaches();

            /*
             * // or use a distributed Token Cache by adding
             *             .AddDistributedTokenCaches();
             *
             * // and then choose your implementation.
             * // See https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.2#distributed-memory-cache
             *
             * // For instance the distributed in memory cache
             *  services.AddDistributedMemoryCache()
             *
             * // Or a Redis cache
             * services.AddStackExchangeRedisCache(options =>
             *      {
             *          options.Configuration = "localhost";
             *          options.InstanceName = "SampleInstance";
             *      });
             *
             * // Or even a SQL Server token cache
             * services.AddDistributedSqlServerCache(options =>
             *  {
             *      options.ConnectionString =
             *          _config["DistCache_ConnectionString"];
             *      options.SchemaName = "dbo";
             *      options.TableName = "TestCache";
             *  });
             *
             * // Add Graph
             * services.AddGraphService(Configuration);
             */


            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();

            services.AddRazorPages();
        }
コード例 #3
0
ファイル: Startup.cs プロジェクト: AbedGhrayeb/Reactivities
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //add dbcontext
            services.AddDbContext <DataContext>(opt => {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
                opt.UseLazyLoadingProxies();
            });
            //Add Cors
            services.AddCors(options => {
                options.AddPolicy("CorsPolicy", policy => {
                    policy.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://localhost:3000");
                });
            });
            //add mediarR
            services.AddMediatR(typeof(List.Handler).Assembly);
            //add automapper config
            var mappingConfig = new MapperConfiguration(map =>
                                                        map.AddProfile(new MappingProfile()));

            services.AddSingleton(mappingConfig.CreateMapper());
            //services.AddAutoMapper(typeof(List.Handler));

            //add Ideintity
            var builder = services.AddDefaultIdentity <AppUser>(opt =>
            {
                opt.Password.RequiredLength         = 6;
                opt.Password.RequireLowercase       = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireNonAlphanumeric = false;
            });
            var IdentityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            IdentityBuilder.AddEntityFrameworkStores <DataContext>();
            IdentityBuilder.AddSignInManager <SignInManager <AppUser> >();

            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.AddScoped <IProfileReader, ProfileReader>();
            services.AddSignalR();
            //Token
            services.AddScoped <IJwtJenerator, JwtJenerator>();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("7592d6c3-fe20-488b-8761-1f5fe317a96c"));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access-token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!String.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddControllers(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
        }
 public static AuthorizationPolicyBuilder RequireCustomClaim(this AuthorizationPolicyBuilder builder, string claimType)
 {
     return(builder.AddRequirements(new CustomRequireClaim(claimType)));
 }
コード例 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Possible fix?
            //services.ConfigureNonBreakingSameSiteCookies();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority  = options.Authority + "/v2.0/";
                options.SaveTokens = true;
                options.TokenValidationParameters.ValidateIssuer = false;

                // Per the code below, this application signs in users in any Work and School
                // accounts and any Microsoft Personal Accounts.
                // If you want to direct Azure AD to restrict the users that can sign-in, change
                // the tenant value of the appsettings.json file in the following way:
                // - only Work and School accounts => 'organizations'
                // - only Microsoft Personal accounts => 'consumers'
                // - Work and School and Personal accounts => 'common'

                // If you want to restrict the users that can sign-in to only one tenant
                // set the tenant value in the appsettings.json file to the tenant ID of this
                // organization, and set ValidateIssuer below to true.

                // If you want to restrict the users that can sign-in to several organizations
                // Set the tenant value in the appsettings.json file to 'organizations', set
                // ValidateIssuer, above to 'true', and add the issuers you want to accept to the
                // options.TokenValidationParameters.ValidIssuers collection

                // possible fix?
                //options.NonceCookie.SameSite = SameSiteMode.None;
                //options.CorrelationCookie.SameSite = SameSiteMode.None;

                //options.Events = new OpenIdConnectEvents
                //{
                //    OnRemoteFailure = ctx =>
                //    {
                //        //ctx.Response.Redirect("/error?FailureMessage=" + System.Text.Encodings.Web.UrlEncoder.Default.Encode(ctx.Failure.Message));
                //        ctx.Response.Redirect("/Home/GetIDToken");
                //        ctx.HandleResponse();
                //        return System.Threading.Tasks.Task.FromResult(0);
                //    }
                //};
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
コード例 #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Add options
            services.AddOptions();
            services.Configure <AppOptions>(Configuration);

            // Add database Context
            services.AddDbContextPool <ApplicationDbContext>(options =>
            {
                options.UseNpgsql(Configuration.Get <AppOptions>().ConnectionStrings.PostgreSqlProvider);
                options.UseOpenIddict();
            });
            services.AddScoped(typeof(IRepository), typeof(EFRepository <ApplicationDbContext>));

            // Add identity
            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Add authorization policies
            services.AddAuthorization(options =>
            {
                // Create a policy for each permission
                Type type = typeof(PermissionClaims);
                foreach (var permissionClaim in type.GetFields())
                {
                    var permissionValue = permissionClaim.GetValue(null).ToString();
                    options.AddPolicy(permissionValue, policy => policy.Requirements.Add(new PermissionRequirement(permissionValue)));
                }
            });
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();

            // Add MVC Core
            services.AddMvcCore(
                options =>
            {
                // Add global authorization filter
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));

                // Add global exception handler for production
                options.Filters.Add(typeof(CustomExceptionFilterAttribute));

                // Add global validation filter
                options.Filters.Add(typeof(ValidateModelFilterAttribute));

                // Add global tenant filter
                options.Filters.Add(typeof(TenantFilterAttribute));
            }
                )
            .AddJsonFormatters()
            .AddAuthorization()
            .AddDataAnnotations()
            .AddCors()
            .AddApiExplorer();

            services.AddAutoMapper(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });

            // Configure Identity to use the same JWT claims as OpenIddict
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequiredLength         = 8;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.ClaimsIdentity.UserIdClaimType  = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType    = OpenIdConnectConstants.Claims.Role;
            });

            services.AddDistributedMemoryCache();

            // Add OpenId Connect/OAuth2
            var secretKey = Configuration.Get <AppOptions>().Jwt.SecretKey;

            services.AddOpenIddict(options =>
            {
                options.AddEntityFrameworkCoreStores <ApplicationDbContext>();
                options.AddMvcBinders();
                options.EnableAuthorizationEndpoint("/connect/authorize")
                //.EnableLogoutEndpoint("/connect/logout")
                .EnableTokenEndpoint("/connect/token");
                //.EnableUserinfoEndpoint("/api/userinfo");
                options.AllowAuthorizationCodeFlow()
                .AllowPasswordFlow()
                .AllowRefreshTokenFlow();
                // Make the "client_id" parameter mandatory when sending a token request.
                // options.RequireClientIdentification();
                options.EnableRequestCaching();
                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();
                options.UseJsonWebTokens();
                options.AddSigningKey(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)));
            });

            // Add authentication
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority                 = Configuration.Get <AppOptions>().Jwt.Authority;
                options.Audience                  = Configuration.Get <AppOptions>().Jwt.Audience;
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType            = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType            = OpenIdConnectConstants.Claims.Role,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
                    ValidateLifetime         = true
                };
            });

            // Add Swagger generator
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "My Web API", Version = "v1"
                });
            });

            // Add Email Service
            services.AddTransient <IEmailService, EmailService>();
        }
コード例 #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(config =>
            {
                config.EnableEndpointRouting = false;
                if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            });

            // Other ConfigureServices() code...

            services.AddSwaggerGen(c =>
            {
                c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "JAG LCRB PDF Service", Version = "v1"
                });
                c.ParameterFilter <AutoRestParameterFilter>();
                // This is only required because Swashbuckle does not present enums correctly
                c.AddEnumsWithValuesFixFilters();
                string baseUri = Configuration["BASE_URI"];
                if (baseUri != null)
                {
                    // ensure baseUri is in the right format.
                    baseUri = baseUri.TrimEnd('/') + @"/";
                    c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
                    {
                        Type  = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            Implicit = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri(baseUri + "api/authentication/redirect/" + Configuration["JWT_TOKEN_KEY"]),
                                Scopes           = new Dictionary <string, string>
                                {
                                    { "openid", "oidc standard" }
                                }
                            }
                        }
                    });
                }

                c.OperationFilter <AuthenticationRequirementsOperationFilter>();
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        //    RequireExpirationTime = false,
                        ValidIssuer      = Configuration["JWT_VALID_ISSUER"],
                        ValidAudience    = Configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            // health checks.
            services.AddHealthChecks();


            if (!string.IsNullOrEmpty(Configuration["WKHTMLTOPDF_LOCATION"]))
            {
                string wkhtmltopdfLocation = Configuration["WKHTMLTOPDF_LOCATION"];
                services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
            }
            else
            {
                services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
            }
        }
コード例 #8
0
        //private bool AuthorizationAccess(AuthorizationHandlerContext context)
        //{
        //	return context.User.IsInRole("Admin") &&
        //			context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
        //			context.User.IsInRole("Super Admin");
        //}

        // 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)
        {
            services.AddDbContextPool <AppDbContext>(
                options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength      = 10;
                options.Password.RequiredUniqueChars = 3;

                options.SignIn.RequireConfirmedEmail = true;

                options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";

                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <CustomConfirmationTokenProvider
                               <ApplicationUser> >("CustomEmailConfirmation");

            // Change token lifespan of all token types ..
            services.Configure <DataProtectionTokenProviderOptions>(o =>
                                                                    o.TokenLifespan = TimeSpan.FromHours(5));

            // Change token lifespan of just the Email Confirmation Token type ...
            services.Configure <CustomEmailConfirmationTokenProviderOptions>(o =>
                                                                             o.TokenLifespan = TimeSpan.FromDays(3));



            services.AddMvc(option =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                option.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlSerializerFormatters();

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "270071815073-md6rmlovrbmghj8vegqkd4p4ng27demc.apps.googleusercontent.com";
                options.ClientSecret = "ic1uxhgdQrCXmHb6Owv6exbQ";

                // To change the call back path
                //options.CallbackPath = "";
            })
            .AddFacebook(options =>
            {
                options.AppId     = "336154827398232";
                options.AppSecret = "b75c37e106ae8633851c7110b0c34643";
            });


            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Administration/AccessDenied");
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("DeleteRolePolicy",
                                  policy => policy.RequireClaim("Delete Role"));

                options.AddPolicy("EditRolePolicy",
                                  policy => policy.AddRequirements(new ManageAdminRolesAndClaimsRequirement()));

                options.AddPolicy("AdminRolePolicy",
                                  policy => policy.RequireRole("Admin"));
            });

            services.AddScoped <IEmployeeRepository, SQLEmployeeRepository>();

            services.AddSingleton <IAuthorizationHandler, CanEditOnlyAdminRolesAndClaimsHandler>();
            services.AddSingleton <IAuthorizationHandler, SuperAdminHandler>();
            services.AddSingleton <DataProtectionPurposeStrings>();
        }
コード例 #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            var appSettings = new AzureADOptions();

            Configuration.Bind("AzureAd", appSettings);

            var application = ConfidentialClientApplicationBuilder.Create(appSettings.ClientId)
                              .WithAuthority(appSettings.Instance + appSettings.TenantId + "/v2.0/")
                              .WithRedirectUri("https://localhost:5001" + appSettings.CallbackPath)
                              .WithClientSecret(appSettings.ClientSecret)
                              .Build();

            services.AddSingleton(application);

            services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                // configure authority to use v2 endpoint
                options.Authority = options.Authority + "/v2.0/";

                // asking Azure AD for id_token (to establish identity) and authorization code (to get access/refresh tokens for calling services)
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                // add the permission scopes you want the application to use
                options.Scope.Add("offline_access");
                Constants.ProductCatalogAPI.SCOPES.ForEach(s => options.Scope.Add(s));

                // validate the token issuer
                options.TokenValidationParameters.NameClaimType = "preferred_username";

                // wire up event to do second part of code authorization flow (exchanging authorization code for token)
                var handler = options.Events.OnAuthorizationCodeReceived;
                options.Events.OnAuthorizationCodeReceived = async context =>
                {
                    // handle the auth code returned post signin
                    context.HandleCodeRedemption();
                    if (!context.HttpContext.User.Claims.Any())
                    {
                        (context.HttpContext.User.Identity as ClaimsIdentity).AddClaims(context.Principal.Claims);
                    }

                    // get token
                    var token = await application.AcquireTokenByAuthorizationCode(options.Scope, context.ProtocolMessage.Code).ExecuteAsync();

                    context.HandleCodeRedemption(null, token.IdToken);
                    await handler(context).ConfigureAwait(false);
                };
            });


            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages();
        }
コード例 #10
0
 public static void Build(AuthorizationPolicyBuilder builder) =>
 builder.RequireClaim("groups", "773d56cf-4ede-494e-8823-1956116230f1");
コード例 #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(option => {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                option.Filters.Add(new AuthorizeFilter(policy));

                option.Filters.Add <AuthFilter>();
            }).AddRazorRuntimeCompilation();


            services.AddAuthorization(option =>
            {
                //UserManage必须满足以下三个条件
                option.AddPolicy("UserManage", policy => {
                    //需要该角色
                    policy.RequireRole("Admin", "Super");
                    //需要该声明,有声明即可
                    //policy.RequireClaim("EditUser");
                    //需要该声明,并且值必须正确
                    //policy.RequireClaim("EditUser", "EditUser");
                });

                option.AddPolicy("Custom", policy => {
                    policy.Requirements.Add(new Permission());
                });
            });

            object p = services.AddControllers()
                       //添加JSON序列化编码,防止中文被编码为Unicode字符。
                       .AddNewtonsoftJson(options => {
                //修改属性名称的序列化方式,首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

                //修改时间的序列化方式
                options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy/MM/dd HH:mm:ss"
                });
            });

            //数据库连接
            services.AddDbContext <SmsDBContext>(action => {
                action.UseSqlServer(Configuration.GetConnectionString("Default"));
            });

            //添加Identity
            services.AddIdentity <SmsUser, SmsRole>(option =>
            {
                option.SignIn.RequireConfirmedEmail       = true;
                option.SignIn.RequireConfirmedAccount     = true;
                option.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddEntityFrameworkStores <SmsDBContext>()
            .AddErrorDescriber <CustomIdentityError>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Admin/Account/AccessDenied");
                //options.Cookie.Name = "YourAppCookieName";
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan  = TimeSpan.FromMinutes(60);
                options.LoginPath       = "/Admin/Account/Login";
                //ReturnUrlParameter requires
                //using Microsoft.AspNetCore.Authentication.Cookies;
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration  = true;
            });


            //设置默认的Identity密码强度
            services.Configure <IdentityOptions>(options => {
                options.Password.RequiredUniqueChars    = 3;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireDigit           = false;
            });

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddTransient <IPolicyData, PolicyData>();

            services.AddTransient <ISmsSysMenuService, SmsSysMenuService>();

            services.AddTransient <ISmsSysMenuRepository, SmsSysMenuRepository>();

            services.AddTransient <IAuthorizationHandler, CustomAuthorize>();

            services.AddTransient <IUnitOfWork, UnitOfWork>();

            //services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
        }
コード例 #12
0
ファイル: Startup.cs プロジェクト: esilean/superhero-backend
        public void ConfigureServices(IServiceCollection services)
        {
            // CORS
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("WWW-Authenticate")
                    .WithOrigins(Configuration["ActivitiesApp"]).AllowCredentials();
                });
            });

            // Other configs
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(List.Handler).Assembly);
            services.AddSignalR();
            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg =>
            {
                cfg.RegisterValidatorsFromAssemblyContaining <Create>();
            });

            //Authorization
            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });
            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

            //Authentication
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
                //add token to hub context
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            //DI
            services.AddScoped <IProfileReader, ProfileReader>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();

            //Photos
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
コード例 #13
0
ファイル: Startup.cs プロジェクト: lastingyeh/DotNetCoreEmp
        public void ConfigureServices(IServiceCollection services)
        {
            // See secret path (*EmployeeManagement.csproj)
            //< UserSecretsId > d7506c45 - 5a03 - 4443 - a64b - 1c27d62e5607 </ UserSecretsId >

            // DB set
            services.AddDbContextPool <AppDbContext>(options =>
                                                     options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

            //Identity Set #2
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength      = 10;
                options.Password.RequiredUniqueChars = 3;

                //Add email confirm
                options.SignIn.RequireConfirmedEmail = true;

                //Add custom token provider options
                options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";

                //Account lockout 5 times/ 15 mins
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <CustomEmailConfirmationTokenProvider <ApplicationUser> >("CustomEmailConfirmation");

            services.Configure <DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(5));

            services.Configure <CustomEmailConfirmationTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromDays(3));

            services.AddMvc(
                config =>
            {
                //all controller actions which are not marked with [AllowAnonymous] will require the user
                // is authenticated with the default authentication scheme.
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlDataContractSerializerFormatters();

            services.AddAuthentication().AddGoogle(options =>
            {
                options.ClientId     = _config.GetValue <string>("GoogleAuth:ID");
                options.ClientSecret = _config.GetValue <string>("GoogleAuth:Secret");

                //issues modify by https://github.com/dotnet/aspnetcore/issues/6486
                options.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
                options.ClaimActions.Clear();
                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
                options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
                options.ClaimActions.MapJsonKey("urn:google:profile", "link");
                options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                // default callbackPath 'https://localhost:44382/signin-google'
                //options.CallbackPath = "";
            }).AddFacebook(options =>
            {
                options.ClientId     = _config.GetValue <string>("FacebookAuth:ID");
                options.ClientSecret = _config.GetValue <string>("FacebookAuth:Secret");
            });

            //Change AccessDeniedPath from Account/AccessDenied to Administration/AccessDenied
            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Administration/AccessDenied");
            });


            // Roles Policy
            services.AddAuthorization(options =>
            {
                //options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("Edit Role", "true"));
                // Policy match rules ["Admin" & "Edit Role", "Super Admin"]
                //options.AddPolicy("EditRolePolicy", policy => policy.RequireAssertion(context => AuthorizeAccess(context, "Edit Role")));
                options.AddPolicy("EditRolePolicy", policy =>
                                  policy.AddRequirements(new ManageAdminRolesAndClaimsRequirement()));

                //As applied 'DeleteRolePolicy' => require two Claims ['Delete Role', 'Create Role']
                //options.AddPolicy("DeleteRolePolicy",
                //    policy => policy.RequireClaim("Delete Role").RequireClaim("Create Role"));

                options.AddPolicy("DeleteRolePolicy",
                                  policy => policy.RequireAssertion(context => AuthorizeAccess(context, "Delete Role")));

                options.AddPolicy("AdminRolePolicy", policy => policy.RequireRole("Admin"));

                //As False, it's return on fail as return 'context.Fail()';
                //options.InvokeHandlersAfterFailure = false;
            });

            ;

            // services.AddSingleton<IEmployeeRepository, MockEmployeeRepository>();

            // kept the same instance of SQLEmployeeRepository during one request
            services.AddScoped <IEmployeeRepository, SQLEmployeeRepository>();

            // new instance each request
            // services.AddScoped<IEmployeeRepository, MockEmployeeRepository>();
            // new instance each render view
            // services.AddTransient<IEmployeeRepository, MockEmployeeRepository>();

            // Custom AuthorizationHandler
            services.AddSingleton <IAuthorizationHandler, CanEditOnlyOtherAdminRoleAndClaimHandler>();
            services.AddSingleton <IAuthorizationHandler, SuperAdminHandler>();
            services.AddSingleton <DataProtectionPurposeStrings>();
        }
コード例 #14
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "AB Project  API",
                    Version = "v1"
                });
            });

            IdentityBuilder builder = services.AddIdentityCore <User>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores <DataContext>();
            builder.AddRoleValidator <RoleValidator <Role> >();
            builder.AddRoleManager <RoleManager <Role> >();
            builder.AddSignInManager <SignInManager <User> >();
            // builder.AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    //

                    ValidIssuer   = Configuration.GetSection("AppSettings:Issuer").Value,
                    ValidAudience = Configuration.GetSection("AppSettings:Issuer").Value,

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppSettings:Key").Value)),
                };


                //Audience = "...",
                //Authority = "...",
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        // Add the access_token as a claim, as we may actually need it
                        var accessToken = context.SecurityToken as JwtSecurityToken;


                        //ClaimsPrincipal currentUser = _contextAccessor.HttpContext.User ;

                        //var jwt = "(the JTW here)";


                        var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
                        var token   = handler.ReadJwtToken(accessToken.RawData);

                        if (accessToken != null)
                        {
                            ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                            if (identity != null)
                            {
                                //identity.AddClaim(new Claim("access_token", accessToken.RawData));


                                foreach (var claim in token.Claims)
                                {
                                    if (!identity.HasClaim(claim.Type, claim.Value))
                                    {
                                        identity.AddClaim(claim);
                                    }
                                }
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };
            });



            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
                options.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator"));
                options.AddPolicy("VipOnly", policy => policy.RequireRole("VIP"));
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = X - Forwarded - Host | ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                // Only loopback proxies are allowed by default.
                // Clear that restriction because forwarders are enabled by explicit
                // configuration.
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });


            services.AddCors();
            services.AddAutoMapper(typeof(IRepositoryBase <>).Assembly);
            services.AddAutoMapper(typeof(IUserService).Assembly);


            services.AddHttpContextAccessor();
            //services.AddClaimsPrincipalFactory<CustomClaimsPrincipalFactory>();

            //services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomUserClaimsPrincipalFactory>();

            //services.AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();
            //services.AddAutoMapper(typeof(DatingRepository).Assembly);
            //services.AddTransient<Seed>();


            //Newly Added by Ibrahim Zakariyau

            services.AddScoped(typeof(IRepositoryBase <>), typeof(RepositoryBase <>));


            services.AddScoped <IAccessLevelService, AccessLevelService>();
            services.AddScoped <ICommodityService, CommodityService>();



            services.AddScoped <IFarmerVarificationStatusService, FarmerVarificationStatusService>();
            services.AddScoped <IFarmOwnershipTypeService, FarmOwnershipTypeService>();


            services.AddScoped <IGenderService, GenderService>();
            services.AddScoped <IIDTypeService, IDTypeService>();

            services.AddScoped <ILgaService, LgaService>();

            services.AddScoped <IMaritalStatusService, MaritalStatusService>();
            services.AddScoped <INationalityService, NationalityService>();


            services.AddScoped <IStateService, StateService>();
            services.AddScoped <IUserService, UserService>();


            services.AddScoped <IFarmerService, FarmerService>();


            services.AddScoped <IEOPService, EOPService>();
            services.AddScoped <IEOPTypeService, EOPTypeService>();
            services.AddScoped <IEOPUnitService, EOPUnitService>();

            services.AddScoped <IInventoryService, InventoryService>();



            //TO be remove

            services.AddScoped <LogUserActivity>();
        }
コード例 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            services.AddMvc()
            .AddJsonOptions(o =>
            {
                o.JsonSerializerOptions.PropertyNamingPolicy = null;
                o.JsonSerializerOptions.DictionaryKeyPolicy  = null;
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Core API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                });
            });
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddAuthentication(x =>
            //{
            //    x.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //    x.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //})
            //.AddJwtBearer(x =>
            //{
            //    //x.Audience = "http://localhost:34023/";
            //    //x.Authority = "http://localhost:2738/";
            //    x.RequireHttpsMetadata = false;
            //    x.SaveToken = true;
            //    x.TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidateIssuerSigningKey = true,
            //        IssuerSigningKey = new SymmetricSecurityKey(key),
            //        ValidateIssuer = true,
            //        ValidateAudience = true,

            //    };
            //})
            // .AddCookie();

            services.AddAuthentication("OAuth")
            .AddJwtBearer("OAuth", config =>
            {
                var secretBytes = Encoding.UTF8.GetBytes(appSettings.Secret);
                var key         = new SymmetricSecurityKey(secretBytes);

                config.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        if (context.Request.Query.ContainsKey("access_token"))
                        {
                            context.Token = context.Request.Query["access_token"];
                            context.Request.Headers.Add("Authorization", "Bearer " + context.Token);
                        }

                        return(Task.CompletedTask);
                    }
                };

                config.TokenValidationParameters = new TokenValidationParameters()
                {
                    ClockSkew        = TimeSpan.Zero,
                    ValidIssuer      = appSettings.Issuer,
                    ValidAudience    = appSettings.Audiance,
                    IssuerSigningKey = key,
                };
            });

            services.AddAuthorization(config =>
            {
                var defaultAuthBuilder = new AuthorizationPolicyBuilder();
                var defaultAuthPolicy  = defaultAuthBuilder
                                         .AddRequirements(new JwtRequirement())
                                         .Build();

                config.DefaultPolicy = defaultAuthPolicy;
            });
            services.AddScoped <IAuthorizationHandler, JwtRequirementHandler>();
            services.AddHttpClient()
            .AddHttpContextAccessor();

            services.AddControllers();



            services.AddTransient <IUsersRepository, UsersRepository>();
            services.AddTransient <IUsersService, UsersService>();
            services.AddTransient <IMenuRepository, MenuRepository>();
            services.AddTransient <IMenuService, MenuService>();

            services.AddTransient <IGroupRepository, GroupRepository>();
            services.AddTransient <IGroupServices, GroupServices>();
            services.AddTransient <IGroupMemberRepository, GroupMemberRepository>();
            services.AddTransient <IGroupMemberServices, GroupMemberServices>();

            services.AddTransient <IOrderNotificationService, OrderNotificationService>();
            services.AddTransient <IUserNotificationService, UserNotificationService>();
            services.AddTransient <IEmailContentRepository, EmailContentRepository>();
            services.AddTransient <IEmailRepository, EmailRepository>();
            services.AddTransient <IMessageRepository, MessageRepository>();
            services.AddTransient <ISmsRepository, SmsRepository>();



            services.AddTransient <ICommonConnection, CommonConnection>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();



            services.AddTransient <DbContext, BinderDBContext>();
            services.AddDbContext <BinderDBContext>(optionsBuilder =>
            {
                optionsBuilder.UseSqlServer(Configuration["ConnectionStrings:SqlConnectionString"]);
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  );

                //.WithOrigins("http://localhost:34023")
            });

            services.AddAutoMapper(typeof(Startup));
        }
コード例 #16
0
 public static void VerifyEveryone(AuthorizationPolicyBuilder PolicyBuilder) => PolicyBuilder.RequireAssertion(Context => true);
コード例 #17
0
        public static void ConfigureAuthentication(this IServiceCollection services)
        {
            //Configuração do Token
            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfigurations
            {
                Audience = AUDIENCE,
                Issuer   = ISSUER,
                Seconds  = int.Parse(TimeSpan.FromDays(1).TotalSeconds.ToString())
            };

            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.SigningCredentials.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                // Valida a assinatura de um token recebido
                paramsValidation.ValidateIssuerSigningKey = true;

                // Verifica se um token recebido 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;
            });

            // Ativa o uso do token como forma de autorizar o acesso
            // a recursos deste projeto
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            //Para todas as requisições serem necessaria o token, para um endpoint não exisgir o token
            //deve colocar o [AllowAnonymous]
            //Caso remova essa linha, para todas as requisições 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));
            });

            //Para todas as requisições serem necessaria o token, para um endpoint não exisgir o token
            //deve colocar o [AllowAnonymous]
            //Caso remova essa linha, para todas as requisições 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();
        }
コード例 #18
0
        // 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)
        {
            //The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.
            //With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.
            services.AddDbContextPool <AppDbContext>(
                options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

            //IdentityUser class is provided by ASP.NET core and contains properties for UserName, PasswordHash, Email etc.
            //This is the class that is used by default by the ASP.NET Core Identity framework to manage registered users of your application
            //we replace IdentitiyUser class with extended ApplicationUser class, which contains more properties.
            services.AddIdentity <ApplicationUser, IdentityRole>(
                options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                //require user's e-mail confirmed to be able to sign in.
                options.SignIn.RequireConfirmedEmail          = true;
                options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";
                //allow user to try a number of times before lock out and wait for a certain amount of time
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
            }
                ).AddEntityFrameworkStores <AppDbContext>() //adds an implementation of entity framework for identity information store.
            .AddDefaultTokenProviders()                     //to generate token for user e-mail confirmation.
            .AddTokenProvider <CustomEmailConfirmationTokenProvider <ApplicationUser> >("CustomEmailConfirmation");


            // Set token life span to 5 hours
            // However all kinds of tokens e.g. password reset token and e-mail confirmation token will have the same life span.
            // to have different life span we need to have customized DataProtectionTokenProvider class (will be discussed later)
            services.Configure <DataProtectionTokenProviderOptions>(o =>
                                                                    o.TokenLifespan = TimeSpan.FromHours(1));

            // Changes token lifespan of just the Email Confirmation Token type
            services.Configure <CustomEmailConfirmationTokenProviderOptions>(o =>
                                                                             o.TokenLifespan = TimeSpan.FromDays(3));

            //configure password options:
            //services.Configure<IdentityOptions>(options =>
            //{
            //    options.Password.RequireDigit = false;
            //    options.Password.RequireUppercase = false;
            //    options.Password.RequireNonAlphanumeric = false;
            //});

            // to use claim based authorization - create policy:
            services.AddAuthorization(options =>
            {
                options.AddPolicy("DeleteRolePolicy",
                                  policy => policy.RequireClaim("Delete Role"));

                //claim type is case-insensitive, however claim value is case-sensitive.
                //options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("Edit Role","true"));

                //use function to create policy: either in (Admin role and has Edit Role claim) or is SuperAdmin role.

                //options.AddPolicy("EditRolePolicy", policy => policy.RequireAssertion(context =>
                //    context.User.IsInRole("Admin") &&
                //    context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
                //    context.User.IsInRole("Super Admin")
                //));

                //instead of using function, we use customized authorization requirement:

                options.AddPolicy("EditRolePolicy", policy =>
                                  policy.AddRequirements(new ManageAdminRolesAndClaimsRequirement()));


                options.AddPolicy("AdminRolePolicy", policy => policy.RequireRole("Admin"));
            });

            //to change the default route of Access denied page:
            //services.ConfigureApplicationCookie(options =>
            //{
            //    options.AccessDeniedPath = new PathString("/Administration/AccessDenied");
            //});


            //services.AddMvc();  //add MVC to .NET CORE application step 1
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;  //need to disable EndpointRouting since we used UseMvcWithDefaultRoute

                //to apply [Authorize] globally throughout the application:
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                //revoke the old credentials and save the new credential in environment variables
                options.ClientId     = _config["Google:ClientID"];
                options.ClientSecret = _config["Google:ClientSecret"];
            }).AddFacebook(options =>
            {
                //revoke the old credentials and save the new credential in environment variables
                options.ClientId     = _config["Facebook:AppID"];
                options.ClientSecret = _config["Facebook:AppSecret"];
            });

            //.AddXmlSerializerFormatters();    //???? what's the usage of AddXmlSerializerFormatters

            //???Difference between AddMvcCore and AddMvc
            //InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered
            //services.AddMvcCore(options =>
            //{
            //    options.EnableEndpointRouting = false;
            //});


            // Unable to resolve service for type 'HelloCoreApp.Models.IEmployeeRepository
            // a Singleton service is created only one time per application and that single instance is used throughout the application life time.
            //services.AddSingleton<IEmployeeRepository, MockEmployeeRepository>();
            services.AddScoped <IEmployeeRepository, SQLEmployeeRepository>();
            //custom authorization requirement:
            //check: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1
            services.AddSingleton <IAuthorizationHandler, CanEditOnlyOtherAdminRolesAndClaimsHandler>();
            // Register the second handler. either handler fulfill the requirement then the user can pass the check.
            services.AddSingleton <IAuthorizationHandler, SuperAdminHandler>();

            services.AddSingleton <DataProtectionPurposeStrings>();
        }
コード例 #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddNewtonsoftJson();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ComfecoBackend", Version = "v1"
                });
            });
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ComfecoProjectDb")));
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["auth:key"])),
                    ClockSkew       = TimeSpan.Zero,
                    SaveSigninToken = true
                };
                options.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = (msg) =>
                    {
                        if (msg.Token == null)
                        {
                            bool hasToken = msg.HttpContext.Request.Query.ContainsKey("token");
                            if (hasToken)
                            {
                                msg.Token = msg.HttpContext.Request.Query["token"];
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };
            }).AddFacebook(config => {
                config.AppId     = Configuration["facebookauth:appid"];
                config.AppSecret = Configuration["facebookauth:appsecret"];
            }).AddGoogle(config =>
            {
                config.ClientId     = Configuration["googleauth:clientid"];
                config.ClientSecret = Configuration["googleauth:clientsecret"];
            }).AddCookie(ApplicationConstants.PersistLoginSchemeName, options =>
            {
                options.Cookie.Name      = ApplicationConstants.PersistLoginCookieName;
                options.LoginPath        = "/api/account/redirecttologin";
                options.AccessDeniedPath = "/api/account/redirecttologin";
                options.Cookie.SameSite  = SameSiteMode.None;
            });

            services.AddAuthorization(options =>
            {
                var adminPolicyBuilder = new AuthorizationPolicyBuilder()
                                         .RequireAuthenticatedUser().RequireRole(ApplicationConstants.Roles.AdminRoleName);

                options.AddPolicy(ApplicationConstants.Roles.AdminRoleName, adminPolicyBuilder.Build());
            });
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail   = false;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
                options.User.RequireUniqueEmail        = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <AuthCodeTokenProvider <ApplicationUser> >(ApplicationConstants.AuthCodeTokenProviderName);

            services.Configure <DataProtectionTokenProviderOptions>(options =>
            {
                options.TokenLifespan = TimeSpan.FromHours(1);
            });
            services.Configure <AuthCodeTokenProviderOptions>(options =>
            {
                options.TokenLifespan = TimeSpan.FromMinutes(5);
            });

            services.Configure <MailSettings>(Configuration.GetSection("MailSettings"));
            services.AddCors(
                options =>
            {
                options.AddPolicy(ApplicationConstants.DevelopmentPolicyName,
                                  new CorsPolicyBuilder()
                                  .WithOrigins("http://localhost:4200", "https://localhost:4200",
                                               "http://team45.comfeco.cristiangerani.com", "https://team45.comfeco.cristiangerani.com")
                                  .WithExposedHeaders(ApplicationConstants.CountOfRecordsHeaderName)
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials()
                                  .Build());



                options.DefaultPolicyName = ApplicationConstants.DevelopmentPolicyName;
            });

            services.AddSingleton(Channel.CreateUnbounded <MailRequest>());
            services.AddSingleton <IEmailService, EmailService>();
            services.AddTransient <ThreadSafeRandom>();
            services.AddAutoMapper(typeof(Startup));

            services.AddSingleton <IFileStorage, FileStorageInLocal>();
        }
コード例 #20
0
ファイル: Startup.cs プロジェクト: jakubasiak/Reactivities
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(opt =>
            {
                opt.UseLazyLoadingProxies();
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://localhost:3000");
                });
            });
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddAutoMapper(typeof(List.Handler));
            services.AddControllers(opt => {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining <Create>());

            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();

            services.AddAuthorization(opt => {
                opt.AddPolicy("IsActivityHost", policy => {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });
            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandeler>();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt => {
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false
                };
            });
            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "Reactivities", Version = "v1"
                });
            });
        }
コード例 #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Database Connection Parameters
            String connectionString = buildConnectionString();

            // WRITE CONNECTION STRING TO THE CONSOLE
            Console.WriteLine("********************************************************************************");
            Console.WriteLine("[Startup] Connection String: " + connectionString);
            Console.WriteLine("********************************************************************************");

            // NOW THAT WE HAVE OUR CONNECTION STRING, WE CAN ESTABLISH OUR DB CONTEXT
            services.AddDbContext <ApplicationDbContext>
            (
                options => options.UseNpgsql(connectionString)
            );

            services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddPasswordValidator <UsernameAsPasswordValidator <ApplicationUser> >();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequiredLength         = 12;
                options.Password.RequireDigit           = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequiredUniqueChars    = 6;

                // Lockout settings
                options.Lockout.MaxFailedAccessAttempts = 3;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.RequireUniqueEmail = true;
            });


            /***************************************************************************************
            *
            *   Require authenticated users
            *
            *   Set the default authentication policy to require users to be authenticated.
            *   You can opt out of authentication at the Razor Page, controller
            *   or action method level with the [AllowAnonymous] attribute.
            *
            *   Setting the default authentication policy to require users to be authenticated
            *   protects newly added Razor Pages and controllers.
            *
            *   Having authentication required by default is safer than relying on new controllers
            *   and Razor Pages to include the [Authorize] attribute.
            ***************************************************************************************/
            services.AddMvc();
            // requires: using Microsoft.AspNetCore.Authorization;
            //           using Microsoft.AspNetCore.Mvc.Authorization;
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });

            /*****************************************************************
             *  With the requirement of all users authenticated,
             *  the AuthorizeFolder and AuthorizePage calls are not required.
             ******************************************************************/
            // services.AddMvc()
            //     .AddRazorPagesOptions(options =>
            //     {
            //         options.Conventions.AuthorizeFolder("/Account/Manage");
            //         options.Conventions.AuthorizePage("/Account/Logout");
            //     });
            /*******************************************************************/

            /*****************************************************************
             *  Register no-op EmailSender used by account confirmation and password
             *  reset during development
             *  For more information on how to enable account confirmation and password reset,
             *  please visit https://go.microsoft.com/fwlink/?LinkID=532713
             ******************************************************************/
            services.AddSingleton <IEmailSender, EmailSender>();

            // Configure startup to use AuthMessageSenderOptions
            services.Configure <AuthMessageSenderOptions>(Configuration);

            // Register the authorization handlers
            // (not being used at this time)
            // services.AddScoped<IAuthorizationHandler, StudentAuthorizationHandler>();
            // services.AddScoped<IAuthorizationHandler, ApproverAuthorizationHandler>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanAccessStudentLink", policy =>
                                  policy.Requirements.Add(new CanAccessStudentLink()));

                options.AddPolicy("CanAccessApproverLink", policy =>
                                  policy.Requirements.Add(new CanAccessApproverLink()));

                options.AddPolicy("CanAccessProfileLink", policy =>
                                  policy.Requirements.Add(new CanAccessProfileLink()));
            });

            services.AddScoped <IAuthorizationHandler, CanAccessStudentLinkHandler>();
            services.AddScoped <IAuthorizationHandler, CanAccessApproverLinkHandler>();
            services.AddScoped <IAuthorizationHandler, CanAccessProfileLinkHandler>();

            // Register EventLogRepository
            services.AddScoped <IEventLogRepository, EventLogRepository>();

            // Register ProgramEnrollmentRepository
            services.AddScoped <IProgramEnrollmentRepository, ProgramEnrollmentRepository>();

            // Register EventLogService
            services.AddScoped <IEventLogService, EventLogService>();
        }
コード例 #22
0
ファイル: Startup.cs プロジェクト: OscarFoav/ProyectoCore
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // builder va a permitir consumir cualquier endpoint del proyecto para cualquier cliente
            services.AddCors(o => o.AddPolicy("corsApp", builder => {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            }));
            services.AddDbContext <CursosOnLineContext>(opt =>
            {
                opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            // Instanciar que se lance IFactoryConnection y IInstructor al arrancar el proyecto
            services.AddOptions();

            // Conexión a dapper
            services.Configure <ConexionConfiguracion>(Configuration.GetSection("ConnectionStrings"));

            services.AddMediatR(typeof(Consulta.Manejador).Assembly);

            // La modificación de debajo es para incluir la librería FluentValidation
            // services.AddControllers();
            services.AddControllers(opt => {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining <Nuevo>());
            // incluimos Core Identity <54> en WebAPI
            var builder         = services.AddIdentityCore <Usuario>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            // Incluir roles
            identityBuilder.AddRoles <IdentityRole>();
            identityBuilder.AddClaimsPrincipalFactory <UserClaimsPrincipalFactory <Usuario, IdentityRole> >();

            identityBuilder.AddEntityFrameworkStores <CursosOnLineContext>();
            identityBuilder.AddSignInManager <SignInManager <Usuario> >();
            services.TryAddSingleton <ISystemClock, SystemClock>();
            // Instanciar que se lance IFactoryConnection y IInstructor al arrancar el proyecto
            services.AddTransient <IFactoryConection, FactoryConnection>();
            services.AddScoped <IInstructor, InstructorRepositorio>();

            // Soportar Swagger
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title   = "Servicio de mantenimiento de cursos.",
                    Version = "v1"
                });
                c.CustomSchemaIds(c => c.FullName);
            });

            // Incluir seguridad del Token (posterior a JWT)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Mi palabra secreta"));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt => {
                opt.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false
                };
            });

            // JWT JSON Web Tokens
            services.AddScoped <IJwtGenerador, JwtGenerador>();
            services.AddScoped <IUsuarioSesion, UsuarioSesion>();
            services.AddAutoMapper(typeof(Consulta.Manejador));
            // Instanciar que se lance IFactoryConnection y al arrancar el proyecto
            services.AddTransient <IFactoryConection, FactoryConnection>();
            services.AddScoped <IInstructor, InstructorRepositorio>();
            // Instanciar paginación
            services.AddScoped <IPaginacion, PaginacionRepositorio>();
        }
コード例 #23
0
 public static AuthorizationPolicyBuilder RequireUserType(this AuthorizationPolicyBuilder builder,
                                                          LoggedInUserType type)
 {
     builder.AddRequirements(new StudentRequirement(type));
     return(builder);
 }
コード例 #24
0
ファイル: Startup.cs プロジェクト: nbyh/NetCoreCMS
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;

            _services.AddTransient <IEmailSender, AuthMessageSender>();
            _services.AddTransient <ISmsSender, AuthMessageSender>();
            _services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            _services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

            _services.AddLogging(loggingBuilder =>
                                 loggingBuilder.AddSerilog(dispose: true));

            _services.AddOptions();
            _services.AddSingleton(typeof(IStringLocalizer), typeof(NccStringLocalizer <SharedResource>));

            _services.AddLocalization();
            _mvcBuilder = services.AddMvc(config => {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                config.Filters.Add(new AuthorizeFilter(policy));
                config.CacheProfiles.Add(NccCacheProfile.Default,
                                         new CacheProfile()
                {
                    Duration        = 300,
                    VaryByQueryKeys = new string[] { "id", "name", "pageNumber", "page", "pageSize", "model", "lang", "status", "sessionId", "requestId", "start", "slug", }
                });
            });

            _mvcBuilder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            _mvcBuilder.AddDataAnnotationsLocalization(options => {
                options.DataAnnotationLocalizerProvider = (type, factory) => new NccStringLocalizer <SharedResource>(factory, new HttpContextAccessor());
            });

            _services.AddResponseCaching();
            _services.AddSession(options =>
            {
                options.Cookie.Name     = ".NetCoreCMS.Cookie.Session";
                options.IdleTimeout     = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
            });

            _services.AddDistributedMemoryCache();
            _services.AddResponseCompression();
            _services.AddSingleton(Configuration);

            _services.AddMaintenance(() => _setupConfig.IsMaintenanceMode, Encoding.UTF8.GetBytes("<div style='width:100%;text-align:center; padding-top:10px;'><h1>" + _setupConfig.MaintenanceMessage + "</h1></div>"), "text/html", _setupConfig.MaintenanceDownTime * 60);

            _services.AddNccCoreModuleServices();
            _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

            var themeFolder             = Path.Combine(_hostingEnvironment.ContentRootPath, NccInfo.ThemeFolder);
            var moduleFolder            = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ModuleFolder);
            var coreModuleFolder        = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.CoreModuleFolder);
            var themesDirectoryContents = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ThemeFolder);

            _themeManager.ScanThemeDirectory(themeFolder);
            _themeManager.RegisterThemes(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);

            var coreModules = _moduleManager.LoadModules(coreModuleFolder);
            var userModules = _moduleManager.LoadModules(moduleFolder);

            GlobalContext.Modules.AddRange(userModules);

            _services.AddModuleDependencies(_mvcBuilder);

            if (SetupHelper.IsDbCreateComplete)
            {
                _services.AddCustomizedIdentity();
                _startup.SelectDatabase(_services);

                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                _moduleManager.AddModulesAsApplicationPart(_mvcBuilder, _services, _serviceProvider);

                _moduleManager.AddModuleServices(_services);
                _moduleManager.AddModuleFilters(_services);
                _moduleManager.AddShortcodes(_services);
                _moduleManager.AddModuleWidgets(_services);
                _moduleManager.AddModuleAuthorizationHandlers(_services);

                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                _themeManager.RegisterThemeWidgets(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);
                _moduleManager.RegisterModuleWidgets(_mvcBuilder, _services, _serviceProvider);
                _moduleManager.RegisterModuleFilters(_mvcBuilder, _serviceProvider);
                _moduleManager.RegisterModuleShortCodes(_mvcBuilder, _serviceProvider);

                _moduleManager.LoadModuleMenus();
            }

            var defaultCulture = new RequestCulture("en");

            if (SetupHelper.IsAdminCreateComplete)
            {
                GlobalContext.SetupConfig = SetupHelper.LoadSetup();
                defaultCulture            = new RequestCulture(GlobalContext.SetupConfig.Language);
                GlobalMessageRegistry.LoadMessagesFromStorage();
            }

            services.Configure <RouteOptions>(options =>
            {
                options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
            });

            _services.Configure <RequestLocalizationOptions>(
                opts =>
            {
                var supportedCultures      = SupportedCultures.Cultures;
                opts.DefaultRequestCulture = defaultCulture;
                opts.SupportedCultures     = supportedCultures;
                opts.SupportedUICultures   = supportedCultures;

                var provider = new RouteDataRequestCultureProvider();
                provider.RouteDataStringKey   = "lang";
                provider.UIRouteDataStringKey = "lang";
                provider.Options             = opts;
                opts.RequestCultureProviders = new[] { provider };
            }
                );

            services.Configure <ClassLibraryLocalizationOptions>(
                options => options.ResourcePaths = new Dictionary <string, string>
            {
                { "NetCoreCMS.Framework", "i18n/Resources" },
                { "NetCoreCMS.Web", "Resources" }
            }
                );

            _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);
            _serviceProvider = _services.BuildModules(ConfigurationRoot, _hostingEnvironment);

            GlobalContext.ServiceProvider  = _serviceProvider;
            GlobalContext.Services         = _services;
            NetCoreCmsHost.Mediator        = _serviceProvider.GetService <IMediator>();
            NetCoreCmsHost.Services        = _services;
            NetCoreCmsHost.ServiceProvider = _serviceProvider;
        }
コード例 #25
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
            });
            services.AddDbContext <InMemoryContext>(opt => opt.UseInMemoryDatabase("InMemoryDatabase"));
            services.AddDbContext <BackOfficeContext>(opt =>
                                                      opt.UseMySql(Configuration.GetConnectionString("MySqlConnection"),
                                                                   x => x.MigrationsAssembly("Persistence")));
            services.AddTransient <IUnitOfWork, UnitOfWork>();
            services.AddMediatR(new Assembly[] { Assembly.Load("Application") });
            services.AddDistributedMemoryCache();
            services.AddAutoMapper();
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "Developer-tool API", Version = "v1"
                });

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                });
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();

            services.AddMvc(opt => {
                opt.Filters.Add(typeof(ValidatorActionFilter));
                opt.Filters.Add(new AuthorizeFilter(policy));
                opt.OutputFormatters.Add(new HtmlOutputFormatter());
            }).AddFluentValidation(fvc =>
                                   fvc.RegisterValidatorsFromAssemblyContaining <Startup>());
            services.AddOptions();
            services.Configure <CacheOptions>(Configuration.GetSection("Cache:CacheOptions"));
            services.Configure <JwtOptions>(Configuration.GetSection("Jwt"));
        }
コード例 #26
0
        // 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)
        {
            services.AddDbContextPool <AppDbContext>(
                options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength      = 10;
                options.Password.RequiredUniqueChars = 3;

                options.SignIn.RequireConfirmedEmail = true;

                options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";

                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <CustomEmailConfirmationTokenProvider
                               <ApplicationUser> >("CustomEmailConfirmation");

            services.Configure <DataProtectionTokenProviderOptions>(o =>
                                                                    o.TokenLifespan = TimeSpan.FromHours(5));

            services.Configure <CustomEmailConfirmationTokenProviderOptions>(o =>
                                                                             o.TokenLifespan = TimeSpan.FromDays(3));

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlSerializerFormatters();

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "443892072779-3n0ljac2jnar4kmnnlkn74h4ic1tdq54.apps.googleusercontent.com";
                options.ClientSecret = "7C6TvX2SWEodUuXd3EpsoO1R";
            })
            .AddFacebook(options =>
            {
                options.AppId     = "2316662895109472";
                options.AppSecret = "e25c1b8d4145034ed426d7a05efe1481";
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Administration/AccessDenied");
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("DeleteRolePolicy",
                                  policy => policy.RequireClaim("Delete Role"));

                options.AddPolicy("EditRolePolicy",
                                  policy => policy.AddRequirements(new ManageAdminRolesAndClaimsRequirement()));

                options.AddPolicy("AdminRolePolicy",
                                  policy => policy.RequireRole("Admin"));
            });

            services.AddScoped <IEmployeeRepository, SQLEmployeeRepository>();

            services.AddSingleton <IAuthorizationHandler, CanEditOnlyOtherAdminRolesAndClaimsHandler>();
            services.AddSingleton <IAuthorizationHandler, SuperAdminHandler>();
            services.AddSingleton <DataProtectionPurposeStrings>();
        }
コード例 #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            // Add initial data in database
            services.AddTransient <DbInitializer>();

            services.AddSingleton <IJwtFactory, JwtFactory>();

            services.TryAddTransient <IHttpContextAccessor, HttpContextAccessor>();

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
            });

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;
            });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                //options.AddPolicy("UserPolicy",
                //          policy =>
                //          policy.Requirements.Add(new UserRoleRequirement()));

                var userPolicy = new AuthorizationPolicyBuilder()
                                 .RequireAssertion(ctx =>
                {
                    return(ctx.User.HasClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.AdminRole) ||
                           ctx.User.HasClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.UserRole));
                })
                                 .Build();

                var adminPolicy = new AuthorizationPolicyBuilder()
                                  .RequireAssertion(ctx =>
                {
                    return(ctx.User.HasClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.AdminRole));
                })
                                  .Build();


                options.AddPolicy("UserPolicy", userPolicy);
                options.AddPolicy("AdminPolicy", adminPolicy);
            });

            // add identity
            var builder = services.AddIdentityCore <AppUser>(o =>
            {
                // configure identity options
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            });

            builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
            builder.AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders();

            // Automapper
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });

            services.AddCors();
            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>())
            .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );

            // Repositories
            services.AddScoped <IMovieRepository, MovieRepository>();
            services.AddScoped <IActorRepository, ActorRepository>();

            services.AddTransient <UserManager <AppUser> >();
            services.AddTransient <RoleManager <IdentityRole> >();
        }
コード例 #28
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })//dependency injection container services we need to add in our application that we want available everywhere
            .AddFluentValidation(cfg =>
            {
                cfg.RegisterValidatorsFromAssemblyContaining <Create>();
            });

            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("WWW-Authenticate")
                    .WithOrigins("http://localhost:3000")
                    .AllowCredentials();
                });
            });
            services.AddMediatR(typeof(List.Handler).Assembly);////add assemblies of type Handler///mediatR should target the List Handler
            services.AddAutoMapper(typeof(List.Handler));
            services.AddSignalR();
            var builder = services.AddIdentityCore <AppUser>(options => {
                options.SignIn.RequireConfirmedEmail = true;
            });
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();
            identityBuilder.AddDefaultTokenProviders();
            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });
            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();
            ///new instance on every call only available for the lifetime of the request

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.AddScoped <IProfileReader, ProfileReader>();
            services.AddScoped <IFaceBookAcessor, FaceBookAccessor>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
            services.Configure <FaceBookAppSettings>(Configuration.GetSection("Authentication:Facebook"));
            services.Configure <SendGridSettings>(Configuration.GetSection("SendGrid"));
            ///stroonglt type cloudinary to configuration...to enable it to be injected in IConfiguration
            ////to enable the method to be injected across classes
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };

                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;

                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }
コード例 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(options =>
            {
                options.UseLazyLoadingProxies();
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("WWW-Authenticate")
                    .WithOrigins("http://localhost:3000")
                    .AllowCredentials();
                });
            });
            services.AddMediatR((typeof(List.Handler).Assembly));
            services.AddAutoMapper(typeof(List.Handler));
            services.AddSignalR();
            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg =>
            {
                cfg.RegisterValidatorsFromAssemblyContaining <Create>();
            });

            var builder         = services.AddIdentityCore <AppUser>();
            var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);

            identityBuilder.AddEntityFrameworkStores <DataContext>();
            identityBuilder.AddSignInManager <SignInManager <AppUser> >();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("IsActivityHost", policy =>
                {
                    policy.Requirements.Add(new IsHostRequirement());
                });
            });

            services.AddTransient <IAuthorizationHandler, IsHostRequirementHandler>();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));



            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateAudience         = false,
                    ValidateIssuer           = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat")))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IUserAccessor, UserAccessor>();
            services.AddScoped <IPhotoAccessor, PhotoAccessor>();
            services.AddScoped <IProfileReader, ProfileReader>();
            services.Configure <CloudinarySettings>(Configuration.GetSection("Cloudinary"));
        }
コード例 #30
0
        public void ConfigureServices(IServiceCollection services)
        {
            RepositoryModule.Load(services);
            ServiceModule.Load(services);
            ApplicationModule.Load(services);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var connection = Configuration["ConnectionStrings:MyConnStr"];
            //services.AddDbContext<j2pContext>(options => options.UseMySql(connection));

            //Config Token
            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfiguration
            {
                Audience = AUDIENCE,
                Issuer   = ISSUER,
                Seconds  = int.Parse(TimeSpan.FromDays(1).TotalSeconds.ToString())
            };

            services.AddSingleton(tokenConfigurations);
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.SigningCredentials.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                // Valida a assinatura de um token recebido
                paramsValidation.ValidateIssuerSigningKey = true;

                // Verifica se um token recebido 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;
            });

            // Ativa o uso do token como forma de autorizar o acesso
            // a recursos deste projeto
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            //Para todas as requisições serem necessaria o token, para um endpoint não exigir o token
            //deve colocar o [AllowAnonymous]
            //Caso remova essa linha, para todas as requisições que precisar de token, deve colocar
            //o atributo [Authorize("Bearer")]
            services.AddMvc(x =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                             .RequireAuthenticatedUser().Build();

                x.Filters.Add(new AuthorizeFilter(policy));
            });

            //services.AddMvc();

            services.AddCors();

            var config = new AutoMapper.MapperConfiguration(c =>
            {
                c.AddProfile(new ApplicationProfile());
            });

            var mapper = config.CreateMapper();

            services.AddSingleton(mapper);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }