当前位置: 首页>>代码示例>>C#>>正文


C# IServiceCollection.ConfigureCookieAuthentication方法代码示例

本文整理汇总了C#中IServiceCollection.ConfigureCookieAuthentication方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.ConfigureCookieAuthentication方法的具体用法?C# IServiceCollection.ConfigureCookieAuthentication怎么用?C# IServiceCollection.ConfigureCookieAuthentication使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IServiceCollection的用法示例。


在下文中一共展示了IServiceCollection.ConfigureCookieAuthentication方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ConfigureServices

    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc(config =>
      {
#if !DEBUG
        //config.Filters.Add(new RequireHttpsAttribute());
#endif
      })
      .AddJsonOptions(opt =>
      {
        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
      });

      services.AddIdentity<WorldUser, IdentityRole>(config =>
      {
        config.User.RequireUniqueEmail = true;
        config.Password.RequiredLength = 8;
      })
      .AddEntityFrameworkStores<WorldContext>();

      services.ConfigureCookieAuthentication(config =>
      {
        config.LoginPath = "/Auth/Login";
        config.Notifications = new CookieAuthenticationNotifications()
        {
          OnApplyRedirect = ctx =>
          {
            if (ctx.Request.Path.StartsWithSegments("/api") && 
                ctx.Response.StatusCode == 200)
            {
              ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
              ctx.Response.Redirect(ctx.RedirectUri);
            }
          }
        };
      });

      services.AddLogging();

      services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<WorldContext>();

      services.AddScoped<CoordService>();
      services.AddTransient<WorldContextSeedData>();
      services.AddScoped<IWorldRepository, WorldRepository>();

#if DEBUG
      services.AddScoped<IMailService, DebugMailService>();
#else
      services.AddScoped<IMailService, DebugMailService>();
#endif
    }
开发者ID:SolosoftNL,项目名称:The-World,代码行数:57,代码来源:Startup.cs

示例2: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));

            var useInMemoryStore = _platform.IsRunningOnMono || _platform.IsRunningOnNanoServer;

            // Add EF services to the services container
            if (useInMemoryStore)
            {
                services.AddEntityFramework()
                        .AddInMemoryDatabase()
                        .AddDbContext<MusicStoreContext>(options =>
                            options.UseInMemoryDatabase());
            }
            else
            {
                services.AddEntityFramework()
                        .AddSqlServer()
                        .AddDbContext<MusicStoreContext>(options =>
                            options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString")));
            }

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>()
                    .AddDefaultTokenProviders();

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

            services.ConfigureFacebookAuthentication(options =>
            {
                options.AppId = "550624398330273";
                options.AppSecret = "10e56a291d6b618da61b1e0dae3a8954";
            });

            services.ConfigureGoogleAuthentication(options =>
            {
                options.ClientId = "977382855444.apps.googleusercontent.com";
                options.ClientSecret = "NafT482F70Vjj_9q1PU4B0pN";
            });

            services.ConfigureTwitterAuthentication(options =>
            {
                options.ConsumerKey = "9J3j3pSwgbWkgPFH7nAf0Spam";
                options.ConsumerSecret = "jUBYkQuBFyqp7G3CUB9SW3AfflFr9z3oQBiNvumYy87Al0W4h8";
            });

            services.ConfigureMicrosoftAccountAuthentication(options =>
            {
                options.Caption = "MicrosoftAccount - Requires project changes";
                options.ClientId = "000000004012C08A";
                options.ClientSecret = "GaMQ2hCnqAC6EcDLnXsAeBVIJOLmeutL";
            });

            services.ConfigureCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.WithOrigins("http://example.com");
                });
            });

            // Add MVC services to the services container
            services.AddMvc();

            //Add all SignalR related services to IoC.
            services.AddSignalR();

            //Add InMemoryCache
            services.AddSingleton<IMemoryCache, MemoryCache>();

            // Add session related services.
            services.AddCaching();
            services.AddSession();

            // Add the system clock service
            services.AddSingleton<ISystemClock, SystemClock>();

            // Configure Auth
            services.Configure<AuthorizationOptions>(options =>
            {
                options.AddPolicy("ManageStore", new AuthorizationPolicyBuilder().RequireClaim("ManageStore", "Allowed").Build());
            });
        }
开发者ID:ZhangYueqiu,项目名称:asp5-mvc6-examples,代码行数:87,代码来源:Startup.cs

