예제 #1
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(Kronika106DBContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // 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

            var provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                OnResponseSignIn = (context) =>
                {
                    // context.Properties.IsPersistent = true;
                    context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddHours(5000);
                }
            };



            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = provider
            });
        }
예제 #2
0
        public void SetCookieAuthenticationProvider(ref IAppBuilder app, CookieAuthenticationProvider provider)
        {
            // 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
            var cookieAuthenticationOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = provider
            };

            // 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(cookieAuthenticationOptions);
            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);
        }
예제 #3
0
        private void ConfigureAuth(IAppBuilder app)
        {
            var provider = new CookieAuthenticationProvider
            {
                OnApplyRedirect = ctx =>
                {
                    if (!IsApiRequest(ctx.Request) && !ctx.Request.Headers.ContainsKey("X-Requested-With"))
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                }
            };

            var loginUrl = "/Account/Login"; //VirtualPathUtility.ToAbsolute("~/Account/Login");

            BaseViewPage.LoginUrl = loginUrl;
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ExpireTimeSpan     = TimeSpan.FromDays(14),
                LoginPath          = new PathString(loginUrl),
                Provider           = provider,
                SessionStore       = new SessionStoreMediator()
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
예제 #4
0
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the Db Context, user manager and role
        // manager to use a single instance per request

        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

        // 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 loggin in with a third party login provider
        // Configure the sign in cookie

        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath          = new PathString("/Account/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, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user)
                    => user.GenerateUserIdentityAsync(manager))
            }
        });
예제 #5
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);

            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            var originalHandler = provider.OnApplyRedirect;

            //Our logic to dynamically modify the path (maybe needs some fine tuning)
            provider.OnApplyRedirect = context =>
            {
                var mvcContext = new HttpContextWrapper(HttpContext.Current);
                var routeData  = RouteTable.Routes.GetRouteData(mvcContext);

                //Get the current language
                RouteValueDictionary routeValues = new RouteValueDictionary();
                routeValues.Add("lang", routeData.Values["lang"]);

                //Reuse the RetrunUrl
                Uri    uri       = new Uri(context.RedirectUri);
                string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);

                //Overwrite the redirection uri
                context.RedirectUri = url.Action("logon", "account", routeValues);
                originalHandler.Invoke(context);
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Logon"),
                Provider           = provider
            });
        }
예제 #6
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    var task = Task.Run(async() => {
                        await AuthInit(ctx);
                    });
                    task.Wait();
                },
                OnValidateIdentity = ctx =>
                {
                    //good spot to troubleshoot nonces, etc...
                    return(Task.FromResult(0));
                }
            };

            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider,
                //may help with redirect loops
                CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
            };

            app.UseCookieAuthentication(cookieOptions);

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType    = CustomAuthType.LabAdmin,
                ClientId              = Settings.LabAdminClientId,
                Authority             = Settings.AdminAuthority,
                PostLogoutRedirectUri = "/",
                Notifications         = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed      = AuthFailed,
                    AuthorizationCodeReceived = async(context) =>
                    {
                        //used if you want to cache the access token for api calls
                        await OnAuthorizationCodeReceived(context);
                        await AuthInit(context);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + "/";
                        context.ProtocolMessage.RedirectUri           = appBaseUrl;
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                }
            });
        }
예제 #7
0
        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            //app.CreatePerOwinContext(CreateKernel);
            //app.UseNinjectMiddleware(CreateKernel);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            var originalHandler = provider.OnApplyRedirect;

            provider.OnApplyRedirect = context =>
            {
                //insert your logic here to generate the redirection URI
                string NewURI = "....";
                //Overwrite the redirection uri
                context.RedirectUri = NewURI;
                originalHandler.Invoke(context);
            };

            // 使应用程序可以使用 Cookie 来存储已登录用户的信息
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                CookieHttpOnly     = true,

                Provider = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = context =>
                    {
                        File.WriteAllText("C:\\1.txt", DateTime.Now.ToString());
                        context.Response.Redirect(context.RedirectUri);
                    }
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 取消注释以下行可允许使用第三方登录提供程序登录
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

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

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

            //app.UseGoogleAuthentication();
        }
