void InitConfig (HttpContext context)
		{
			if(isConfigInitialized)
				return;
			_config = (AuthenticationSection) WebConfigurationManager.GetSection ("system.web/authentication");
			isConfigInitialized = true;
		}
Example #2
0
 public AccountManagement()
 {
     // Get encryption and decryption key information from the configuration.
     Configuration cfg =
         WebConfigurationManager.OpenWebConfiguration(
             System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
     machineKey = (MachineKeySection) cfg.GetSection("system.web/machineKey");
     formsConfig = (AuthenticationSection) cfg.GetSection("system.web/authentication");
 }
		public void Defaults()
		{
			AuthenticationSection a = new AuthenticationSection();

			Assert.IsNotNull (a.Forms, "A1");
			Assert.AreEqual (typeof (FormsAuthenticationConfiguration), a.Forms.GetType(), "A2");
			Assert.IsNotNull (a.Passport, "A3");
			Assert.AreEqual (typeof (PassportAuthentication), a.Passport.GetType(), "A4");
			Assert.AreEqual (AuthenticationMode.Windows, a.Mode, "A5");
		}
Example #4
0
        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            System.Web.Configuration.AuthenticationSection section =
                (System.Web.Configuration.AuthenticationSection)System.Web.Configuration.WebConfigurationManager.GetSection("system.web/authentication");
            if (section.Mode != System.Web.Configuration.AuthenticationMode.Windows)
            {
                // Do something because it is running under Windows mode


                // System.Web.Configuration.AuthenticationSection
                // 使应用程序可以使用 Cookie 来存储已登录用户的信息

                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath          = new PathString("/Account/Login"),
                    CookiePath         = "/",
                    //#if  DEBUG
                    //#else
                    //CookieDomain = WebConfigurationManager.AppSettings["WebUrl"].IndexOf("lilly.com") >= 0 ? ".lilly.com" : ""
                    CookieDomain = WebConfigurationManager.AppSettings["CookieDomain"] ?? ""
                                   //#endif
                                   // ExpireTimeSpan=new System.TimeSpan()
                });

                //System.IO.File.AppendAllText("d:\\a.txt", System.Web.Configuration.WebConfigurationManager.AppSettings["WebUrl"] + "\r\n");
            }

            // 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.UseOAuthClientAuthentication(
            //  new OAuthClientAuthenticationOptions
            //  {
            //      AppId = "228714892725",
            //      AppSecret = "f5947310789ab6c91f3b8fa8642deb00",
            //      Endpoints = new OAuthClientAuthenticationOptions.OAuthClientAuthenticationEndpoints()
            //      {
            //          AuthorizationEndpoint = "https://auth.dxy.cn/conn/oauth2/authorize",
            //          TokenEndpoint = "https://auth.dxy.cn/conn/oauth2/accessToken",
            //          UserInfoEndpoint = "https://auth.dxy.cn/conn/oauth2/profile"
            //      }
            //  });
        }
		void InitConfig (HttpContext context)
		{
			if(isConfigInitialized)
				return;
			_config = (AuthenticationSection) WebConfigurationManager.GetSection ("system.web/authentication");

			// authentication is an app level setting only
			// so we can read app config early on in an attempt to try and
			// skip wiring up event delegates
			if (!_fAuthChecked) {
				_fAuthRequired = (_config.Mode == AuthenticationMode.Forms);
				_fAuthChecked = true;
			}
			isConfigInitialized = true;
		}
Example #6
0
        /// <summary>
        /// Webs the dav authenticates.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="ticket">The ticket.</param>
        /// <returns></returns>
        internal static bool WebDavAuthentificate(HttpContext context, WebDavTicket ticket)
        {
            int userId = -1;

            if (ticket == null)
            {
                throw new Exception("ticket");
            }

            System.Web.Configuration.AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");

            //Если есть сессионный id в тикете
            if (ticket.SessionId != Guid.Empty)
            {
                CleanupAuthSession(ticket.AbsolutePath.StorageType);
                //Пытаемся получить id пользователя из тикета
                userId = TrySessionAuthentificate(ticket.SessionId);
            }
            //Пытемся аутентифицироваться из сессии
            if (userId == -1)
            {
                UserLight userLight = Security.CurrentUser;
                if (userLight != null)
                {
                    userId = userLight.UserID;
                }
            }
            ////Используем стандартный механизм аутентификации
            //if (userId == -1 && section.Mode == AuthenticationMode.Forms)
            //{
            //    System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            //    return false;
            //}
            ////Используем Basic аутентификацию
            //else if (userId == -1)
            //{
            //    userId = BasicAuthentificate(context, ticket);
            //}

            return(userId != -1);
        }