示例3: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));

            //Sql client not available on mono
            string value;
            var useInMemoryStore = Configuration.TryGet("UseInMemoryStore", out value) && value == "true" ?
                true :
                _runtimeEnvironment.RuntimeType.Equals("Mono", StringComparison.OrdinalIgnoreCase);

            // Add EF services to the services container
            if (useInMemoryStore)
            {
                services.AddEntityFramework()
                        .AddInMemoryDatabase()
                        .AddDbContext<MusicStoreContext>(options =>
                            options.UseInMemoryDatabase());
            }
            else
            {
                services.AddEntityFramework()
                        .AddSqlServer()
                        .AddDbContext<MusicStoreContext>(options =>
                            options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString")));
            }

            // Add Identity services to the services container
            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<MusicStoreContext>()
                    .AddDefaultTokenProviders();

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

            services.ConfigureFacebookAuthentication(options =>
            {
                options.AppId = "[AppId]";
                options.AppSecret = "[AppSecret]";
                options.Notifications = new OAuthAuthenticationNotifications()
                {
                    OnAuthenticated = FacebookNotifications.OnAuthenticated,
                    OnReturnEndpoint = FacebookNotifications.OnReturnEndpoint,
                    OnApplyRedirect = FacebookNotifications.OnApplyRedirect
                };
                options.BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler();
                options.StateDataFormat = new CustomStateDataFormat();
                options.Scope.Add("email");
                options.Scope.Add("read_friendlists");
                options.Scope.Add("user_checkins");
            });

            services.ConfigureGoogleAuthentication(options =>
            {
                options.ClientId = "[ClientId]";
                options.ClientSecret = "[ClientSecret]";
                options.AccessType = "offline";
                options.Notifications = new OAuthAuthenticationNotifications()
                {
                    OnAuthenticated = GoogleNotifications.OnAuthenticated,
                    OnReturnEndpoint = GoogleNotifications.OnReturnEndpoint,
                    OnApplyRedirect = GoogleNotifications.OnApplyRedirect
                };
                options.StateDataFormat = new CustomStateDataFormat();
                options.BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler();
            });

            services.ConfigureTwitterAuthentication(options =>
            {
                options.ConsumerKey = "[ConsumerKey]";
                options.ConsumerSecret = "[ConsumerSecret]";
                options.Notifications = new TwitterAuthenticationNotifications()
                {
                    OnAuthenticated = TwitterNotifications.OnAuthenticated,
                    OnReturnEndpoint = TwitterNotifications.OnReturnEndpoint,
                    OnApplyRedirect = TwitterNotifications.OnApplyRedirect
                };
                options.StateDataFormat = new CustomTwitterStateDataFormat();
                options.BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler();
#if DNX451
                options.BackchannelCertificateValidator = null;
#endif
            });

            services.ConfigureMicrosoftAccountAuthentication(options =>
            {
                options.Caption = "MicrosoftAccount - Requires project changes";
                options.ClientId = "[ClientId]";
                options.ClientSecret = "[ClientSecret]";
                options.Notifications = new OAuthAuthenticationNotifications()
                {
                    OnAuthenticated = MicrosoftAccountNotifications.OnAuthenticated,
                    OnReturnEndpoint = MicrosoftAccountNotifications.OnReturnEndpoint,
                    OnApplyRedirect = MicrosoftAccountNotifications.OnApplyRedirect
                };
                options.BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler();
                options.StateDataFormat = new CustomStateDataFormat();
                options.Scope.Add("wl.basic");
                options.Scope.Add("wl.signin");
//.........这里部分代码省略.........
开发者ID:Glimpse,项目名称:MusicStore,代码行数:101,代码来源:StartupSocialTesting.cs

示例4: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            // Add Smash League data
            services.AddSmashLeagueData(options =>
            {
                options.ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];
            });

            // Congfigure logging
            services.AddLogging();

            // Configure battlenet authentication
            services.ConfigureBattlenetAuthentication(options =>
            {
                options.CallbackPath = new PathString("/auth/signin-battlenet");
                options.ClientId = Configuration["Battlenet:ClientId"];
                options.ClientSecret = Configuration["Battlenet:ClientSecret"];
            });

            // Configure cookie authentication
            services.ConfigureCookieAuthentication(options =>
            {
                options.LoginPath = null;
                options.AccessDeniedPath = null;
            });

            // Add Mvc services
            services.AddMvc();

            // Add email services
            services.AddEmailService();

            // Add application services
            services.AddSmashLeagueServices(Environment);

            services.AddSmashLeagueAuthorization();
        }
开发者ID:iteam-software,项目名称:smash-league,代码行数:37,代码来源:Startup.cs

示例5: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Entity Framework services to the services container.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:CRMDBConnection:ConnectionString"]));

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.ConfigureIdentity(conf => {
                conf.Password.RequiredLength = 6;
                conf.Password.RequireLowercase = false;
                conf.Password.RequireDigit = false;
                conf.Password.RequireNonLetterOrDigit = false;
                conf.Password.RequireUppercase = false;

                conf.User.UserNameValidationRegex = null;
            });

            // Configure the options for the authentication middleware.
            // You can add options for Google, Twitter and other middleware as shown below.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            services.Configure<FacebookAuthenticationOptions>(options =>
            {
                options.AppId = Configuration["Authentication:Facebook:AppId"];
                options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            });

            services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
            {
                options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
                options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
            });

            services.ConfigureCookieAuthentication(options => {
                CookieAuthenticationNotifications cookieAuthN = options.Notifications as CookieAuthenticationNotifications;
                if (cookieAuthN == null)
                {
                    cookieAuthN = new CookieAuthenticationNotifications();
                    options.Notifications = cookieAuthN;
                }

                cookieAuthN.OnApplyRedirect = ctx =>
                {
                    if (IsAjaxRequest(ctx.Request) == false)
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                };
            });

            // Add MVC services to the services container.
            services.AddMvc();

            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();

            // Register application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            services.AddReact();
        }