예제 #8
0
        private static void ConfigureAuthentication(IAppBuilder app)
        {
            //Register filters for authentication
            RegisterFilters(GlobalFilters.Filters);

            //Create cookie authentication provider
            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();
            var originalHandler = provider.OnApplyRedirect;
            var commonLoginUrl  = WebConfigurationManager.AppSettings["CommonLoginUrl"];

            if (commonLoginUrl != null)
            {
                provider.OnApplyRedirect = context =>
                {
                    var redirectUri = commonLoginUrl + "/Account/Login" + new QueryString(context.Options.ReturnUrlParameter, context.Request.Uri.AbsoluteUri);
                    context.RedirectUri = redirectUri;
                    originalHandler.Invoke(context);
                };
            }

            //Authentication cookie expiry timespan
            double cookieExpiryHours;

            if (!double.TryParse(WebConfigurationManager.AppSettings["CookieExpiryHours"], out cookieExpiryHours))
            {
                cookieExpiryHours = DefaultCookieExpiryHours;
            }

            //Authentication cookie domain
            var cookieDomain = WebConfigurationManager.AppSettings["CookieDomain"];

            if (string.IsNullOrEmpty(cookieDomain))
            {
                throw new ArgumentException("No cookie domain was specified. Unable to proceed with authentication configuration.");
            }

            //Setup the application to use cookie authentication, information for the signed in user is stored in the cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                CookieSecure       = CookieSecureOption.Always,
                SlidingExpiration  = false,
                CookieName         = "CommonLoginPage",
                ExpireTimeSpan     = TimeSpan.FromHours(cookieExpiryHours),
                CookieDomain       = cookieDomain,
                Provider           = provider
            });

            //Set the anti-forgery claim type
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
예제 #9
0
        /// <summary>
        /// Cookie auth provider that adds extra role claims on the identity
        /// Role claims are kept in cache and added on the identity on every request
        /// </summary>
        /// <returns></returns>
        private static CookieAuthenticationProvider GetMyCookieAuthenticationProvider()
        {
            var cookieAuthenticationProvider = new CookieAuthenticationProvider();

            cookieAuthenticationProvider.OnValidateIdentity = async context =>
            {
                var cookieValidatorFunc = SecurityStampValidator.OnValidateIdentity <UserManager, ApplicationUser>(
                    TimeSpan.FromMinutes(10),
                    (manager, user) =>
                {
                    var identity = manager.GenerateUserIdentityAsync(user);
                    return(identity);
                });
                await cookieValidatorFunc.Invoke(context);

                if (context.Identity == null || !context.Identity.IsAuthenticated)
                {
                    return;
                }

                // get list of roles on the user
                var userRoles = context.Identity
                                .Claims
                                .Where(c => c.Type == ClaimTypes.Role)
                                .Select(c => c.Value)
                                .ToList();

                foreach (var roleName in userRoles)
                {
                    var cacheKey     = ApplicationRole.GetCacheKey(roleName);
                    var cachedClaims = System.Web.HttpContext.Current.Cache[cacheKey] as IEnumerable <Claim>;
                    if (cachedClaims == null)
                    {
                        var roleManager = DependencyResolver.Current.GetService <RoleManager>();
                        cachedClaims = await roleManager.GetClaimsAsync(roleName);

                        System.Web.HttpContext.Current.Cache[cacheKey] = cachedClaims;
                    }
                    context.Identity.AddClaims(cachedClaims);
                }
            };
            cookieAuthenticationProvider.OnApplyRedirect = ctx =>
            {
                if (!IsApiRequest(ctx.Request))
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }
            };
            return(cookieAuthenticationProvider);
        }
