Esempio n. 1
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();
        }
 /// <summary>
 /// Create an instance of the options initialized with the default values
 /// </summary>
 public CookieAuthenticationOptions()
     : base(CookieAuthenticationDefaults.AuthenticationType)
 {
     ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
     CookiePath         = "/";
     ExpireTimeSpan     = TimeSpan.FromDays(14);
     SlidingExpiration  = true;
     CookieHttpOnly     = true;
     CookieSecure       = CookieSecureOption.SameAsRequest;
     SystemClock        = new SystemClock();
     Provider           = new CookieAuthenticationProvider();
 }
 /// <summary>
 /// Create an instance of the options initialized with the default values
 /// </summary>
 public CookieAuthenticationOptions()
     : base(CookieAuthenticationDefaults.AuthenticationType)
 {
     ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
     CookiePath = "/";
     ExpireTimeSpan = TimeSpan.FromDays(14);
     SlidingExpiration = true;
     CookieHttpOnly = true;
     CookieSecure = CookieSecureOption.SameAsRequest;
     SystemClock = new SystemClock();
     Provider = new CookieAuthenticationProvider();
 }
Esempio n. 4
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);
                }
            };
            return cookieAuthenticationProvider;
        }
Esempio n. 5
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.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),
                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
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");
            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 = "827541077270473",
                              AppSecret = "aa63a79f14dff2a568db23b90bbfd6d7",
                              Provider = facebookProvider
                          };
            options.Scope.Add("email");
            app.UseFacebookAuthentication(options);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Esempio n. 6
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);
        }
        // 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
                });
            }
        }