开发者ID:AntonHuang,项目名称:WebApp,代码行数:68,代码来源:Startup.cs

示例6: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Application Insights data collection services to the services container.
            services.AddApplicationInsightsTelemetry(Configuration);

            // Add Entity Framework services to the services container.
            if (Configuration["Data:DefaultConnection:UseInMemory"] == "true")
            {
                services.AddEntityFramework()
                .AddInMemoryStore()
                .AddDbContext<PrepOpsContext>();
            }
            else
            {
                //string connectionStringPath = "Data:DefaultConnection:LocalConnectionString";
                string connectionStringPath = "Data:DefaultConnection:AzureConnectionString";
                services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<PrepOpsContext>(options =>
                    options.UseSqlServer(Configuration[connectionStringPath]));
            }

            // Add CORS support
            services.AddCors();

            //var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();

            //policy.Headers.Add("*");
            //policy.Methods.Add("*");
            //policy.Origins.Add("*");
            //policy.SupportsCredentials = true;

            //services.ConfigureCors(x => x.AddPolicy("prepOps", policy));
            services.ConfigureCors(options => {
                options.AddPolicy("prepOps",
                    builder => builder.AllowAnyOrigin()
                                .AllowAnyHeader()
                                .AllowAnyMethod()
                                .AllowCredentials()
                    );
            });

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<PrepOpsContext>()
                .AddDefaultTokenProviders();

            // Add Authorization rules for the app
            services.Configure<AuthorizationOptions>(options =>
            {
                options.AddPolicy("TenantAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", new string[] { "TenantAdmin", "SiteAdmin" }).Build());
                options.AddPolicy("SiteAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", "SiteAdmin").Build());
            });

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

            // Configure the options for the authentication middleware.
            // You can add options for Google, Twitter and other middleware as shown below.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            if (Configuration["Authentication:Facebook:AppId"] != null)
            {
                services.Configure<FacebookAuthenticationOptions>(options =>
                {
                    options.AppId = Configuration["Authentication:Facebook:AppId"];
                    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                });
            }

            //Enable Twitter Auth, only id key set
            if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
            {
                services.Configure<TwitterAuthenticationOptions>(options =>
                {
                    options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
                    options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
                });
            }

            if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
            {
                services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
                {
                    options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
                    options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
                });
            }

            // Add MVC services to the services container.
            services.AddMvc();

            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();

            // Register application services.
            services.AddSingleton((x) => this.Configuration);
//.........这里部分代码省略.........
开发者ID:rspaulino,项目名称:allReady,代码行数:101,代码来源:Startup.cs