예제 #10
0
        private static CookieAuthenticationProvider getProvide()
        {
            CookieAuthenticationProvider provider = new CookieAuthenticationProvider()
            {
            };
            var originalHandler = provider.OnApplyRedirect;

            //Our logic to dynamically modify the path (maybe needs some fine tuning)
            provider.OnApplyRedirect = context =>
            {
                UrlHelper            urlHelper   = new UrlHelper(HttpContext.Current.Request.RequestContext);
                var                  mvcContext  = new HttpContextWrapper(HttpContext.Current);
                RouteData            routeData   = RouteTable.Routes.GetRouteData(mvcContext);
                RouteValueDictionary routeValues = new RouteValueDictionary();

                if (!(routeData.Values["controller"].ToString() == "Account" && routeData.Values["action"].ToString() == "Login"))
                {
                    //Get the current language
                    routeValues.Add("lang", routeData.Values["lang"]);

                    //Reuse the RetrunUrl
                    Uri    uri       = new Uri(context.RedirectUri);
                    string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                    routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);

                    if (routeData.DataTokens["area"] != null && routeData.DataTokens["area"].ToString() != null)
                    {
                        string areaName = routeData.DataTokens["area"].ToString();

                        if (areaName == "Manager")
                        {
                            areaName = null;
                        }
                        else if (areaName == "Mobile")
                        {
                            routeValues.Add("provider", "Weixin");
                            context.RedirectUri = urlHelper.Action("ExternalLogin", "Account", routeValues);
                            originalHandler.Invoke(context);
                            return;
                        }
                        routeValues.Add("area", areaName);
                    }

                    //Overwrite the redirection uri
                    context.RedirectUri = urlHelper.Action("Login", "Account", routeValues);
                }
                originalHandler.Invoke(context);
            };
            return(provider);
        }
예제 #11
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            #region Sql Server
            //ConfigureSqlServerContext(ref app);
            //CookieAuthenticationProvider cookieAuthenticationProvider = GetSqlServerCookieAuthenticationProvider();
            #endregion

            #region MongoDb
            ConfigureMongoDbContext(ref app);
            CookieAuthenticationProvider cookieAuthenticationProvider = GetMongoDbCookieAuthenticationProvider();
            #endregion

            SetCookieAuthenticationProvider(ref app, cookieAuthenticationProvider);
            SetSocialLogins(ref app);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    //ctx.Identity = StartupAuth.InitAuth(ctx);
                }
            };
            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider
            };

            app.UseCookieAuthentication(cookieOptions);

            // Required for AAD
            OpenIdConnectAuthenticationOptions Options = new OpenIdConnectAuthenticationOptions
            {
                Authority = string.Format(aadInstance, tenant),
                ClientId  = clientId,
                //ProtocolValidator = new OpenIdConnectProtocolValidator
                //{
                //    RequireNonce = false
                //},
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = string.Format("{0}://{1}{2}", context.Request.Scheme, context.Request.Host, context.Request.PathBase);
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + "/Account/SignedOut";
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = CustomAuthTypes.B2E,
            };

            app.UseOpenIdConnectAuthentication(Options);
        }
 public AutenticadorCookieAuthenticationOptions()
 {
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
     LoginPath          = ConfigCustomAutenticadorCookieAuthentication.LoginPath;
     CookieHttpOnly     = true;
     CookieName         = ConfigCustomAutenticadorCookieAuthentication.CookieName;
     CookiePath         = ConfigCustomAutenticadorCookieAuthentication.CookiePath;
     SlidingExpiration  = ConfigCustomAutenticadorCookieAuthentication.SlidingExpiration;
     ExpireTimeSpan     = ConfigCustomAutenticadorCookieAuthentication.ExpireTimeSpan;
     CookieSecure       = CookieSecureOption.SameAsRequest;
     ReturnUrlParameter = ConfigCustomAutenticadorCookieAuthentication.ReturnUrlParameter;
     CookieDomain       = ConfigCustomAutenticadorCookieAuthentication.CookieDomain;
     Provider           = new CookieAuthenticationProvider
     {
         OnApplyRedirect = ApplyRedirect
     };
 }
예제 #14
0
        public void ConfigureAuth(IAppBuilder app)
        {
            UrlHelper _url      = new UrlHelper(HttpContext.Current.Request.RequestContext);
            string    actionUri = _url.Action("Index", "Login", new { area = "Common" });

            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            // need to add UserManager into owin, because this is used in cookie invalidation
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = EnscoAuthentication.ApplicationCookie,
                LoginPath          = new PathString(actionUri),
                Provider           = provider,
                CookieName         = "EnscoAuthCookieName",
                CookieHttpOnly     = true,
                SlidingExpiration  = true,
                ExpireTimeSpan     = TimeSpan.FromHours(0.5), // adjust to your needs
            });
        }