Example #7
0
    /// <summary>
    /// 用户登陆成功后,发放表单cookie验证票据并记录用户的相关信息
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="userName">与票证关联的用户名</param>
    /// <param name="Page">页面对象</param>
    /// <param name="expiration">FormsAuthenticationTicket过期时间</param>
    /// <param name="userInfo">要保存在cookie中用户对象</param>
    public static void UserLoginSetCookie <T>(string userName, Page page, DateTime expiration, T userInfo)
    {
        Configuration conn = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config");

        System.Web.Configuration.AuthenticationSection section = (System.Web.Configuration.AuthenticationSection)conn.SectionGroups.Get("system.web").Sections.Get("authentication");
        expiration = expiration.AddMinutes(section.Forms.Timeout.TotalMinutes);

        //将对象序列化成字符串
        string strUser = JsonHelper.SerializeObject(userInfo);

        // 设置票据Ticket信息
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expiration, false, strUser);

        string strTicket = FormsAuthentication.Encrypt(ticket);                             // 加密票据

        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket); // 使用新userdata保存cookie

        //cookie.Expires = ticket.Expiration;//将票据的过期时间和Cookie的过期时间同步,避免因两者的不同所产生的矛盾

        page.Response.Cookies.Add(cookie);
    }
Example #8
0
        private ConfigurationAuthenticationModel ProcessAuthenticationSection(AuthenticationSection authenticationSection)
        {
            if (authenticationSection == null)
            {
                return null;
            }

            var formsSection = authenticationSection.Forms;

            var result = new ConfigurationAuthenticationModel { Mode = authenticationSection.Mode.ToString() };

            if (result.Forms != null)
            {
                result.Forms = new ConfigurationAuthenticationFormsModel
                    {
                        Cookieless = formsSection.Cookieless.ToString(),
                        DefaultUrl = formsSection.DefaultUrl,
                        Domain = formsSection.Domain,
                        EnableCrossAppRedirects = formsSection.EnableCrossAppRedirects,
                        Name = formsSection.Name,
                        Path = formsSection.Path,
                        Protection = formsSection.Protection.ToString(),
                        RequireSSL = formsSection.RequireSSL,
                        SlidingExpiration = formsSection.SlidingExpiration,
                        TicketCompatibilityMode = TicketCompatibilityMode(formsSection),
                        Timeout = formsSection.Timeout
                    };

                var credentialsSection = formsSection.Credentials;
                if (credentialsSection != null)
                {
                    result.Forms.Credentials = new ConfigurationAuthenticationFormsCredentialsModel
                        {
                            PasswordFormat = credentialsSection.PasswordFormat.ToString()
                        };
                }
            }

            return result;
        }
Example #9
0
    public UsingPassportAuthentication()
    {
// <Snippet1>

// Get the configuration.
// Get the Web application configuration.
        System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnetTest");

// Get the section.
        System.Web.Configuration.AuthenticationSection authenticationSection = (System.Web.Configuration.AuthenticationSection)configuration.GetSection("system.web/authentication");

// Get the authentication passport element.
        PassportAuthentication passport = authenticationSection.Passport;

// </Snippet1>


// <Snippet2>

// Create a new passport object.
        PassportAuthentication newPassport = new PassportAuthentication();

// </Snippet2>

// <Snippet3>

// Get the passport redirect URL
        string redirectUrl = passport.RedirectUrl;

// Set passport redirect Url.
        passport.RedirectUrl = "passportLogin.aspx";

        if (!authenticationSection.SectionInformation.IsLocked)
        {
            configuration.Save();
        }

// </Snippet3>
    }
