Ejemplo n.º 1
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions
            {
                ConnectionStringName = _connectionStringHandler.Commerce.Name
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider.
            // Configure the sign in cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Apps/Shell/Pages/Login.aspx"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect = (context => context.Response.Redirect(context.RedirectUri))
                }
            });
        }
Ejemplo n.º 2
0
        public void Configuration(IAppBuilder app)
        {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <ApplicationUser>();

            // Remove to block registration of administrators
            app.UseAdministratorRegistrationPage(() => HttpContext.Current.Request.IsLocal);

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(Global.LoginPath),
                Provider           = new CookieAuthenticationProvider
                {
                    // If the "/util/login.aspx" has been used for login otherwise you don't need it you can remove OnApplyRedirect.
                    OnApplyRedirect = cookieApplyRedirectContext =>
                    {
                        app.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get <ApplicationSignInManager <ApplicationUser> >());
                    },

                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });
        }
Ejemplo n.º 3
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <ApplicationUser>(new ApplicationOptions()
            {
                ConnectionStringName = "EPiServerDB"
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider.
            // Configure the sign in cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/util/login.aspx"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect = (context =>
                    {
                        if (!IsContentApiRequest(context.Request.Uri))
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                    }),
                    OnResponseSignOut = (context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))),
                },
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
Ejemplo n.º 4
0
        public void Configuration(IAppBuilder app)
        {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <ApplicationUser>();

            // Remove to block registration of administrators
            app.UseSetupAdminAndUsersPage(() => HttpContext.Current.Request.IsLocal);

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(Global.LoginPath),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });

            app.MapSignalR();
        }
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions
            {
                ConnectionStringName = _connectionStringHandler.Commerce.Name
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider.
            // Configure the sign in cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect   = context => context.Response.Redirect(context.RedirectUri),
                    OnResponseSignOut = context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))
                }
            });

            //REGISTER VSF AUTH
            app.RegisterVueStorefrontAuth(ConfigurationManager.GetSection("vsf.apiBridge") as VsfApiBridgeConfiguration);

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

#if GOOGLE_ACCOUNT_LOGIN_FEATURE
            EnableGoogleAccountLogin(app);
#endif

#if FACEBOOK_ACCOUNT_LOGIN_FEATURE
            EnableFacebookAccountLogin(app);
#endif

#if TWITTER_ACCOUNT_LOGIN_FEATURE
            EnableTwitterAccountLogin(app);
#endif

#if MICROSOFT_ACCOUNT_LOGIN_FEATURE
            EnableMicrosoftAccountLogin(app);
#endif
        }
        public void Configuration(IAppBuilder app)
        {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <ApplicationUser>();

            // Remove to block registration of administrators
            app.UseAdministratorRegistrationPage(() => HttpContext.Current.Request.IsLocal);

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(Global.LoginPath),
                Provider           = new CookieAuthenticationProvider
                {
                    // If the "/util/login.aspx" has been used for login otherwise you don't need it you can remove OnApplyRedirect.
                    OnApplyRedirect = cookieApplyRedirectContext =>
                    {
                        app.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get <ApplicationSignInManager <ApplicationUser> >());
                    },

                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });

            // Configure the use of Bearer Tokens
            // Do not set the token expiry too high, as when editing user roles we don't have revoke mechanism
            app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(6),
                Provider = new WebApiAuthorizationServerProvider()
            });

            // Configure Web API
            HttpConfiguration config = new HttpConfiguration();

            // Enable CORS
            config.EnableCors();
            // Map Attribute Routes
            config.MapHttpAttributeRoutes();
            // Remove XmlFormatter
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            // Ignore reference loops
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            // Apply Web API configuration for self-host.
            app.UseWebApi(config);
        }
Ejemplo n.º 7
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <ApplicationUser>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/util/login.aspx"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>,
                                                                                    ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });
        }
Ejemplo n.º 8
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions
            {
                ConnectionStringName = _connectionStringHandler.Commerce.Name
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider.
            // Configure the sign in cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect   = (context => context.Response.Redirect(context.RedirectUri)),
                    OnResponseSignOut = (context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage)))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // To enable using an external provider like Facebook or Google, uncomment the options you want to make available.
            // Also remember to apply the correct client id and secret code to each method that you call below.
            // Uncomment the external login providers you want to enable in your site. Don't forget to change their respective client id and secret.

            //EnableMicrosoftAccountLogin(app);
            //EnableTwitterAccountLogin(app);
            //EnableFacebookAccountLogin(app);
            //EnableGoogleAccountLogin(app);
        }
Ejemplo n.º 9
0
        public virtual void Configuration(IAppBuilder applicationBuilder)
        {
            applicationBuilder.AddCmsAspNetIdentity <ApplicationUser>();

            applicationBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Util/Login.aspx"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = cookieApplyRedirectContext => { applicationBuilder.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get <ApplicationSignInManager <ApplicationUser> >()); },

                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        TimeSpan.FromMinutes(30),
                        (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });
        }
Ejemplo n.º 10
0
        public void Configuration(IAppBuilder app)
        {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <SiteUser>();

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(Global.LoginPath),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });
        }
Ejemplo n.º 11
0
        public void Configuration(IAppBuilder app)
        {
            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <ApplicationUser>();

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/util/login.aspx"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
                }
            });
        }
Ejemplo n.º 12
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions
            {
                ConnectionStringName = _connectionStringHandler.Commerce.Name
            });

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider.
            // Configure the sign in cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect   = context => context.Response.Redirect(context.RedirectUri),
                    OnResponseSignOut = context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.UseServiceApiIdentityTokenAuthorization <ApplicationUserManager <SiteUser>, SiteUser>();
        }