예제 #15
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            var provider        = new CookieAuthenticationProvider();
            var originalHandler = provider.OnApplyRedirect;

            provider.OnApplyRedirect = context =>
            {
                if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api")))
                {
                    context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery;
                    originalHandler.Invoke(context);
                }
            };
            provider.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)
                );
            // 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("/Account/Login"),
                Provider           = provider
            });
            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(1));

            // 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);
        }
예제 #16
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/"),
                CookieName         = "authentication",
                SlidingExpiration  = true,
                ExpireTimeSpan     = new TimeSpan(30, 0, 0, 0),
                Provider           = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = context =>
                    {
                        context.Response.StatusCode = 401;
                    }
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);


            var cookieProvider = new CookieAuthenticationProvider
            {
                // ... Options from your existing application
            };
            // Modify redirect behaviour to convert login URL to relative
            var applyRedirect = cookieProvider.OnApplyRedirect;

            cookieProvider.OnApplyRedirect = context =>
            {
                if (context.RedirectUri.StartsWith("http://" + context.Request.Host))
                {
                    context.RedirectUri = context.RedirectUri.Substring(
                        context.RedirectUri.IndexOf('/', "http://".Length));
                }
                applyRedirect(context);
            };



            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = cookieProvider
            });

            // MAKE SURE PROVIDERS KEYS ARE SET IN the CodePasteKeys.json FILE
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;


            //Setup SignalR
            app.MapSignalR();
        }
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

        var url             = new UrlHelper(HttpContext.Current.Request.RequestContext);
        var provider        = new CookieAuthenticationProvider();
        var originalHandler = provider.OnApplyRedirect;

        provider.OnApplyRedirect = context =>
        {
            var routeValues = new RouteValueDictionary();
            var uri         = new Uri(context.RedirectUri);
            var returnUrl   = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
            routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);
            context.RedirectUri = url.Action("Login", "Account", routeValues);
            originalHandler.Invoke(context);
        };
        provider.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager));


        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath          = new PathString("/Account/Login"),
            Provider           = provider,
            SlidingExpiration  = true,
            ExpireTimeSpan     = TimeSpan.FromMinutes(30)
        });
        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));
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    }
예제 #19
0
        public void ConfigureAuth(IAppBuilder app)
        {
            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            var originalHandler = provider.OnApplyRedirect;

            //Our logic to dynamically modify the path (maybe needs some fine tuning)
            provider.OnApplyRedirect = context =>
            {
                var mvcContext = new HttpContextWrapper(HttpContext.Current);
                var routeData  = RouteTable.Routes.GetRouteData(mvcContext);

                //Get the current language
                RouteValueDictionary routeValues = new RouteValueDictionary();


                //Reuse the RetrunUrl
                Uri    uri       = new Uri(context.RedirectUri);
                string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);
                originalHandler.Invoke(context);
            };

            var expiredTime = DateTime.Now.AddYears(1).ToLocalTime();

            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // 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

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                ExpireTimeSpan = expiredTime - DateTime.Now,
                Provider       = provider
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
예제 #20
0
        public void ConfigureAuth(IAppBuilder app)
        {
            AppBuilderExtensions.CreatePerOwinContext <ApplicationDbContext>(app, (Func <M0>) new Func <ApplicationDbContext>(ApplicationDbContext.Create));
            AppBuilderExtensions.CreatePerOwinContext <ApplicationUserManager>(app, (Func <IdentityFactoryOptions <M0>, IOwinContext, M0>) new Func <IdentityFactoryOptions <ApplicationUserManager>, IOwinContext, ApplicationUserManager>(ApplicationUserManager.Create));
            AppBuilderExtensions.CreatePerOwinContext <ApplicationSignInManager>(app, (Func <IdentityFactoryOptions <M0>, IOwinContext, M0>) new Func <IdentityFactoryOptions <ApplicationSignInManager>, IOwinContext, ApplicationSignInManager>(ApplicationSignInManager.Create));
            IAppBuilder iappBuilder = app;
            CookieAuthenticationOptions authenticationOptions1 = new CookieAuthenticationOptions();

            ((AuthenticationOptions)authenticationOptions1).set_AuthenticationType("ApplicationCookie");
            authenticationOptions1.set_LoginPath(new PathString("/Account/Login"));
            CookieAuthenticationOptions  authenticationOptions2  = authenticationOptions1;
            CookieAuthenticationProvider authenticationProvider1 = new CookieAuthenticationProvider();

            authenticationProvider1.set_OnValidateIdentity(SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(TimeSpan.FromMinutes(30.0), (Func <M0, M1, Task <ClaimsIdentity> >)((manager, user) => user.GenerateUserIdentityAsync((UserManager <ApplicationUser>)manager))));
            CookieAuthenticationProvider authenticationProvider2 = authenticationProvider1;

            authenticationOptions2.set_Provider((ICookieAuthenticationProvider)authenticationProvider2);
            CookieAuthenticationOptions authenticationOptions3 = authenticationOptions1;

            CookieAuthenticationExtensions.UseCookieAuthentication(iappBuilder, authenticationOptions3);
            AppBuilderExtensions.UseExternalSignInCookie(app, "ExternalCookie");
            AppBuilderExtensions.UseTwoFactorSignInCookie(app, "TwoFactorCookie", TimeSpan.FromMinutes(5.0));
            AppBuilderExtensions.UseTwoFactorRememberBrowserCookie(app, "TwoFactorRememberBrowser");
        }
