示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //services.AddTransient<IEmailSender, AuthMessageSender>();
            //services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient <IContextService, ContextService>();

            var hostingEnvironment = services.BuildServiceProvider().GetService <IHostingEnvironment>();

            services.AddOptions();
            services.AddHttpContextAccessor();

            services.AddOpenCqrs().AddMySqlProvider(Configuration);

            services.Configure <NTCore.DataAccess.Configuration.Data>(c =>
            {
                c.Provider = (NTCore.DataAccess.Configuration.DataProvider)Enum.Parse(
                    typeof(NTCore.DataAccess.Configuration.DataProvider),
                    Configuration.GetSection("Data")["Provider"]);
            });
            services.Configure <ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

            //services.AddApplicationInsightsTelemetry(Configuration);
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = Configuration.GetConnectionString("Redis");
            });

            services.AddEntityFramework(Configuration);
            //services.AddTransient<IContextFactory, ContextFactory>();

            // TEMP
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySQL(Configuration.GetConnectionString("ConnectionString")));

            // TEMP
            services.AddIdentity <ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ViewLocationExpander());
            });

            //var connection = Configuration.GetConnectionString("SqlServer");
            //services.AddEntityFrameworkSqlServer().AddDbContext<MainContext>(options => options.UseSqlServer(connection, b => b.MigrationsAssembly("NTCore.WebFront")));
            //var connection = Configuration.GetConnectionString("MySQL");
            //services.AddEntityFrameworkSqlServer().AddDbContext<NFDbContext>(options => options.UseMySQL(connection, b => b.MigrationsAssembly("NTCore.WebFront")));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = Keys.AuthenticationScheme;
                options.DefaultChallengeScheme    = Keys.AuthenticationScheme;
            })
            .AddCookie(Keys.AuthenticationScheme, options =>
            {
                options.Cookie.Name = Keys.AuthenticationCookie;
                options.Cookie.Path = "/";

                var path = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "auth-ticket-keys"));
                options.DataProtectionProvider = DataProtectionProvider.Create(path);

                options.LoginPath           = "/passport/login";
                options.LogoutPath          = "/passport/logout";
                options.AccessDeniedPath    = "/passport/forbidden";
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.Lax;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });


            //services.AddMvc(options =>
            //{
            //    options.Filters.Add(typeof(ValidationFilter));

            //    var policy = new AuthorizationPolicyBuilder()
            //        .RequireAuthenticatedUser()
            //        .Build();
            //    options.Filters.Add(new AuthorizeFilter(policy));
            //});
            var builder = new ContainerBuilder();

            builder.RegisterModule(new AutofacModule());
            builder.Populate(services);

            var container = builder.Build();

            return(container.Resolve <IServiceProvider>());
        }
示例#2
0
 public PasswordTokenFactory(string appName)
 {
     _provider = DataProtectionProvider.Create(appName);
 }