Example #10
0
        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            System.Web.Configuration.AuthenticationSection section =
                (System.Web.Configuration.AuthenticationSection)System.Web.Configuration.WebConfigurationManager.GetSection("system.web/authentication");
            if (section.Mode != System.Web.Configuration.AuthenticationMode.Windows)
            {
                // Do something because it is running under Windows mode


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

            // 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>
        /// Initializes configuration-related properties and validates configuration.
        /// </summary>        
        public static void Initialize()
        {
            if (!_initialized)
            {
                lock (LockObject)
                {
                    if (!_initialized)
                    {
                        FormsAuthentication.Initialize();
                        AuthenticationConfig = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
                        UserAuthenticationConfig = UserAuthenticationConfiguration.GetConfig();

                        if (UserAuthenticationConfig != null)
                        {
                            _enabled = true;

                            _hashAlgorithm = new SHA512Managed();

                            if (AuthenticationConfig == null)
                            {
                                throw new ConfigurationErrorsException("The UserAuthenticationModule requires Forms authentication to be enabled in web.config.");
                            }

                            _formsTimeout = AuthenticationConfig.Forms.Timeout;

                            if (AuthenticationConfig.Mode != AuthenticationMode.Forms)
                            {
                                throw new ConfigurationErrorsException("The UserAuthenticationModule requires Forms authentication to be enabled in web.config.");
                            }

                            if (FormsAuthentication.CookieMode != HttpCookieMode.UseCookies)
                            {
                                throw new ConfigurationErrorsException("The UserAuthenticationModule requires Forms Authentication to use cookies (cookieless='UseCookies').");
                            }

                            if (UserAuthenticationConfig.StateProvider == null)
                            {
                                // TODO: Add exception text
                                throw new ConfigurationErrorsException("TODO");
                            }

                            _providers = new UserAuthenticationTicketProviderCollection();
                            ProvidersHelper.InstantiateProviders(UserAuthenticationConfig.Providers, _providers, typeof (UserAuthenticationTicketProviderBase));
                            _providers.SetReadOnly();

                            _provider = _providers[UserAuthenticationConfig.StateProvider];

                            _enforceClientHostAddressValidation = UserAuthenticationConfig.EnforceClientHostAddressValidation;
                            _enforceUserAgentValidation = UserAuthenticationConfig.EnforceUserAgentValidation;

                            /* TODO: Implement/fix sliding Provider expiration */
                            _hashSalt = UserAuthenticationConfig.HashSalt;

                            if (_hashSalt == "ExampleSalt")
                            {
                                throw new ConfigurationErrorsException("For security purposes, you must change the example salt in web.config's userAuthentication element.`");
                            }
                        }
                        else
                        {
                            _enabled = false;

                            if (AuthenticationConfig != null && AuthenticationConfig.Mode == AuthenticationMode.Forms)
                            {
                                _formsTimeout = AuthenticationConfig.Forms.Timeout;
                            }

                            _enforceClientHostAddressValidation = false;
                            _enforceUserAgentValidation = false;
                        }

                        _initialized = true;
                    }
                }
            }
        }
        /// <summary>
        /// Initializes configuration-related properties and validates configuration.
        /// </summary>        
        public static void Initialize()
        {
            if (!initialized)
            {
                lock (LockObject)
                {
                    if (!initialized)
                    {
                        FormsAuthentication.Initialize();
                        AuthenticationConfig = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
                        CasClientConfig = CasClientConfiguration.Config;

                        if (AuthenticationConfig == null)
                        {
                            LogAndThrowConfigurationException(
                                "The CAS authentication provider requires Forms authentication to be enabled in web.config.");
                        }

                        if (AuthenticationConfig.Mode != AuthenticationMode.Forms)
                        {
                            LogAndThrowConfigurationException(
                                "The CAS authentication provider requires Forms authentication to be enabled in web.config.");
                        }

                        if (FormsAuthentication.CookieMode != HttpCookieMode.UseCookies)
                        {
                            LogAndThrowConfigurationException(
                                "CAS requires Forms Authentication to use cookies (cookieless='UseCookies').");
                        }

                        xmlReaderSettings = new XmlReaderSettings();
                        xmlReaderSettings.ConformanceLevel = ConformanceLevel.Auto;
                        xmlReaderSettings.IgnoreWhitespace = true;

                        xmlNameTable = new NameTable();

                        xmlNamespaceManager = new XmlNamespaceManager(xmlNameTable);
                        xmlNamespaceManager.AddNamespace("cas", "http://www.yale.edu/tp/cas");
                        xmlNamespaceManager.AddNamespace("saml", "urn: oasis:names:tc:SAML:1.0:assertion");
                        xmlNamespaceManager.AddNamespace("saml2", "urn: oasis:names:tc:SAML:1.0:assertion");
                        xmlNamespaceManager.AddNamespace("samlp", "urn: oasis:names:tc:SAML:1.0:protocol");

                        formsLoginUrl = AuthenticationConfig.Forms.LoginUrl;
                        formsTimeout = AuthenticationConfig.Forms.Timeout;

                        if (string.IsNullOrEmpty(CasClientConfig.CasServerUrlPrefix))
                        {
                            LogAndThrowConfigurationException("The CasServerUrlPrefix is required");
                        }

                        casServerUrlPrefix = CasClientConfig.CasServerUrlPrefix;
                        configLogger.Info("casServerUrlPrefix = " + casServerUrlPrefix);
                        
                        casServerLoginUrl = CasClientConfig.CasServerLoginUrl;
                        configLogger.Info("casServerLoginUrl = " + casServerLoginUrl);
                        
                        ticketValidatorName = CasClientConfig.TicketValidatorName;
                        configLogger.Info("ticketValidatorName = " + ticketValidatorName);
                        
                        ticketTimeTolerance = CasClientConfig.TicketTimeTolerance;
                        configLogger.Info("ticketTimeTolerance = " + ticketTimeTolerance);
                        
                        serverName = CasClientConfig.ServerName;
                        configLogger.Info("serverName = " + serverName);
                        
                        renew = CasClientConfig.Renew;
                        configLogger.Info("renew = " + renew);
                        
                        gateway = CasClientConfig.Gateway;
                        configLogger.Info("gateway = " + gateway);
                        
                        gatewayStatusCookieName = CasClientConfig.GatewayStatusCookieName;
                        configLogger.Info("gatewayStatusCookieName = " + gatewayStatusCookieName);
                        
                        redirectAfterValidation = CasClientConfig.RedirectAfterValidation;
                        configLogger.Info("redirectAfterValidation = " + redirectAfterValidation);
                        
                        singleSignOut = CasClientConfig.SingleSignOut;
                        configLogger.Info("singleSignOut = " + singleSignOut);
                        
                        serviceTicketManagerProvider = CasClientConfig.ServiceTicketManager;
                        configLogger.Info("serviceTicketManagerProvider = " + serviceTicketManagerProvider);
                        
                        proxyTicketManagerProvider = CasClientConfig.ProxyTicketManager;
                        configLogger.Info("proxyTicketManagerProvider = " + proxyTicketManagerProvider);
                        
                        notAuthorizedUrl = CasClientConfig.NotAuthorizedUrl;
                        configLogger.Info("notAuthorizedUrl = " + notAuthorizedUrl);
                        
                        cookiesRequiredUrl = CasClientConfig.CookiesRequiredUrl;
                        configLogger.Info("cookiesRequiredUrl = " + cookiesRequiredUrl);
                        
                        gatewayParameterName = CasClientConfig.GatewayParameterName;
                        configLogger.Info("gatewayParameterName = " + gatewayParameterName);
                        
                        proxyCallbackParameterName = CasClientConfig.ProxyCallbackParameterName;
                        configLogger.Info("proxyCallbackParameterName = " + proxyCallbackParameterName);

                        casProxyCallbackUrl = CasClientConfig.ProxyCallbackUrl;
                        configLogger.Info("proxyCallbackUrl = " + casProxyCallbackUrl);

                        requireCasForMissingContentTypes = CasClientConfig.RequireCasForMissingContentTypes;
                        configLogger.Info("requireCasForMissingContentTypes = " + requireCasForMissingContentTypes);

                        requireCasForContentTypes = CasClientConfig.RequireCasForContentTypes;
                        configLogger.Info("requireCasForContentTypes = " + requireCasForContentTypes);

                        bypassCasForHandlers = CasClientConfig.BypassCasForHandlers;
                        configLogger.Info("bypassCasForHandlers = " + bypassCasForHandlers);
                        
                        if (!String.IsNullOrEmpty(ticketValidatorName))
                        {
                            if (String.Compare(CasClientConfiguration.CAS10_TICKET_VALIDATOR_NAME,ticketValidatorName) == 0)                            
                                ticketValidator = new Cas10TicketValidator();
                            else if (String.Compare(CasClientConfiguration.CAS20_TICKET_VALIDATOR_NAME, ticketValidatorName) == 0)
                                ticketValidator = new Cas20ServiceTicketValidator();
                            else if (String.Compare(CasClientConfiguration.SAML11_TICKET_VALIDATOR_NAME, ticketValidatorName) == 0)
                                ticketValidator = new Saml11TicketValidator();                            
                            else
                            {
                                // the ticket validator name is not recognized, let's try to get it using Reflection then                                
                                Type ticketValidatorType = Type.GetType(ticketValidatorName, false, true);
                                if (ticketValidatorType != null)
                                {
									if (typeof(ITicketValidator).IsAssignableFrom(ticketValidatorType))
										ticketValidator = (ITicketValidator)Activator.CreateInstance(ticketValidatorType);                                    
                                    else
                                        LogAndThrowConfigurationException("Ticket validator type is not correct " + ticketValidatorName);
                                }
                                else
                                    LogAndThrowConfigurationException("Could not find ticket validatory type " + ticketValidatorName);
                            }
                            configLogger.Info("TicketValidator type = " + ticketValidator.GetType().ToString());
                        }
                        else                                                    
                            LogAndThrowConfigurationException("Ticket validator name missing");
                        
                        
                        
                        if (String.IsNullOrEmpty(serviceTicketManagerProvider))
                        {
                            // Web server cannot maintain ticket state, verify tickets, perform SSO, etc.
                        }
                        else
                        {
                            if (String.Compare(CasClientConfiguration.CACHE_SERVICE_TICKET_MANAGER, serviceTicketManagerProvider) == 0)
                                serviceTicketManager = new CacheServiceTicketManager();
                            else
                            {
                                // the service ticket manager  is not recognized, let's try to get it using Reflection then
                                Type serviceTicketManagerType = Type.GetType(serviceTicketManagerProvider, false, true);
                                if (serviceTicketManagerType != null)
                                {
                                    if (typeof(IServiceTicketManager).IsAssignableFrom(serviceTicketManagerType))
                                        serviceTicketManager = (IServiceTicketManager)Activator.CreateInstance(serviceTicketManagerType);
                                    else
                                        LogAndThrowConfigurationException("Service Ticket Manager type is not correct " + serviceTicketManagerProvider);
                                }
                                else
                                    LogAndThrowConfigurationException("Could not find Service Ticket Manager type " + serviceTicketManagerProvider);
                            }
                            configLogger.Info("ServiceTicketManager type = " + serviceTicketManager.GetType().ToString());
                        }

                        if (String.IsNullOrEmpty(proxyTicketManagerProvider))
                        {
                            // Web server cannot generate proxy tickets
                        }
                        else
                        {
                            if (String.Compare(CasClientConfiguration.CACHE_PROXY_TICKET_MANAGER, proxyTicketManagerProvider) == 0)
                                proxyTicketManager = new CacheProxyTicketManager();
                            else
                            {
                                // the proxy ticket manager  is not recognized, let's try to get it using Reflection then
                                Type proxyTicketManagerType = Type.GetType(proxyTicketManagerProvider, false, true);
                                if (proxyTicketManagerType != null)
                                {
                                    if (typeof(IProxyTicketManager).IsAssignableFrom(proxyTicketManagerType))
                                        proxyTicketManager = (IProxyTicketManager)Activator.CreateInstance(proxyTicketManagerType);
                                    else
                                        LogAndThrowConfigurationException("Proxy Ticket Manager type is not correct " + proxyTicketManagerProvider);
                                }
                                else
                                    LogAndThrowConfigurationException("Could not find Proxy Ticket Manager type " + proxyTicketManagerProvider);
                            }
                            configLogger.Info("ProxyTicketManager type = " + proxyTicketManager.GetType().ToString());
                        }

                        // Validate configuration
                        bool haveServerName = !String.IsNullOrEmpty(serverName);
                        if (!haveServerName)
                        {
                            LogAndThrowConfigurationException(CasClientConfiguration.SERVER_NAME + " cannot be null or empty.");
                        }

                        if (String.IsNullOrEmpty(casServerLoginUrl))
                        {
                            LogAndThrowConfigurationException(CasClientConfiguration.CAS_SERVER_LOGIN_URL + " cannot be null or empty.");
                        }

                        if (serviceTicketManager == null && singleSignOut)
                        {
                            LogAndThrowConfigurationException("Single Sign Out support requires a ServiceTicketManager.");
                        }

                        if (gateway && renew)
                        {
                            LogAndThrowConfigurationException("Gateway and Renew functionalities are mutually exclusive");
                        }

                        if (!redirectAfterValidation)
                        {
                            LogAndThrowConfigurationException(
                                "Forms Authentication based modules require RedirectAfterValidation to be set to true.");
                        }

                        initialized = true;
                    }
                }

                if (ServiceTicketManager != null) ServiceTicketManager.Initialize();
                if (ProxyTicketManager != null) ProxyTicketManager.Initialize();
                if (TicketValidator != null) TicketValidator.Initialize();
            }
        }
		internal AuthenticationConfiguration(AuthenticationSection section) {
			this.authenticationSection = section;
			formsAuthenticationConfiguration = new FormsAuthenticationConfigurationWrapper(authenticationSection.Forms);
		}