예제 #21
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Provider to avoid api redirection
            var provider        = new CookieAuthenticationProvider();
            var originalHandler = provider.OnApplyRedirect;

            provider.OnApplyRedirect = context =>
            {
                if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api")))
                {
                    context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery;
                    originalHandler.Invoke(context);
                }
            };

            // Options
            var options = new CookieAuthenticationOptions
            {
                LoginPath = new PathString("/Account/Login"),
                Provider  = provider
            };

            // Add options
            app.UseCookieAuthentication(options);

            // Set default authentitationtype
            app.SetDefaultSignInAsAuthenticationType(options.AuthenticationType);

            //// Basic
            //app.UseBasicAuthentication(new BasicAuthenticationOptions(
            //    "AtomPub",
            //    BasicAuthentication));

            // Add Microsoft Account Authentication
            if (Settings.Current.MicrosoftAccountAuthentication)
            {
                String id     = ConfigurationManager.AppSettings["MicrosoftAccountAuthenticationClientId"];
                String secret = ConfigurationManager.AppSettings["MicrosoftAccountAuthenticationSecret"];

                if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(secret))
                {
                    app.UseMicrosoftAccountAuthentication(id, secret);
                }
            }

            // Add Twitter Authentication
            if (Settings.Current.TwitterAuthentication)
            {
                String id     = ConfigurationManager.AppSettings["TwitterAuthenticationClientId"];
                String secret = ConfigurationManager.AppSettings["TwitterAuthenticationSecret"];

                if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(secret))
                {
                    app.UseTwitterAuthentication(id, secret);
                }
            }

            // Add FaceBook Authentication
            if (Settings.Current.FacebookAuthentication)
            {
                String id     = ConfigurationManager.AppSettings["FacebookAuthenticationClientId"];
                String secret = ConfigurationManager.AppSettings["FacebookAuthenticationSecret"];

                if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(secret))
                {
                    app.UseFacebookAuthentication(id, secret);
                }
            }

            // Add Google Plus Authentication
            if (Settings.Current.GoogleAuthentication)
            {
                String id     = ConfigurationManager.AppSettings["GoogleAuthenticationClientId"];
                String secret = ConfigurationManager.AppSettings["GoogleAuthenticationSecret"];

                if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(secret))
                {
                    app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
                    {
                        ClientId     = id,
                        ClientSecret = secret
                    });
                }
            }
        }