示例#3
0
        /// <summary>
        /// Creates a new instance of the <see cref="OpenIdConnectServerMiddleware"/> class.
        /// </summary>
        public OpenIdConnectServerMiddleware(
            [NotNull] OwinMiddleware next,
            [NotNull] IDictionary <string, object> properties,
            [NotNull] OpenIdConnectServerOptions options)
            : base(next, options)
        {
            if (Options.HtmlEncoder == null)
            {
                throw new ArgumentException("The HTML encoder registered in the options cannot be null.", nameof(options));
            }

            if (Options.Provider == null)
            {
                throw new ArgumentException("The authorization provider registered in the options cannot be null.", nameof(options));
            }

            if (Options.SystemClock == null)
            {
                throw new ArgumentException("The system clock registered in the options cannot be null.", nameof(options));
            }

            if (Options.Issuer != null)
            {
                if (!Options.Issuer.IsAbsoluteUri)
                {
                    throw new ArgumentException("The issuer registered in the options must be a valid absolute URI.", nameof(options));
                }

                // See http://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery
                if (!string.IsNullOrEmpty(Options.Issuer.Query) || !string.IsNullOrEmpty(Options.Issuer.Fragment))
                {
                    throw new ArgumentException("The issuer registered in the options must contain " +
                                                "no query and no fragment parts.", nameof(options));
                }

                // Note: while the issuer parameter should be a HTTPS URI, making HTTPS mandatory
                // in Owin.Security.OpenIdConnect.Server would prevent the end developer from
                // running the different samples in test environments, where HTTPS is often disabled.
                // To mitigate this issue, AllowInsecureHttp can be set to true to bypass the HTTPS check.
                // See http://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery
                if (!Options.AllowInsecureHttp && string.Equals(Options.Issuer.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("The issuer registered in the options must be a HTTPS URI when " +
                                                "AllowInsecureHttp is not set to true.", nameof(options));
                }
            }

            if (Options.AuthenticationMode == AuthenticationMode.Active)
            {
                throw new ArgumentException("Automatic authentication cannot be used with " +
                                            "the OpenID Connect server middleware.", nameof(options));
            }

            if (Options.AccessTokenHandler != null && !(Options.AccessTokenHandler is JwtSecurityTokenHandler))
            {
                throw new ArgumentException("The access token handler must be derived from 'JwtSecurityTokenHandler'.", nameof(options));
            }

            // Ensure at least one signing certificate/key was registered if an access token handler was registered.
            if (Options.AccessTokenHandler != null && Options.SigningCredentials.Count == 0)
            {
                throw new ArgumentException("At least one signing key must be registered when using JWT as the access token format. " +
                                            "Consider registering a X.509 certificate using 'services.AddOpenIddict().AddSigningCertificate()' " +
                                            "or call 'services.AddOpenIddict().AddEphemeralSigningKey()' to use an ephemeral key.", nameof(options));
            }

            if (Options.Logger == null)
            {
                Options.Logger = new LoggerFactory().CreateLogger <OpenIdConnectServerMiddleware>();
            }

            if (Options.DataProtectionProvider == null)
            {
                // Use the application name provided by the OWIN host as the Data Protection discriminator.
                // If the application name cannot be resolved, throw an invalid operation exception.
                var discriminator = new AppProperties(properties).AppName;
                if (string.IsNullOrEmpty(discriminator))
                {
                    throw new InvalidOperationException("The application name cannot be resolved from the OWIN application builder. " +
                                                        "Consider manually setting the 'DataProtectionProvider' property in the " +
                                                        "options using 'DataProtectionProvider.Create([unique application name])'.");
                }

                Options.DataProtectionProvider = DataProtectionProvider.Create(discriminator);
            }

            if (Options.AccessTokenFormat == null)
            {
                var protector = Options.DataProtectionProvider.CreateProtector(
                    nameof(OpenIdConnectServerHandler),
                    nameof(Options.AccessTokenFormat), Options.AuthenticationType);

                Options.AccessTokenFormat = new AspNetTicketDataFormat(new DataProtectorShim(protector));
            }

            if (Options.AuthorizationCodeFormat == null)
            {
                var protector = Options.DataProtectionProvider.CreateProtector(
                    nameof(OpenIdConnectServerHandler),
                    nameof(Options.AuthorizationCodeFormat), Options.AuthenticationType);

                Options.AuthorizationCodeFormat = new AspNetTicketDataFormat(new DataProtectorShim(protector));
            }

            if (Options.RefreshTokenFormat == null)
            {
                var protector = Options.DataProtectionProvider.CreateProtector(
                    nameof(OpenIdConnectServerHandler),
                    nameof(Options.RefreshTokenFormat), Options.AuthenticationType);

                Options.RefreshTokenFormat = new AspNetTicketDataFormat(new DataProtectorShim(protector));
            }

            var environment = new AppProperties(properties).Get <string>("host.AppMode");

            if (Options.AllowInsecureHttp && !string.Equals(environment, "Development", StringComparison.OrdinalIgnoreCase))
            {
                Options.Logger.LogWarning("Disabling the transport security requirement is not recommended in production. " +
                                          "Consider setting 'OpenIdConnectServerOptions.AllowInsecureHttp' to 'false' " +
                                          "to prevent the OpenID Connect server middleware from serving non-HTTPS requests.");
            }
        }
示例#4
0
        public void ConfigureServices(IServiceCollection services)
        {
            NullGuard.NotNull(services, nameof(services));

            services.Configure <ForwardedHeadersOptions>(opt =>
            {
                opt.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                opt.KnownNetworks.Clear();
                opt.KnownProxies.Clear();
            });

            services.Configure <CookiePolicyOptions>(opt =>
            {
                opt.CheckConsentNeeded    = context => true;
                opt.MinimumSameSitePolicy = SameSiteMode.None;
                opt.Secure = CookieSecurePolicy.SameAsRequest;
            });

            services.AddDataProtection()
            .SetApplicationName("OSDevGrp.OSIntranet.Mvc")
            .UseEphemeralDataProtectionProvider()
            .SetDefaultKeyLifetime(new TimeSpan(30, 0, 0, 0));

            services.AddAntiforgery();

            services.AddControllersWithViews(opt => opt.Filters.Add(typeof(AcquireTokenActionFilter)))
            .AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                opt.JsonSerializerOptions.Converters.Add(new DecimalFormatJsonConverter());
                opt.JsonSerializerOptions.Converters.Add(new NullableDecimalFormatJsonConverter());
                opt.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
            });
            services.AddRazorPages();

            services.AddAuthentication(opt =>
            {
                opt.DefaultScheme       = "OSDevGrp.OSIntranet.Internal";
                opt.DefaultSignInScheme = "OSDevGrp.OSIntranet.External";
            })
            .AddCookie("OSDevGrp.OSIntranet.Internal", opt =>
            {
                opt.LoginPath              = "/Account/Login";
                opt.LogoutPath             = "/Account/Logoff";
                opt.ExpireTimeSpan         = new TimeSpan(0, 60, 0);
                opt.Cookie.SameSite        = SameSiteMode.None;
                opt.Cookie.SecurePolicy    = CookieSecurePolicy.SameAsRequest;
                opt.DataProtectionProvider = DataProtectionProvider.Create("OSDevGrp.OSIntranet.Mvc");
            })
            .AddCookie("OSDevGrp.OSIntranet.External", opt =>
            {
                opt.LoginPath              = "/Account/Login";
                opt.LogoutPath             = "/Account/Logoff";
                opt.ExpireTimeSpan         = new TimeSpan(0, 0, 10);
                opt.Cookie.SameSite        = SameSiteMode.None;
                opt.Cookie.SecurePolicy    = CookieSecurePolicy.SameAsRequest;
                opt.DataProtectionProvider = DataProtectionProvider.Create("OSDevGrp.OSIntranet.Mvc");
            })
            .AddMicrosoftAccount(opt =>
            {
                opt.ClientId     = Configuration["Security:Microsoft:ClientId"];
                opt.ClientSecret = Configuration["Security:Microsoft:ClientSecret"];
                opt.SignInScheme = "OSDevGrp.OSIntranet.External";
                opt.CorrelationCookie.SameSite     = SameSiteMode.None;
                opt.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                opt.SaveTokens = true;
                opt.Scope.Clear();
                opt.Scope.Add("User.Read");
                opt.Scope.Add("Contacts.ReadWrite");
                opt.Scope.Add("offline_access");
                opt.Events.OnCreatingTicket += o =>
                {
                    double seconds = o.ExpiresIn?.TotalSeconds ?? 0;
                    IRefreshableToken refreshableToken = new RefreshableToken(o.TokenType, o.AccessToken, o.RefreshToken, DateTime.UtcNow.AddSeconds(seconds));
                    o.Properties.Items.Add($".{TokenType.MicrosoftGraphToken}", refreshableToken.ToBase64());
                    return(Task.CompletedTask);
                };
                opt.DataProtectionProvider = DataProtectionProvider.Create("OSDevGrp.OSIntranet.Mvc");
            })
            .AddGoogle(opt =>
            {
                opt.ClientId     = Configuration["Security:Google:ClientId"];
                opt.ClientSecret = Configuration["Security:Google:ClientSecret"];
                opt.SignInScheme = "OSDevGrp.OSIntranet.External";
                opt.CorrelationCookie.SameSite     = SameSiteMode.None;
                opt.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                opt.DataProtectionProvider         = DataProtectionProvider.Create("OSDevGrp.OSIntranet.Mvc");
            });
            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("SecurityAdmin", policy => policy.RequireClaim(ClaimHelper.SecurityAdminClaimType));
                opt.AddPolicy("Accounting", policy => policy.RequireClaim(ClaimHelper.AccountingClaimType));
                opt.AddPolicy("CommonData", policy => policy.RequireClaim(ClaimHelper.CommonDataClaimType));
                opt.AddPolicy("Contacts", policy => policy.RequireClaim(ClaimHelper.ContactsClaimType));
            });

            services.AddHealthChecks();

            services.AddCommandBus().AddCommandHandlers(typeof(AuthenticateCommandHandlerBase <,>).Assembly);
            services.AddQueryBus().AddQueryHandlers(typeof(AuthenticateCommandHandlerBase <,>).Assembly);
            services.AddEventPublisher();
            services.AddResolvers();
            services.AddDomainLogic();
            services.AddRepositories();
            services.AddBusinessLogicValidators();
            services.AddBusinessLogicHelpers();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IPrincipalResolver, PrincipalResolver>();
            services.AddTransient <ITrustedDomainHelper, TrustedDomainHelper>();
            services.AddTransient <ITokenHelperFactory, TokenHelperFactory>();
            services.AddTransient <ITokenHelper, MicrosoftGraphTokenHelper>();
        }