示例7: ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<GlobalSettings>(Configuration.GetSection("globalSettings"));

            // Options
            services.AddOptions();

            // Settings
            var provider = services.BuildServiceProvider();
            var globalSettings = provider.GetRequiredService<IOptions<GlobalSettings>>().Options;
            services.AddSingleton(s => globalSettings);

            // Repositories
            services.AddSingleton<IPostRepository>(s => new Core.Repositories.Sql.PostRepository(globalSettings));
            services.AddSingleton<IUserRepository>(s => new Core.Repositories.Sql.UserRepository(globalSettings));
            services.AddSingleton<IBlogRepository>(s => new Core.Repositories.Sql.BlogRepository(globalSettings));

            // Identity
            services.AddTransient<ILookupNormalizer, LowerInvariantLookupNormalizer>();
            services.AddTransient<IPasswordHasher<User>, PlaintextPasswordHasher>();
            services.AddIdentity<User, Role>().AddUserStore<UserStore>().AddRoleStore<RoleStore>();

            // Services
            services.AddScoped<IPostService, PostService>();
            services.AddScoped<IPageService, PageService>();
            services.AddScoped<IBlogService, BlogService>();

            // Auth
            services.ConfigureCookieAuthentication(options =>
            {
                options.CookieName = "NPress";
                options.ExpireTimeSpan = new TimeSpan(30, 0, 0, 0);
                options.SlidingExpiration = true;
                options.ReturnUrlParameter = "returnUrl";
                options.LoginPath = new PathString("/admin/login");
                options.AccessDeniedPath = new PathString("/admin/login");
                options.LogoutPath = new PathString("/admin/logout");
            });

            // MVC
            services.AddMvc();
        }
开发者ID:kspearrin,项目名称:NPress,代码行数:42,代码来源:Startup.cs

示例8: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Application Insights data collection services to the services container.
              services.AddApplicationInsightsTelemetry(Configuration);

              // Add Entity Framework services to the services container.
              var ef = services.AddEntityFramework();

              if (Configuration["Data:DefaultConnection:UseInMemory"].ToLowerInvariant() == "true")
              {
            ef = ef.AddInMemoryDatabase();
              }
              else
              {
            ef = ef.AddSqlServer();
              }

              ef.AddDbContext<AllReadyContext>();

              // Add CORS support
              services.AddCors();
              services.ConfigureCors(options =>
              {
            options.AddPolicy("allReady",
            builder => builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
            );
              });

              // Add Identity services to the services container.
              services.AddIdentity<ApplicationUser, IdentityRole>()
              .AddEntityFrameworkStores<AllReadyContext>()
              .AddDefaultTokenProviders();

              // Add Authorization rules for the app
              services.Configure<AuthorizationOptions>(options =>
              {
            options.AddPolicy("TenantAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", new string[] { "TenantAdmin", "SiteAdmin" }).Build());
            options.AddPolicy("SiteAdmin", new AuthorizationPolicyBuilder().RequireClaim("UserType", "SiteAdmin").Build());
              });

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

              // Configure the options for the authentication middleware.
              // You can add options for Google, Twitter and other middleware as shown below.
              // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
              if (Configuration["Authentication:Facebook:AppId"] != null)
              {
            services.Configure<FacebookAuthenticationOptions>(options =>
            {
              options.AppId = Configuration["Authentication:Facebook:AppId"];
              options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            });
              }

              //Enable Twitter Auth, only id key set
              if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
              {
            services.Configure<TwitterAuthenticationOptions>(options =>
            {
              options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
              options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
            });
              }

              if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
              {
            services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
            {
              options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
              options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
            });
              }

              // Add MVC services to the services container.
              services.AddMvc();

              // Register application services.
              services.AddSingleton((x) => Configuration);
              services.AddTransient<IEmailSender, AuthMessageSender>();
              services.AddTransient<ISmsSender, AuthMessageSender>();
              services.AddSingleton<IClosestLocations, SqlClosestLocations>();
              services.AddTransient<IAllReadyDataAccess, AllReadyDataAccessEF7>();
              services.AddSingleton<IImageService, ImageService>();
              //services.AddSingleton<GeoService>();
        }
开发者ID:rebeccacollins,项目名称:allReady,代码行数:92,代码来源:Startup.cs


注:本文中的IServiceCollection.ConfigureCookieAuthentication方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。