예제 #22
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            //app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);

            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();

            var originalHandler = provider.OnApplyRedirect;

            //Our logic to dynamically modify the path (maybe needs some fine tuning)
            provider.OnApplyRedirect = context =>
            {
                var mvcContext = new HttpContextWrapper(HttpContext.Current);
                var routeData  = RouteTable.Routes.GetRouteData(mvcContext);

                //Get the current language
                RouteValueDictionary routeValues = new RouteValueDictionary();
                routeValues.Add("lang", routeData.Values["lang"]);

                //Reuse the RetrunUrl
                Uri    uri       = new Uri(context.RedirectUri);
                string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);

                //Overwrite the redirection uri
                context.RedirectUri = url.Action("login", "account", routeValues);
                originalHandler.Invoke(context);
            };

            // 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("/Account/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, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            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);

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

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
예제 #23
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    ctx.Identity = StartupAuth.InitAuth(ctx);
                }
            };
            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider
            };

            app.UseCookieAuthentication(cookieOptions);

            // Required for AAD B2C
            // Configure OpenID Connect middleware for each policy
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SusiPolicyId));
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ResetPolicyId));

            // Required for AAD Multitenant
            OpenIdConnectAuthenticationOptions multiOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = aadInstanceMulti,
                ClientId      = clientIdB2B,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = WutAuthTypes.B2EMulti,
            };

            app.UseOpenIdConnectAuthentication(multiOptions);

            // Required for AAD B2B
            OpenIdConnectAuthenticationOptions b2bOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = string.Format(aadInstanceB2B, tenantB2B),
                ClientId      = clientIdB2B,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = WutAuthTypes.B2B,
            };

            app.UseOpenIdConnectAuthentication(b2bOptions);
        }
예제 #24
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    StartupAuth.InitAuth(ctx);
                }
            };

            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider
            };

            app.UseCookieAuthentication(cookieOptions);

            // Required for AAD Multitenant (Pre-auth access to home tenant during sign-up)
            OpenIdConnectAuthenticationOptions multiOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = aadInstanceMulti,
                ClientId      = clientId_preAuth,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = OnAuthenticationFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        var issuer = "";
                        if (context.Request.QueryString.HasValue)
                        {
                            var user = HttpUtility.ParseQueryString(context.Request.QueryString.Value)["user"];
                            if (user.Length > 0)
                            {
                                var domain = user.Split('@')[1];
                                issuer = string.Format(aadInstanceLocal + "/oauth2/authorize?login_hint={1}", domain, user);
                            }
                        }

                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        if (issuer != "")
                        {
                            context.ProtocolMessage.IssuerAddress = issuer;
                        }
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer  = false,
                    SaveSigninToken = true
                },
                AuthenticationType = AuthTypes.B2EMulti,
            };

            app.UseOpenIdConnectAuthentication(multiOptions);

            // Required for AAD B2B
            OpenIdConnectAuthenticationOptions b2bOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority     = string.Format(aadInstanceLocal, tenant),
                ClientId      = clientId_admin,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed      = OnAuthenticationFailed
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = AuthTypes.Local,
                ResponseType       = Microsoft.IdentityModel.Protocols.OpenIdConnectResponseTypes.CodeIdToken
            };

            app.UseOpenIdConnectAuthentication(b2bOptions);
        }
예제 #25
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            InitializeDataStore();

            // 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

            var coProvider = 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>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                OnApplyRedirect = (context) => {
                }
            };
            var coProviderOrigHandler = coProvider.OnApplyRedirect;

            //Our logic to dynamically modify the path (maybe needs some fine tuning)
            coProvider.OnApplyRedirect = ctx =>
            {
                if (ctx.Request.User.Identity.IsAuthenticated == false)
                {
                    if (ctx.Request.Path.StartsWithSegments(new PathString("/api")))
                    {
                        ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                    }
                    else
                    {
                        ctx.Response.Redirect(MvcApplication.LoginRedirPath);
                    }
                }
                else
                {
                    coProviderOrigHandler.Invoke(ctx);
                }
            };

            var co = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(MvcApplication.LoginRedirPath),
                Provider           = coProvider
            };


            app.UseCookieAuthentication(co);
            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);

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

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = Devmasters.Config.GetWebConfigValue("oauth_id"),
            //    ClientSecret = Devmasters.Config.GetWebConfigValue("oauth_secr")
            //});

            //stage
            // X7T1fbyWdJWsYWQUlvrNNwJj

            //production
            //
            //
        }