示例#5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseExceptionHandler("/Home/Error");

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
#pragma warning disable CS0612 // El tipo o el miembro están obsoletos
            app.UseApplicationInsightsRequestTelemetry();
#pragma warning restore CS0612 // El tipo o el miembro están obsoletos

            var logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .Enrich.WithProperty("Environment", env.EnvironmentName)
                         //.WriteTo.RollingFile("log-{Date}.txt")
                         .WriteTo.Seq("http://*****:*****@"c:\shared-auth-ticket-keys\"))
            });
            //app.UseIdentity();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Login}/{action=Index}/{id?}");
            });
        }
示例#6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Log.Information("Configuring Services");

            services.AddMvc();


            services.AddScoped <IFamilyEventReadRepository, FamilyEventReadRepository>();
            services.AddScoped <IWriteRepository <FamilyEvent, Guid>, FamilyEventWriteRepository <FamilyEvent, Guid> >();

            services.AddScoped <IGalleryReadRepository, GalleryReadRepository>();
            services.AddScoped <IWriteRepository <Gallery, Guid>, GalleryWriteRepository <Gallery, Guid> >();

            services.AddScoped <IImageReferenceReadRepository, ImageReferenceReadRepository>();
            services.AddScoped <IWriteRepository <ImageReference, Guid>, ImageReferenceWriteRepository <ImageReference, Guid> >();

            services.AddScoped <IFileService>(context => new S3Service(context.GetRequiredService <IAWSClientFactory>(), "familybryce.gallery"));

            services.AddScoped <IPersonReadRepository, PeopleReadRepository>();
            services.AddScoped <IUnionReadRepository, UnionReadRepository>();
            services.AddScoped <IWriteRepository <Person, int>, PeopleWriteRepository <Person, int> >();
            services.AddScoped <IWriteRepository <Union, Guid>, UnionWriteRepository <Union, Guid> >();

            services.AddScoped <IStoryReadRepository, StoryReadRepository>();
            services.AddScoped <IWriteRepository <StoryContent, Guid>, StoryWriteRepository <StoryContent, Guid> >();

            services.AddSingleton <ISesService, SesService>();

            services.AddSingleton <IAWSClientFactory, AWSClientFactory>();

            services.AddSingleton(context => new DynamoDBOperationConfig()
            {
                TableNamePrefix = "familybryce."
            });

            services.AddSingleton(context => new CDNServiceRoot("https://cdn.brycefamily.net"));

            services.AddScoped <ClanAndPeopleService>();
            services.AddScoped <ContextService>();

            Log.Information("Configuring Identity Management");

            // Identity Management
            services.Configure <DynamoDbSettings>(Configuration.GetSection("DynamoDB"));

            services.AddDynamoDBIdentity <DynamoIdentityUser, DynamoIdentityRole>()
            .AddUserStore()
            .AddRoleStore()
            .AddRoleUsersStore();

            services.Configure <IdentityOptions>(options =>
            {
                options.Lockout.AllowedForNewUsers = true;
                options.Password.RequiredLength    = 8;
                options.Password.RequireUppercase  = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                var dataProtectionPath         = Path.Combine(HostingEnvironment.WebRootPath, "identity-artifacts");
                options.LoginPath              = "/Account/LogIn";
                options.LogoutPath             = "/Account/LogOff";
                options.DataProtectionProvider = DataProtectionProvider.Create(dataProtectionPath);
                options.ExpireTimeSpan         = TimeSpan.FromMinutes(30);
                options.SlidingExpiration      = true;
            }
                                                );

            services.AddAuthentication(options => {
                options.DefaultScheme        = IdentityConstants.ApplicationScheme;
                options.DefaultSignOutScheme = IdentityConstants.ApplicationScheme;
            }).AddCookie(IdentityConstants.ApplicationScheme);


            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddOptions();
            services.AddDataProtection();

            services.TryAddSingleton <IUserValidator <DynamoIdentityUser>, UserValidator <DynamoIdentityUser> >();
            services.TryAddSingleton <IPasswordValidator <DynamoIdentityUser>, PasswordValidator <DynamoIdentityUser> >();
            services.TryAddSingleton <IPasswordHasher <DynamoIdentityUser>, BCryptPasswordHasher <DynamoIdentityUser> >();
            services.TryAddSingleton <ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddSingleton <IdentityErrorDescriber>();
            services.TryAddSingleton <ISecurityStampValidator, SecurityStampValidator <DynamoIdentityUser> >();
            services
            .TryAddSingleton <IUserClaimsPrincipalFactory <DynamoIdentityUser>, Infrastructure.Authentication.UserClaimsPrincipalFactory <DynamoIdentityUser> >();
            services.TryAddSingleton <UserManager <DynamoIdentityUser>, UserManager <DynamoIdentityUser> >();
            services.TryAddScoped <SignInManager <DynamoIdentityUser>, SignInManager <DynamoIdentityUser> >();


            AddDefaultTokenProviders(services);


            services.AddMemoryCache();
        }
