public void RemoveAuthenticationMethod(DSMAuthenticationMethod method) { if (AuthenticationSection.ContainsKey(method)) { AuthenticationSection.Remove(AuthenticationSection[method]); } }
/// <summary> /// Gets the user email address either from the SQL Membership provider or from AD depending /// on how security is configured for the applciation. /// </summary> /// <param name="userName">Name of the user whose email you wish to fetch.</param> /// <returns></returns> public static string GetUserEmailAddress(string userName) { lock (lockGetUserEmailAddress) { string emailAddress = string.Empty; AuthenticationSection authenticationSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); switch (authenticationSection.Mode) { case AuthenticationMode.Windows: emailAddress = GetAdUserProperty(userName, "mail"); break; case AuthenticationMode.Forms: MembershipUser user = Membership.GetUser(userName); if (user != null) { emailAddress = user.Email; } break; default: break; } return(emailAddress); } }
public void Init(HttpApplication context) { if (context == null) { throw new ArgumentNullException("context"); } //配置Web应用程序的身份验证,无法继承此类 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication"); //获取或设置身份验证模式,此处用于判断身份验证模式是否为Forms if (section.Mode == AuthenticationMode.Forms) { //当安全模块已建立用户标识时发生 context.AuthenticateRequest += new EventHandler(CommonModule.Application_AuthenticateRequest); //恰好在ASP.NET开始执行事件处理程序时发生 context.PreRequestHandlerExecute += new EventHandler(CommonModule.context_PreRequestHandlerExecute); } SiteConfigInfo config = SiteConfig.ConfigInfo(); string virtualPath = config.SiteInfo.VirtualPath; if (string.IsNullOrEmpty(virtualPath) || (string.Compare(virtualPath, VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath), true, CultureInfo.CurrentCulture) != 0)) { config.SiteInfo.VirtualPath = HttpContext.Current.Request.ApplicationPath; new SiteConfig().Update(config); } Jobs.Instance().Start(); }
//Método de gerenciamento de sessão private void SetAuthenticationCookie(string employeeID, List <string> roles) { HttpCookiesSection cookieSection = (HttpCookiesSection)ConfigurationManager.GetSection("system.web/httpCookies"); AuthenticationSection authenticationSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, employeeID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(authenticationSection.Forms.Timeout.TotalMinutes), false, string.Empty); Session["usuario"] = string.Join("|", roles.ToArray()); String encryptedTicket = FormsAuthentication.Encrypt(authTicket); FormsAuthentication.Authenticate(employeeID, null); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (cookieSection.RequireSSL || authenticationSection.Forms.RequireSSL) { authCookie.Secure = true; } HttpContext.Response.Cookies.Add(authCookie); FormsAuthentication.SetAuthCookie(employeeID, true); }
public IdentityClient() { Application = new ApplicationSection(); Authentication = new AuthenticationSection(); Account = new AccountSection(); Email = new EmailSection(); }
public bool IsWindowsAuth() { Configuration config = OpenWebConfiguration(ApplicationPath); AuthenticationSection auth = (AuthenticationSection)config.GetSection("system.web/authentication"); return(auth.Mode == AuthenticationMode.Windows); }
public ActionResult IndexOriginal(string id, string file) { string mediaPath = "/media/" + id + "/" + file; IMediaService mediaService = ApplicationContext.Current.Services.MediaService; IMedia media = mediaService.GetMediaByPath(mediaPath); if (media != null) { bool requiresMemberLogin = media.GetValue <bool>("requiresMemberLogin"); if (requiresMemberLogin == true) { if (!User.Identity.IsAuthenticated) { System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/"); AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms; string redirectUrl = formsAuthentication.LoginUrl + "?ReturnUrl=" + Url.Encode(mediaPath); return(Redirect(redirectUrl)); } } FileStream fileStream = new FileStream(Server.MapPath(mediaPath), FileMode.Open); return(new FileStreamResult(fileStream, MimeMapping.GetMimeMapping(file))); } else { return(HttpNotFound()); } }
public static AuthenticationMode GetAuthMode() { Configuration cfg = WebConfigurationManager.OpenWebConfiguration("~/"); AuthenticationSection authenticationSection = (AuthenticationSection)cfg.GetSection("system.web/authentication"); return(authenticationSection.Mode); }
public void Init(HttpApplication context) { // Below is an example of how you can handle LogRequest event and provide // custom logging implementation for it //context.LogRequest += new EventHandler(OnLogRequest); // For authentication and authorization, detemine which authentication option goes which functionality System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/WebModule"); _AutheSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); AuthenticationMode _AutheMode = _AutheSection.Mode; switch (_AutheMode) { case AuthenticationMode.Forms: //For custom authenticating context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest); //For custom authorization context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest); // context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute); break; // future : for windows domain case, refer to Active Directory programming later. case AuthenticationMode.Windows: break; } }
public override MembershipUser GetUser(string username, bool userIsOnline) { string email = null; AuthenticationSection authSection = (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication"); FormsAuthenticationUser user = authSection.Forms.Credentials.Users[username.ToLower()]; if (user != null) { NameValueCollection emailsSection = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("emails"); email = emailsSection[user.Name]; return(new MembershipUser( "FormsProvider", username, null, email, null, null, true, false, // do not use DateTime.MinValue because some WebDAV clients may not properly parse it. new DateTime(2000, 1, 1), new DateTime(2000, 1, 1), new DateTime(2000, 1, 1), new DateTime(2000, 1, 1), new DateTime(2000, 1, 1))); } return(null); }
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { bool defaultPassword = this.IsDefaultFormsAuthPassword(); if (defaultPassword) { this.Login1.Visible = false; this.changePassword.Focus(); } else { this.changePassword.Visible = false; AuthenticationSection authenticationSection = this.GetFormsAuthConfig(); FormsAuthenticationUserCollection users = authenticationSection.Forms.Credentials.Users; if (users.Count > 0) { this.Login1.UserName = users[0].Name; } this.Login1.Focus(); } } }
public override void ProcessGeneratedCode(DomainServiceDescription domainServiceDescription, CodeCompileUnit codeCompileUnit, IDictionary <Type, CodeTypeDeclaration> typeMapping) { // Get a reference to the entity class CodeTypeDeclaration codeGenEntity = typeMapping[typeof(TestEntity)]; AppDomain appDomain = AppDomain.CurrentDomain; AppDomainSetup setup = appDomain.SetupInformation; string baseDir = appDomain.BaseDirectory; codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] BaseDirectory:" + baseDir)); Configuration cfg = WebConfigurationManager.OpenWebConfiguration(null); AuthenticationSection authSection = (AuthenticationSection)cfg.GetSection("system.web/authentication"); FormsAuthenticationConfiguration formsAuth = authSection.Forms; if (formsAuth != null) { codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] Authentication:forms")); } ConnectionStringsSection connSect = cfg.ConnectionStrings; if (connSect != null) { ConnectionStringSettingsCollection connColl = connSect.ConnectionStrings; foreach (ConnectionStringSettings connSetting in connColl) { codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] ConnectionString:" + connSetting.ConnectionString)); } } }
private void OnEnter(object source, EventArgs eventArgs) { if (!_fAuthChecked || _fAuthRequired) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; if (!_fAuthChecked) { AuthenticationSection authentication = RuntimeConfig.GetAppConfig().Authentication; _fAuthRequired = AuthenticationConfig.Mode == AuthenticationMode.Passport; _LoginUrl = authentication.Passport.RedirectUrl; _fAuthChecked = true; } if (_fAuthRequired) { PassportIdentity identity = new PassportIdentity(); this.OnAuthenticate(new PassportAuthenticationEventArgs(identity, context)); context.SetSkipAuthorizationNoDemand(AuthenticationConfig.AccessingLoginPage(context, _LoginUrl), false); if (!context.SkipAuthorization) { context.SkipAuthorization = AssemblyResourceLoader.IsValidWebResourceRequest(context); } } } }
/// <summary> /// Authenticates the user in the application using cookieModel. /// </summary> private void Authenticate(AuthorizationCookieModel cookieModel, bool rememberMe = false) { HttpContext context = HttpContext.Current; //Create a new ticket AuthenticationSection config = (AuthenticationSection)context.GetSection("system.web/authentication"); //Update Cookie bool isRememberMePreviousCookie = false; HttpCookie authCookie = HttpContext.Current.Request.Cookies[_cookieName]; if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value)) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { isRememberMePreviousCookie = authTicket.IsPersistent; } } DateTime expirationDate = rememberMe || isRememberMePreviousCookie ? DateTime.Now.AddDays(AppConfigManager.RememberMeExpirationTimeFrameInDays) : DateTime.Now.AddMinutes(config.Forms.Timeout.TotalMinutes); //todo: move to separate method string cookieBody; using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize(ms, cookieModel); cookieBody = BytesToHexString((ms.ToArray())); } FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, cookieModel.UserId.ToString(CultureInfo.InvariantCulture), DateTime.Now, expirationDate, rememberMe || isRememberMePreviousCookie, cookieBody, FormsAuthentication.FormsCookiePath); //Assign ticket to cookie string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(_cookieName, encryptedTicket) { HttpOnly = true }; //Remember Me if (rememberMe || isRememberMePreviousCookie) { cookie.Expires = expirationDate; } context.Response.Cookies.Clear(); context.Response.Cookies.Add(cookie); AssignPrincipal(cookieModel); }
private AuthenticationSection GetAuthenticationSection() { AuthenticationSection section = new AuthenticationSection(); section.Mode = AuthenticationMode.Forms; return(section); }
internal IdentityClient(IdentityClientConfiguration config) { Configuration = config; HttpHelper.Configure(config.ApplicationId, config.Address); Application = new ApplicationSection(); Authentication = new AuthenticationSection(); Email = new EmailSection(); }
public static bool Authenticate(string name, string password) { if (name == null || password == null) { return(false); } Initialize(); HttpContext context = HttpContext.Current; if (context == null) { throw new HttpException("Context is null!"); } name = name.ToLower(Helpers.InvariantCulture); #if NET_2_0 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection(authConfigPath); FormsAuthenticationCredentials config = section.Forms.Credentials; FormsAuthenticationUser user = config.Users[name]; string stored = null; if (user != null) { stored = user.Password; } #else AuthConfig config = context.GetConfig(authConfigPath) as AuthConfig; Hashtable users = config.CredentialUsers; string stored = users [name] as string; #endif if (stored == null) { return(false); } bool caseInsensitive = true; switch (config.PasswordFormat) { case FormsAuthPasswordFormat.Clear: caseInsensitive = false; /* Do nothing */ break; case FormsAuthPasswordFormat.MD5: password = HashPasswordForStoringInConfigFile(password, FormsAuthPasswordFormat.MD5); break; case FormsAuthPasswordFormat.SHA1: password = HashPasswordForStoringInConfigFile(password, FormsAuthPasswordFormat.MD5); break; } #if NET_2_0 return(String.Compare(password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0); #else return(String.Compare(password, stored, caseInsensitive, Helpers.InvariantCulture) == 0); #endif }
public static void Initialize() { if (initialized) { return; } lock (locker) { if (initialized) { return; } #if NET_2_0 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection(authConfigPath); FormsAuthenticationConfiguration config = section.Forms; cookieName = config.Name; timeout = (int)config.Timeout.TotalMinutes; cookiePath = config.Path; protection = config.Protection; requireSSL = config.RequireSSL; slidingExpiration = config.SlidingExpiration; cookie_domain = config.Domain; cookie_mode = config.Cookieless; cookies_supported = true; /* XXX ? */ default_url = MapUrl(config.DefaultUrl); enable_crossapp_redirects = config.EnableCrossAppRedirects; login_url = MapUrl(config.LoginUrl); #else HttpContext context = HttpContext.Current; AuthConfig authConfig = context.GetConfig(authConfigPath) as AuthConfig; if (authConfig != null) { cookieName = authConfig.CookieName; timeout = authConfig.Timeout; cookiePath = authConfig.CookiePath; protection = authConfig.Protection; #if NET_1_1 requireSSL = authConfig.RequireSSL; slidingExpiration = authConfig.SlidingExpiration; #endif } else { cookieName = ".MONOAUTH"; timeout = 30; cookiePath = "/"; protection = FormsProtectionEnum.All; #if NET_1_1 slidingExpiration = true; #endif } #endif initialized = true; } }
private AuthenticationSection GetFormsAuthConfig(out Configuration webConfig) { string root = this.Request.ApplicationPath; webConfig = WebConfigurationManager.OpenWebConfiguration(root); AuthenticationSection authenticationSection = (AuthenticationSection)webConfig.GetSection("system.web/authentication"); return(authenticationSection); }
void InitConfig(HttpContext context) { if (isConfigInitialized) { return; } _config = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication"); isConfigInitialized = true; }
public void RemoveAuthenticationMethod(DSMAuthenticationMethod method) { DSMAuthentication am = AuthenticationSection.TryGet(method); if (am != null) { AuthenticationSection.Remove(am); } }
public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { string encryptedUsername = model.UserName; //base64Encryption.Encrypt(model.UserName); string encryptedPassword = model.Password; //base64Encryption.Encrypt(model.Password); var result = db.users.Where(u => u.username.Equals(encryptedUsername) && u.password.Equals(encryptedPassword)); //ModelState.AddModelError("",model.UserName+":"+base64Encryption.Encrypt(model.UserName)); //ModelState.AddModelError("", model.Password + ":" + base64Encryption.Encrypt(model.Password)); //return View(); if (result.Count() != 0) { var dbuser = result.FirstOrDefault(); AuthenticationSection authSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); int timeOut = authSection.Forms.Timeout.Minutes; Session["userName"] = dbuser.name; var serializer = new JavaScriptSerializer(); var serializedUser = serializer.Serialize(dbuser.id); var ticket = new FormsAuthenticationTicket(1, dbuser.name, DateTime.Now, DateTime.Now.AddMinutes(timeOut), false, serializedUser); var hash = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) { Expires = ticket.Expiration }; Response.Cookies.Add(authCookie); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { // return Redirect(returnUrl); this.TempData["returnUrl"] = returnUrl; return(RedirectToAction("Index")); } else { return(RedirectToAction("Index")); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return(View(model)); }
protected FormsAuthenticationUserCollection getUsers() { if (_users == null) { AuthenticationSection section = getAuthenticationSection(); FormsAuthenticationCredentials creds = section.Forms.Credentials; _users = section.Forms.Credentials.Users; } return(_users); }
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"); }
public ActionResult Index2() { // Get the Web application configuration. Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Web.config"); // Get the section. AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); return(Content(authenticationSection.SectionInformation.AllowDefinition.ToString())); }
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 DSMAuthentication GetOrAddAuthenticationMethod(DSMAuthenticationMethod method) { DSMAuthentication am = AuthenticationSection.TryGet(method); if (am == null) { am = new DSMAuthentication(method); AuthenticationSection.Add(am); } return(am); }
public DSMAuthentication GetAuthenticationMethod(DSMAuthenticationMethod method) { if (AuthenticationSection.ContainsKey(method)) { return(AuthenticationSection[method]); } else { return(null); } }
/// <summary> /// Gets the user name formatted for use in the TicketDesk database. /// </summary> /// <remarks> /// For AD users, this removes the domain name from the user name. /// </remarks> /// <param name="userName">Name of the user to format.</param> /// <returns></returns> public static string GetFormattedUserName(string userName) { lock (lockGetFormattedUserName) { AuthenticationSection authenticationSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); if (authenticationSection.Mode == AuthenticationMode.Windows && !string.IsNullOrEmpty(userName) && userName.Contains('\\')) { userName = userName.Split('\\')[1]; } return(userName.ToLower()); } }
/// <summary> /// Adds web.config settings for windows authentication. /// </summary> internal void WriteConfigForWindowsAuth() { // Turn on Windows authentication AuthenticationSection authSection = _config.GetSection("system.web/authentication") as AuthenticationSection; authSection.Mode = AuthenticationMode.Windows; // Turn off anonymous auth AnonymousIdentificationSection anonSection = _config.GetSection("system.web/anonymousIdentification") as AnonymousIdentificationSection; anonSection.Enabled = false; }