예제 #26
0
        private static void ConfigureDefaultAuth(IAppBuilder app)
        {
            // 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

            var authProvider = 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 <AppUserManager, AppUser, Int64>
                                     (
                    validateInterval: TimeSpan.FromMinutes(30),
                    getUserIdCallback: (user) =>
                {
                    return(user.GetUserId <Int64>());
                },
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager)
                                     ),
                OnResponseSignedIn = (context) =>
                {
                }
            };

            //var originalHandler = authProvider.OnApplyRedirect;

            authProvider.OnApplyRedirect = (context) =>
            {
                if (context.Request.SkipAuthRedirect())
                {
                    return;
                }
                var    refer     = context.Request.Query["ref"];
                var    loginPath = context.Options.LoginPath;
                String qs        = $"{context.Options.ReturnUrlParameter}={HttpUtility.UrlEncode(context.Request.Path.Value)}";
                if (refer != null)
                {
                    qs += $"&ref={HttpUtility.UrlEncode(refer)}";
                }
                String url = loginPath.Add(new QueryString(qs));
                context.Response.Redirect(url);
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/account/login"),
                ReturnUrlParameter = "returnurl",
                Provider           = authProvider,
                CookieName         = GetApplicationCookieName(),
                // new values
                CookieSameSite = Microsoft.Owin.SameSiteMode.None,
                CookieSecure   = CookieSecureOption.Always,

                /*
                 * ExpireTimeSpan = TimeSpan.FromSeconds(20),
                 * CookieDomain = "thishost:81"
                 */
            });

            String GetApplicationCookieName()
            {
                var key = ConfigurationManager.AppSettings["AppKey"];

                return($"{key}.ASP.NET.ApplicationCookie");
            }
        }
예제 #27
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // 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

            //==
            var provider = new CookieAuthenticationProvider {
                OnException = context => { }
            };

            //==
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                Provider = provider
            });
            //app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            if (!String.IsNullOrEmpty(MicrosoftClientID) && !String.IsNullOrEmpty(MicrosoftSecret))
            {
                app.UseMicrosoftAccountAuthentication(MicrosoftClientID, MicrosoftSecret);
            }

            if (!String.IsNullOrEmpty(TwitterSecret) && !String.IsNullOrEmpty(TwitterSecret))
            {
                app.UseTwitterAuthentication(TwitterKey, TwitterSecret);
            }

            if (!String.IsNullOrEmpty(FacebookAppID) && !String.IsNullOrEmpty(FacebookSecret))
            {
                //app.UseFacebookAuthentication(FacebookAppID, FacebookSecret);
                var facebookProvider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        // Add the email id to the claim
                        context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email));
                        return(Task.FromResult(0));
                    }
                };
                var options = new FacebookAuthenticationOptions()
                {
                    AppId     = FacebookAppID,
                    AppSecret = FacebookSecret,
                    Provider  = facebookProvider
                };
                options.Scope.Add("email");
                app.UseFacebookAuthentication(options);
            }


            if (!String.IsNullOrEmpty(GoogleClientID) && !String.IsNullOrEmpty(GoogleSecret))
            {
                app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = GoogleClientID,
                    ClientSecret = GoogleSecret
                });
            }
        }