Ejemplo n.º 13
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions()
            {
                ConnectionStringName = "AspNetIdentity"
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Util/Login.aspx"),
                Provider           = new CookieAuthenticationProvider()
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect  = context => context.Response.Redirect(context.RedirectUri),
                    OnResponseSignIn = context =>
                                       context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))
                }
            });
        }
Ejemplo n.º 14
0
        public void Configuration(IAppBuilder app)
        {
            app.AddCmsAspNetIdentity <SiteUser>(new ApplicationOptions
            {
                ConnectionStringName = _connectionStringHandler.Commerce.Name
            });

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                CookieName         = ".AspNet." + DefaultAuthenticationTypes.ExternalCookie,
                ExpireTimeSpan     = TimeSpan.FromMinutes(5)
            });

            // <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];

            // <add key="ida:ClientId" value="Client ID from Azure AD application" />
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];

            // <add key="ida:Tenant" value="Azure Active Directory, Directory Eg. Contoso.onmicrosoft.com/" />
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];

            //<add key="ida:PostLogoutRedirectUri" value="https://the logout post uri/" />
            string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            const string LogoutPath = "/Login/SignOut";

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = authority,
                RedirectUri           = ConfigurationManager.AppSettings["ida:RedirectUri"],
                PostLogoutRedirectUri = postLogoutRedirectUri,
                Scope        = OpenIdConnectScopes.OpenIdProfile,
                ResponseType = OpenIdConnectResponseTypes.IdToken,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    RoleClaimType  = ClaimTypes.Role
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Write(context.Exception.Message);
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = context =>
                    {
                        // Here you can change the return uri based on multisite
                        HandleMultiSiteReturnUrl(context);

                        // To avoid a redirect loop to the federation server send 403
                        // when user is authenticated but does not have access
                        if (context.OwinContext.Response.StatusCode == 401 &&
                            context.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            context.OwinContext.Response.StatusCode = 403;
                            context.HandleResponse();
                        }
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = context =>
                    {
                        var redirectUri = new Uri(context.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
                        if (redirectUri.IsAbsoluteUri)
                        {
                            context.AuthenticationTicket.Properties.RedirectUri = redirectUri.PathAndQuery;
                        }
                        //Sync user and the roles to EPiServer in the background
                        ServiceLocator.Current.GetInstance <ISynchronizingUserService>().
                        SynchronizeAsync(context.AuthenticationTicket.Identity);
                        return(Task.FromResult(0));
                    }
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager <SiteUser>, SiteUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
                    OnApplyRedirect   = context => context.Response.Redirect(context.RedirectUri),
                    OnResponseSignOut = context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))
                }
            });

            app.UseStageMarker(PipelineStage.Authenticate);
            app.Map(LogoutPath, map =>
            {
                map.Run(ctx =>
                {
                    if (OpenIdConnectUser(ctx.Authentication.User))
                    {
                        ctx.Authentication.SignOut();
                    }
                    else
                    {
                        ctx.Get <ApplicationSignInManager <SiteUser> >().SignOut();
                    }
                    return(Task.FromResult(0));
                });
            });

            // If the application throws an antiforgerytoken exception like “AntiForgeryToken: A Claim of Type NameIdentifier or IdentityProvider Was Not Present on Provided ClaimsIdentity”,
            // set AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier.
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
Ejemplo n.º 15
0
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = aadAuthority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                ResponseType          = OpenIdConnectResponseType.CodeIdToken,

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    RoleClaimType  = ClaimTypes.Role
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        string[] scopes       = "User.Read User.ReadBasic.All".Split(new char[] { ' ' });

                        TokenCache userTokenCache = new SessionTokenCache(signedInUserID, MemoryCache.Default);
                        var credential            = new ClientCredential(clientId, ClientSecret);

                        AuthenticationContext authContext = new AuthenticationContext(aadAuthority);
                        AuthenticationResult result       = authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(postLogoutRedirectUri), credential, "https://graph.microsoft.com/").Result;
                        ACCESS_TOKEN = result.AccessToken;
                    },
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Write(context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });



            app.UseStageMarker(PipelineStage.Authenticate);
            app.Map(LogoutPath, map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return(Task.FromResult(0));
                });
            });



            // Add CMS integration for ASP.NET Identity
            app.AddCmsAspNetIdentity <ApplicationUser>();

            // Remove to block registration of administrators
            app.UseSetupAdminAndUsersPage(() => HttpContext.Current.Request.IsLocal);

            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = "Application",
            //    LoginPath = new PathString("/Login"),
            //    LogoutPath = new PathString("/Logout")
            //});
            //app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
            //});



            /*
             * // Use cookie authentication
             * app.UseCookieAuthentication(new CookieAuthenticationOptions
             * {
             *  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
             *  LoginPath = new PathString(Global.LoginPath),
             *  Provider = new CookieAuthenticationProvider
             *  {
             *      // If the "/util/login.aspx" has been used for login otherwise you don't need it you can remove OnApplyRedirect.
             *      OnApplyRedirect = cookieApplyRedirectContext =>
             *      {
             *          app.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get<ApplicationSignInManager<ApplicationUser>>());
             *      },
             *
             *      // Enables the application to validate the security stamp when the user logs in.
             *      // This is a security feature which is used when you change a password or add an external login to your account.
             *      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<ApplicationUser>, ApplicationUser>(
             *          validateInterval: TimeSpan.FromMinutes(30),
             *          regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
             *  }
             * });*/
        }