示例#7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory)
        {
            loggerFactory.AddSerilog();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.ApplicationServices.GetService <Data.Context>().Migrate();

            app.UseResponseCompression();

            // configure static files with 7 day cache
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = _ =>
                {
                    var headers          = _.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromDays(7)
                    };
                }
            });

            string contentPath = null;

            if (!string.IsNullOrEmpty(Configuration[ConfigurationKey.ContentDirectory]))
            {
                contentPath = Configuration[ConfigurationKey.ContentDirectory];
            }
            else
            {
                contentPath = Path.Combine(Directory.GetCurrentDirectory(), "content");
            }

            if (!Directory.Exists(contentPath))
            {
                try
                {
                    Directory.CreateDirectory(contentPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to create directory '{contentPath}' in {Directory.GetCurrentDirectory()}");
                    throw (ex);
                }
            }

            string pathString = null;

            if (!string.IsNullOrEmpty(Configuration[ConfigurationKey.ContentPath]))
            {
                pathString = "/" + Configuration[ConfigurationKey.ContentPath];
            }
            else
            {
                pathString = "/content";
            }

            // configure /content with 7 day cache
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider      = new PhysicalFileProvider(contentPath),
                RequestPath       = new PathString(pathString),
                OnPrepareResponse = _ =>
                {
                    var headers          = _.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromDays(7)
                    };
                }
            });

            app.UseSession();

            // set cookie authentication options
            var cookieAuthOptions = new CookieAuthenticationOptions
            {
                AuthenticationScheme  = Controllers.Authentication.SchemeGRACookie,
                LoginPath             = new PathString("/SignIn/"),
                AccessDeniedPath      = new PathString("/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true
            };

            // if there's a data protection path, set it up - for clustered/multi-server configs
            if (!string.IsNullOrEmpty(Configuration[ConfigurationKey.DataProtectionPath]))
            {
                cookieAuthOptions.DataProtectionProvider = DataProtectionProvider.Create(
                    new DirectoryInfo(Configuration[ConfigurationKey.DataProtectionPath]));
            }

            app.UseCookieAuthentication(cookieAuthOptions);

            // sitePath is also referenced in GRA.Controllers.Filter.SiteFilter
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: null,
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: null,
                    template: "{sitePath}/Info/{stub}",
                    defaults: new { controller = "Info", action = "Index" },
                    constraints: new
                {
                    sitePath = new SiteRouteConstraint(app.ApplicationServices.GetRequiredService <Controllers.Base.ISitePathValidator>())
                });
                routes.MapRoute(
                    name: null,
                    template: "Info/{stub}",
                    defaults: new { controller = "Info", action = "Index" });

                routes.MapRoute(
                    name: null,
                    template: "{sitePath}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new
                {
                    sitePath = new SiteRouteConstraint(app.ApplicationServices.GetRequiredService <Controllers.Base.ISitePathValidator>())
                });
                routes.MapRoute(
                    name: null,
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
示例#8
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new ULearnUserManager(new ULearnDb()));

            var configuration = ApplicationConfiguration.Read <WebApiConfiguration>();

            // Enable the application to use a cookie to store information for the signed in user
            var cookieKeyRingDirectoy = new DirectoryInfo(Path.Combine(Utils.GetAppPath(), configuration.Web.CookieKeyRingDirectory));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Identity.Application",
                CookieName         = configuration.Web.CookieName,
                CookieDomain       = configuration.Web.CookieDomain,

                LoginPath = new PathString("/Login"),
                Provider  = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ULearnUserManager, ApplicationUser, string>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: identity => identity.GetUserId()
                        )
                },

                /* Configure sharing cookies between application.
                 * See https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?tabs=aspnetcore2x for details */
                TicketDataFormat = new AspNetTicketDataFormat(
                    new DataProtectorShim(
                        DataProtectionProvider.Create(cookieKeyRingDirectoy, builder => builder.SetApplicationName("ulearn"))
                        .CreateProtector(
                            "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                            "Identity.Application",
                            // DefaultAuthenticationTypes.ApplicationCookie,
                            "v2"))),
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //	clientId: "",
            //	clientSecret: "");

            //app.UseTwitterAuthentication(
            //	consumerKey: "hC6XpJy0OPVkbvGzRIOJRA",
            //	  consumerSecret: "cEDewTtU7RKHimj2D1IpD75HUKnjVeobdSNhjAAQ");

            var vkAppId     = WebConfigurationManager.AppSettings["owin.vk.appId"];
            var vkAppSecret = WebConfigurationManager.AppSettings["owin.vk.appSecret"];

            app.UseVkAuthentication(vkAppId, vkAppSecret);
            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            var konturPassportClientId     = WebConfigurationManager.AppSettings["owin.konturPassport.clientId"];
            var konturPassportClientSecret = WebConfigurationManager.AppSettings["owin.konturPassport.clientSecret"];

            if (!string.IsNullOrEmpty(konturPassportClientSecret))
            {
                app.UseKonturPassportAuthentication(konturPassportClientId, konturPassportClientSecret);
            }

            //app.UseGoogleAuthentication();
            app.UseLtiAuthentication();
        }