예제 #28
0
        public static void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext <AppSignInManager>(AppSignInManager.Create);

            // 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

            var authProvider = 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 <AppUserManager, AppUser, Int64>
                                     (
                    validateInterval: TimeSpan.FromMinutes(30),
                    getUserIdCallback: (user) =>
                {
                    return(user.GetUserId <Int64>());
                },
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager)
                                     ),
                OnResponseSignedIn = (context) =>
                {
                }
            };

            //var originalHandler = authProvider.OnApplyRedirect;

            authProvider.OnApplyRedirect = (context) =>
            {
                if (context.Request.SkipAuthRedirect())
                {
                    return;
                }
                var    refer     = context.Request.Query["ref"];
                var    loginPath = context.Options.LoginPath;
                String qs        = $"{context.Options.ReturnUrlParameter}={HttpUtility.UrlEncode(context.Request.Path.Value)}";
                if (refer != null)
                {
                    qs += $"&ref={HttpUtility.UrlEncode(refer)}";
                }
                String url = loginPath.Add(new QueryString(qs));
                context.Response.Redirect(url);
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/account/login"),
                ReturnUrlParameter = "returnurl",
                Provider           = authProvider,
                CookieName         = GetApplicationCookieName(),
            });


            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            //AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; //

            // 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));

            app.UseCacheForStaticFiles();

            String GetApplicationCookieName()
            {
                var key = ConfigurationManager.AppSettings["AppKey"];

                return($"{key}.ASP.NET.ApplicationCookie");
            }

            if (ConfigurationManager.GetSection("oauth2") is Oauth2Section oauth2Config)
            {
                var expTimeSpan = oauth2Config.expireTimeSpan;
                if (expTimeSpan.TotalMilliseconds == 0)
                {
                    expTimeSpan = TimeSpan.FromMinutes(20);
                }

                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()
                {
                    Provider                  = new OAuth2Provider(),
                    TokenEndpointPath         = new PathString(oauth2Config.tokenEndpoint),
                    AllowInsecureHttp         = oauth2Config.allowInsecureHttp,
                    AccessTokenExpireTimeSpan = expTimeSpan
                });
            }

            var apiAuth = ConfigurationManager.AppSettings["apiAuthentication"];

            if (apiAuth != null)
            {
                var apiAuthKeys = apiAuth.Split(',');
                if (apiAuthKeys.Any(x => x.Equals("APIKEY", StringComparison.InvariantCultureIgnoreCase)))
                {
                    var opts = new ApiKeyAuthenticationOptions()
                    {
                        UnauthorizedCode = 403
                    };
                    app.UseApiKeyAuthentication(opts);
                }
                if (apiAuthKeys.Any(x => x.Equals("BASIC", StringComparison.InvariantCultureIgnoreCase)))
                {
                    var opts = new ApiBasicAuthenticationOptions()
                    {
                        UnauthorizedCode = 403
                    };
                    app.UseApiBasicAuthentication(opts);
                }
            }
        }
예제 #29
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            var cookieProvider = 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>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            };
            // Modify redirect behaviour to convert login URL to relative
            var applyRedirect = cookieProvider.OnApplyRedirect;

            cookieProvider.OnApplyRedirect = context =>
            {
                var redirectUri = new Uri(context.RedirectUri, UriKind.Absolute);

                if (redirectUri.Scheme == "http" && redirectUri.Host == context.Request.Uri.Host)
                {
                    context.RedirectUri = redirectUri.PathAndQuery;
                }

                applyRedirect(context);
            };
            // 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("/Account/Login"),
                Provider           = cookieProvider
            });
            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);

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

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

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "318088221907523",
                AppSecret = "1ff722cddf38c7f51341ea6797549f2c"
            };

            facebookAuthenticationOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);


            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
예제 #30
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app, IKernel kernel)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => kernel.Get <IRememBeerMeDbContext>());
            app.CreatePerOwinContext <IApplicationUserManager>(
                (factoryOptions, owinContext) =>
            {
                var dbContext = kernel.Get <IRememBeerMeDbContext>();
                return(kernel.Get <IIdentityFactory>()
                       .GetApplicationUserManager(factoryOptions,
                                                  owinContext,
                                                  (DbContext)dbContext));
            });

            app.CreatePerOwinContext <IApplicationSignInManager>(kernel.Get <IIdentityFactory>()
                                                                 .GetApplicationSignInManager);

            // 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
            var onValidateIdentity = SecurityStampValidator
                                     .OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) =>
                user.GenerateUserIdentityAsync(manager));

            var cookieAuthProvider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = onValidateIdentity
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = cookieAuthProvider
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            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);

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

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }