Inheritance: IPrincipal, ISerializable
Exemple #1
0
 public static void AddUsersToRoles(string[] usernames, string[] roleNames)
 {
     EnsureEnabled();
     SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 0, "roleNames");
     SecUtility.CheckArrayParameter(ref usernames, true, true, true, 0, "usernames");
     Provider.AddUsersToRoles(usernames, roleNames);
     try
     {
         RolePrincipal currentUser = GetCurrentUser() as RolePrincipal;
         if (((currentUser != null) && (currentUser.ProviderName == Provider.Name)) && currentUser.IsRoleListCached)
         {
             foreach (string str in usernames)
             {
                 if (System.Web.Util.StringUtil.EqualsIgnoreCase(currentUser.Identity.Name, str))
                 {
                     currentUser.SetDirty();
                     return;
                 }
             }
         }
     }
     catch
     {
     }
 }
Exemple #2
0
        static public void RemoveUsersFromRole(string[] usernames, string roleName)
        {
            EnsureEnabled();

            SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");

            SecUtility.CheckArrayParameter(ref usernames,
                                           true,
                                           true,
                                           true,
                                           0,
                                           "usernames");

            Provider.RemoveUsersFromRoles(usernames, new string[] { roleName });
            try
            {
                RolePrincipal user = GetCurrentUser() as RolePrincipal;
                if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached)
                {
                    foreach (string username in usernames)
                    {
                        if (StringUtil.EqualsIgnoreCase(user.Identity.Name, username))
                        {
                            user.SetDirty();
                            break;
                        }
                    }
                }
            }
            catch { }
        }
 public IPrincipal GetImpersonatorPrincipal()
 {
     IPrincipal result = null;
     var impersonatorUserName = GetRealUserName();
     if (impersonatorUserName != null)
     {
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(impersonatorUserName, true, TimeSpan.FromMinutes(30).Minutes);
         result = new RolePrincipal(new FormsIdentity(ticket));
     }
     return result;
 }
        /// <summary>
        /// Sets the current user for unit tests. 
        /// </summary>
        /// <param name="userName">The user to become the current one.</param>
        /// <param name="roleNameList">The roles the current user will be in. The parameter is ignored by this security provider; 
        /// the role provider set for the application (in <i>Web.Config</i>) will be used to retrieve roles.</param>
        public override void SetUser(string userName, string roleNameList)
        {
            HttpRequest request = new HttpRequest("", "http://www.bits4finance.com", "");
            HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                2, userName, DateTime.Now, DateTime.Now.AddMinutes(30), false, "", "/TotalGiro");
            IIdentity identity = new FormsIdentity(ticket);
            IPrincipal user = new RolePrincipal(identity);

            Thread.CurrentPrincipal = user;
            HttpContext.Current.User = user;
        }
        /// <summary>
        /// Authenticates the request.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void AuthenticateRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            var http = new HttpContextWrapper(app.Context);

            if (http.User == null || http.User is RolePrincipal) 
                return;

            var principal = new RolePrincipal(http.User.Identity);

            app.Context.User = principal;
            Thread.CurrentPrincipal = principal;
        }
 private void InitFromEncryptedTicket(string encryptedTicket)
 {
     if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(4, 8))
     {
         EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest);
     }
     if (!string.IsNullOrEmpty(encryptedTicket))
     {
         byte[] buffer = CookieProtectionHelper.Decode(Roles.CookieProtectionValue, encryptedTicket);
         if (buffer != null)
         {
             RolePrincipal principal           = null;
             MemoryStream  serializationStream = null;
             try
             {
                 serializationStream = new MemoryStream(buffer);
                 principal           = new BinaryFormatter().Deserialize(serializationStream) as RolePrincipal;
             }
             catch
             {
             }
             finally
             {
                 serializationStream.Close();
             }
             if (((principal != null) && StringUtil.EqualsIgnoreCase(principal._Username, this._Identity.Name)) && (StringUtil.EqualsIgnoreCase(principal._ProviderName, this._ProviderName) && (DateTime.UtcNow <= principal._ExpireDate)))
             {
                 this._Version           = principal._Version;
                 this._ExpireDate        = principal._ExpireDate;
                 this._IssueDate         = principal._IssueDate;
                 this._IsRoleListCached  = principal._IsRoleListCached;
                 this._CachedListChanged = false;
                 this._Username          = principal._Username;
                 this._Roles             = principal._Roles;
                 this.RenewIfOld();
                 if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(4, 8))
                 {
                     EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", this._Identity.Name);
                 }
                 return;
             }
         }
     }
     this.Init();
     this._CachedListChanged = true;
     if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(4, 8))
     {
         EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", this._Identity.Name);
     }
 }
        private void OnLeave(Object source, EventArgs eventArgs)
        {
            HttpApplication app;
            HttpContext     context;

            app     = (HttpApplication)source;
            context = app.Context;

            if (!Roles.Enabled || !Roles.CacheRolesInCookie || context.Response.HeadersWritten)
            {
                return;
            }

            if (context.User == null || !(context.User is RolePrincipal) || !context.User.Identity.IsAuthenticated)
            {
                return;
            }
            if (Roles.CookieRequireSSL && !context.Request.IsSecureConnection)
            { // if cookie is sent, then clear it
                if (context.Request.Cookies[Roles.CookieName] != null)
                {
                    Roles.DeleteCookie();
                }
                return;
            }
            RolePrincipal rp = (RolePrincipal)context.User;

            if (rp.CachedListChanged && context.Request.Browser.Cookies)
            {
                string s = rp.ToEncryptedTicket();
                if (string.IsNullOrEmpty(s) || s.Length > MAX_COOKIE_LENGTH)
                {
                    Roles.DeleteCookie();
                }
                else
                {
                    HttpCookie cookie = new HttpCookie(Roles.CookieName, s);
                    cookie.HttpOnly = true;
                    cookie.Path     = Roles.CookiePath;
                    cookie.Domain   = Roles.Domain;
                    if (Roles.CreatePersistentCookie)
                    {
                        cookie.Expires = rp.ExpireDate;
                    }
                    cookie.Secure = Roles.CookieRequireSSL;
                    context.Response.Cookies.Add(cookie);
                }
            }
        }
        /// <summary>
        /// Validates the user given their username and password
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static bool ValidateUser(string username, string password)
        {
            bool isAuthenticated = System.Web.Security.Membership.ValidateUser(username, password);

            if (isAuthenticated)
            {
                MembershipUser user = System.Web.Security.Membership.GetUser(username);
                BMRestoIdentity identity = new BMRestoIdentity(user.UserName);
                RolePrincipal principal = new RolePrincipal(identity);

                System.Threading.Thread.CurrentPrincipal = principal;
            }

            return isAuthenticated;
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            var outputIdentity = new ClaimsIdentity();
            var roles = new RolePrincipal(principal.Identity);

            outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, principal.Identity.Name));
            outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, roles.GetRoles().First()));

            return outputIdentity;
        }
Exemple #10
0
 static public void AddUserToRole(string username, string roleName)
 {
     EnsureEnabled();
     SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
     SecUtility.CheckParameter(ref username, true, true, true, 0, "username");
     Provider.AddUsersToRoles(new string [] { username }, new string [] { roleName });
     try
     {
         RolePrincipal user = GetCurrentUser() as RolePrincipal;
         if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username))
         {
             user.SetDirty();
         }
     }
     catch { }
 }
Exemple #11
0
        static public bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            EnsureEnabled();
            SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");

            bool roleDeleted = Provider.DeleteRole(roleName, throwOnPopulatedRole);

            try {
                RolePrincipal user = GetCurrentUser() as RolePrincipal;
                if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && user.IsInRole(roleName))
                {
                    user.SetDirty();
                }
            }
            catch { }

            return(roleDeleted);
        }
Exemple #12
0
 public static void RemoveUserFromRoles(string username, string[] roleNames)
 {
     EnsureEnabled();
     SecUtility.CheckParameter(ref username, true, true, true, 0, "username");
     SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 0, "roleNames");
     Provider.RemoveUsersFromRoles(new string[] { username }, roleNames);
     try
     {
         RolePrincipal currentUser = GetCurrentUser() as RolePrincipal;
         if (((currentUser != null) && (currentUser.ProviderName == Provider.Name)) && (currentUser.IsRoleListCached && System.Web.Util.StringUtil.EqualsIgnoreCase(currentUser.Identity.Name, username)))
         {
             currentUser.SetDirty();
         }
     }
     catch
     {
     }
 }
Exemple #13
0
        private void OnLeave(object source, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            if (((Roles.Enabled && Roles.CacheRolesInCookie) && !context.Response.HeadersWritten) && (((context.User != null) && (context.User is RolePrincipal)) && context.User.Identity.IsAuthenticated))
            {
                if (Roles.CookieRequireSSL && !context.Request.IsSecureConnection)
                {
                    if (context.Request.Cookies[Roles.CookieName] != null)
                    {
                        Roles.DeleteCookie();
                    }
                }
                else
                {
                    RolePrincipal user = (RolePrincipal)context.User;
                    if (user.CachedListChanged && context.Request.Browser.Cookies)
                    {
                        string str = user.ToEncryptedTicket();
                        if (string.IsNullOrEmpty(str) || (str.Length > 0x1000))
                        {
                            Roles.DeleteCookie();
                        }
                        else
                        {
                            HttpCookie cookie = new HttpCookie(Roles.CookieName, str)
                            {
                                HttpOnly = true,
                                Path     = Roles.CookiePath,
                                Domain   = Roles.Domain
                            };
                            if (Roles.CreatePersistentCookie)
                            {
                                cookie.Expires = user.ExpireDate;
                            }
                            cookie.Secure = Roles.CookieRequireSSL;
                            context.Response.Cookies.Add(cookie);
                        }
                    }
                }
            }
        }
		void WordUpEntities_SendingRequest (object sender, System.Data.Services.Client.SendingRequestEventArgs e)
			{
			NetworkCredential Creds = this.Credentials as NetworkCredential;
			String UserName = Thread.CurrentPrincipal.Identity.Name;
			RolePrincipal PrRolePrincipal = new RolePrincipal (Thread.CurrentPrincipal.Identity);
			String [] AllRoles = PrRolePrincipal.GetRoles ();
			String AuthenticationType = Thread.CurrentPrincipal.Identity.AuthenticationType;

			((HttpWebRequest) e.Request).CookieContainer
				= ((ClientFormsIdentity) Thread.CurrentPrincipal.Identity).AuthenticationCookies;

//            foreach (Object TestCookie in ((HttpWebRequest) e.Request).CookieContainer.GetCookies (this.BaseUri))
//                {
//                }
////			((HttpWebRequest) e.Request).Credentials = CredentialCache.DefaultNetworkCredentials;
//            //String AuthCookie = GetCookie ("Heinz", "monika").Replace (".ASPXAUTH=", "");
//            //((HttpWebRequest) e.Request).Headers.Add (".ASPXAUTH", AuthCookie);
//            ((HttpWebRequest) e.Request).PreAuthenticate = true;
//            List<String> Headers = new List<string> ();
//            foreach (String Key in ((HttpWebRequest) e.Request).Headers.AllKeys)
//                {
//                Headers.Add (Key + " = " + ((HttpWebRequest) e.Request).Headers [Key].ToString());
//                }
			}
Exemple #15
0
		void OnPostAuthenticateRequest (object sender, EventArgs args)
		{
			HttpApplication app = (HttpApplication)sender;

			/* if we're disabled, bail out early */
			if (_config == null || !_config.Enabled)
				return;

			/* allow the user to populate the Role */
			RoleManagerEventHandler eh = events [getRolesEvent] as RoleManagerEventHandler;
			if (eh != null) {
				RoleManagerEventArgs role_args = new RoleManagerEventArgs (app.Context);

				eh (this, role_args);

				if (role_args.RolesPopulated)
					return;
			}

			RolePrincipal principal;

			HttpCookie cookie = app.Request.Cookies [_config.CookieName];

			IIdentity currentIdentity = app.Context.User.Identity;
			if (app.Request.IsAuthenticated) {
				if (cookie != null) {
					if (!_config.CacheRolesInCookie)
						cookie = null;
					else if (_config.CookieRequireSSL && !app.Request.IsSecureConnection) {
						cookie = null;
						ClearCookie (app, _config.CookieName);
					}
						
				}

				if (cookie == null || String.IsNullOrEmpty (cookie.Value))
					principal = new RolePrincipal (currentIdentity);
				else
					principal = new RolePrincipal (currentIdentity, cookie.Value);
			}
			else {
				/* anonymous request */

				if (cookie != null) {
					ClearCookie (app, _config.CookieName);
				}

				principal = new RolePrincipal (currentIdentity);
			}

			app.Context.User = principal;
			Thread.CurrentPrincipal = principal;
		}
 public RoleClaimProvider(RolePrincipal rolePrincipal, ClaimsIdentity subject)
 {
     _rolePrincipal  = rolePrincipal;
     _subject        = subject;
 }
        void OnPostAuthenticateRequest(object sender, EventArgs args)
        {
            HttpApplication app = (HttpApplication)sender;

            /* if we're disabled, bail out early */
            if (_config == null || !_config.Enabled)
            {
                return;
            }

            /* allow the user to populate the Role */
            RoleManagerEventHandler eh = events [getRolesEvent] as RoleManagerEventHandler;

            if (eh != null)
            {
                RoleManagerEventArgs role_args = new RoleManagerEventArgs(app.Context);

                eh(this, role_args);

                if (role_args.RolesPopulated)
                {
                    return;
                }
            }

            RolePrincipal principal;

            HttpCookie cookie = app.Request.Cookies [_config.CookieName];

            IIdentity currentIdentity = app.Context.User.Identity;

            if (app.Request.IsAuthenticated)
            {
                if (cookie != null)
                {
                    if (!_config.CacheRolesInCookie)
                    {
                        cookie = null;
                    }
                    else if (_config.CookieRequireSSL && !app.Request.IsSecureConnection)
                    {
                        cookie = null;
                        ClearCookie(app, _config.CookieName);
                    }
                }

                if (cookie == null || String.IsNullOrEmpty(cookie.Value))
                {
                    principal = new RolePrincipal(currentIdentity);
                }
                else
                {
                    principal = new RolePrincipal(currentIdentity, cookie.Value);
                }
            }
            else
            {
                /* anonymous request */

                if (cookie != null)
                {
                    ClearCookie(app, _config.CookieName);
                }

                principal = new RolePrincipal(currentIdentity);
            }

            app.Context.User        = principal;
            Thread.CurrentPrincipal = principal;
        }
        void OnEndRequest(object sender, EventArgs args)
        {
            HttpApplication app = (HttpApplication)sender;

            /* if we're not enabled or configured to cache
             * cookies, bail out */
            if (_config == null || !_config.Enabled || !_config.CacheRolesInCookie)
            {
                return;
            }

            /* if the user isn't authenticated, bail
             * out */
            if (!app.Request.IsAuthenticated)
            {
                return;
            }

            /* if the configuration requires ssl for
             * cookies and we're not on an ssl connection,
             * bail out */
            if (_config.CookieRequireSSL && !app.Request.IsSecureConnection)
            {
                return;
            }

            RolePrincipal principal = app.Context.User as RolePrincipal;

            if (principal == null) /* just for my sanity */
            {
                return;
            }

            if (!principal.CachedListChanged)
            {
                return;
            }

            string ticket = principal.ToEncryptedTicket();

            if (ticket == null || ticket.Length > 4096)
            {
                ClearCookie(app, _config.CookieName);
                return;
            }

            HttpCookie cookie = new HttpCookie(_config.CookieName, ticket);

            cookie.HttpOnly = true;
            if (!string.IsNullOrEmpty(_config.Domain))
            {
                cookie.Domain = _config.Domain;
            }
            if (_config.CookieRequireSSL)
            {
                cookie.Secure = true;
            }
            if (_config.CookiePath.Length > 1) // more than '/'
            {
                cookie.Path = _config.CookiePath;
            }
            app.Response.SetCookie(cookie);
        }
Exemple #19
0
 public CustomPrincipal(string CPF, RolePrincipal roles)
 {
     this.Identity = new GenericIdentity(CPF);
     this.Roles = roles;
 }
		public void Contructor_Identity_Null ()
		{
			RolePrincipal rp = new RolePrincipal (null);
		}
Exemple #21
0
        public static String [] CheckUser (ref String UserName)
            {
            int RetryCounter = 0;
            while (RetryCounter < 5)
                {
                try
                    {
                    CheckServiceUris ();
                    bool Return = false;
                    String MainModuleName =
                        System.IO.Path.GetFileNameWithoutExtension (Basics.GetCurrentProcessNamePure ());
                    if (Clipboard.ContainsText (TextDataFormat.UnicodeText))
                        {
                        Object ClipboardContent = Clipboard.GetData (DataFormats.UnicodeText);
                        if (((String) ClipboardContent).IndexOf (MainModuleName + "_WPMediaStartWith;") != -1)
                            {
                            String [] ExternalCredentials = ((String) ClipboardContent).Split (';');
                            if (ExternalCredentials.Length > 3)
                                {
                                Return = Membership.ValidateUser (ExternalCredentials [1], ExternalCredentials [2]);
                                }
                            if (Return)
                                {
                                WMB.WPMediaApplicationState.Instance.Properties ["CommunicationMutexName"] = ExternalCredentials [3];
                                Clipboard.Clear ();
                                }
                            }
                        else
                            {
                            Return = Membership.ValidateUser(String.Empty, String.Empty);
                            }
                        }
                    else
                        {
                        Return = Membership.ValidateUser(String.Empty, String.Empty);
                        }
                    if (!Return)
                        {
                        return null;
                        }
                    RetryCounter = 10;
                    }
                catch (Exception Excp)
                    {
                    Basics.ReportErrorToEventViewer ("CVM.LoginHandler.CheckUser", "Fehler beim Logon\r\n"
                                                                                   + Excp.ToString());
                    MessageBox.Show ("Fehler beim " + Convert.ToString (++RetryCounter) + ". LogonVersuch\r\n"
                                     + "Bitte versuchen Sie es noch einmal\r\n");
                    if (RetryCounter > 3)
                        {
                        MessageBox.Show ("Fehler beim " + Convert.ToString (++RetryCounter) + ". LogonVersuch\r\n"
                                         + "es scheint Verbindungsprobleme zu geben,\r\n"
                                         + "Bitte versuchen Sie es etwas später noch einmal\r\n");
                        return null;
                        }
                    }
                }
            UserName = Thread.CurrentPrincipal.Identity.Name;
            Roles.ApplicationName = Membership.ApplicationName;

            String [] AllRoles = null;
            RolePrincipal RPRolePrincipal = new RolePrincipal (Thread.CurrentPrincipal.Identity);
            try
                {
                AllRoles = RPRolePrincipal.GetRoles ();
                CreateSecurityToken (UserName);
                return AllRoles;

                }
            catch (Exception Excp)
                {
                Basics.ReportErrorToEventViewer ("CVM.LoginHandler.CheckUser", "Fehler beim GetRoles\r\n"
                                                                               + Excp.ToString());
                return null;
                }
            }
 public RoleClaimProvider(RolePrincipal rolePrincipal, ClaimsIdentity subject)
 {
     _rolePrincipal = rolePrincipal;
     _subject       = subject;
 }
        /// <summary>
        /// Authenticate l'utilisateur
        /// </summary>
        /// <param name="userName">Pseudo</param>
        /// <param name="userPassword">Mot de Passe</param>
        /// <returns>True si l'operation success</returns>
        /// <exception cref="SecurityException">CAN_NOT_FIND_USER</exception>
        public bool Authenticate(string userName, string userPassword)
        {
            //foreach (var user in Membership.GetAllUsers())
            //    Membership.DeleteUser(user.ToString());


            if (Membership.GetAllUsers().Count == 0)
            {
                MembershipCreateStatus status;
                Membership.CreateUser(
                    "admin",
                    "admin00.",
                    "*****@*****.**",
                    "admin",
                    "admin",
                    true,
                    new Guid("53f258a3-f931-4975-b6ec-17d26aa95848"),
                    out status);
                if (status == MembershipCreateStatus.Success)
                {
                    using (var db = new StationContext())
                    {
                        var shadow = new Staff
                        {
                            StaffGuid = new Guid("53f258a3-f931-4975-b6ec-17d26aa95848"),
                            Person = new Person
                            {
                                PersonGuid = Guid.NewGuid(),
                                FirstName = "Admin",
                                LastName = "Admin"
                            }
                        };
                        if (db.Staffs.Find(new Guid("53f258a3-f931-4975-b6ec-17d26aa95848")) == null)
                            db.Staffs.Add(shadow);
                        db.SaveChanges();

                        foreach (var adminClear in Enum.GetValues(typeof(AdminClearances)).Cast<object>().Where(adminClear => !Roles.RoleExists(adminClear.ToString())))
                            Roles.CreateRole(adminClear.ToString());

                        foreach (var adminClear in Enum.GetValues(typeof(AdminClearances)).Cast<object>().Where(adminClear => !Roles.IsUserInRole("admin", adminClear.ToString())))
                            Roles.AddUserToRole("admin", adminClear.ToString());

                        if (!Roles.RoleExists(UserSpace.AdminSpace.ToString()))
                            Roles.CreateRole(UserSpace.AdminSpace.ToString());

                        if (!Roles.IsUserInRole("admin", UserSpace.AdminSpace.ToString()))
                            Roles.AddUserToRole("admin", UserSpace.AdminSpace.ToString());

                    }
                }
            }


            try
            {
                if (!Membership.ValidateUser(userName, userPassword))
                    return false;

                var user = Membership.GetUser(userName);
                if (user == null)
                    throw new SecurityException("CAN_NOT_FIND_USER");

                var identity = new GenericIdentity(user.UserName);
                var principal = new RolePrincipal(identity);
                Thread.CurrentPrincipal = principal;
                return true;
            }
            catch (SqlException sqlException)
            {
                DebugHelper.WriteException(sqlException);
                throw;
            }
            catch (Exception ex)
            {
                DebugHelper.WriteException(ex);
                return false;
            }
            //try
            //{
            //    //foreach (var allUser in Membership.GetAllUsers())
            //    //    Membership.DeleteUser(allUser.ToString());

            //    //using (var db = new StationContext())
            //    //{
            //    //    if (db.Database.Exists())
            //    //    {
            //    //        db.Database.Delete();
            //    //        db.Database.Create();
            //    //    }
            //    //}

            //    if (!Membership.ValidateUser(userName, userPassword))
            //        {
            //            if (Membership.GetAllUsers().Count != 0) return false;
            //            MembershipCreateStatus status;
            //            Membership.CreateUser(
            //                "admin",
            //                "admin00.",
            //                "*****@*****.**",
            //                "admin",
            //                "admin",
            //                true,
            //                new Guid("53f258a3-f931-4975-b6ec-17d26aa95848"),
            //                out status);
            //            if (status != MembershipCreateStatus.Success) return false;
            //            Roles.CreateRole(AdminClearances.SuperUser.ToString());
            //            Roles.CreateRole(AdminClearances.StaffWrite.ToString());
            //            Roles.CreateRole(UserSpace.AdminSpace.ToString());

            //            Roles.AddUserToRole("admin", AdminClearances.SuperUser.ToString());
            //            Roles.AddUserToRole("admin", AdminClearances.StaffWrite.ToString());
            //            Roles.AddUserToRole("admin", UserSpace.AdminSpace.ToString());
            //            return false;
            //        }

            //    var user = Membership.GetUser(userName);
            //    if (user == null)
            //        throw new SecurityException("CAN_NOT_FIND_USER");

            //    var identity = new GenericIdentity(user.UserName);
            //    var principal = new RolePrincipal(identity);
            //    Thread.CurrentPrincipal = principal;
            //    return true;
            //}
            //catch (SqlException sqlException)
            //{
            //    DebugHelper.WriteException(sqlException);
            //    throw;
            //}
            //catch (Exception ex)
            //{
            //    DebugHelper.WriteException(ex);
            //    return false;
            //}
        }
Exemple #24
0
        private void InitFromEncryptedTicket(string encryptedTicket)
        {
            if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null)
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest);
            }

            if (string.IsNullOrEmpty(encryptedTicket))
            {
                goto Exit;
            }

            byte[] bTicket = CookieProtectionHelper.Decode(Roles.CookieProtectionValue, encryptedTicket, Purpose.RolePrincipal_Ticket);
            if (bTicket == null)
            {
                goto Exit;
            }

            RolePrincipal rp = null;
            MemoryStream  ms = null;

            try{
                ms = new System.IO.MemoryStream(bTicket);
                rp = (new BinaryFormatter()).Deserialize(ms) as RolePrincipal;
            } catch {
            } finally {
                ms.Close();
            }
            if (rp == null)
            {
                goto Exit;
            }
            if (!StringUtil.EqualsIgnoreCase(rp._Username, _Identity.Name))
            {
                goto Exit;
            }
            if (!StringUtil.EqualsIgnoreCase(rp._ProviderName, _ProviderName))
            {
                goto Exit;
            }
            if (DateTime.UtcNow > rp._ExpireDate)
            {
                goto Exit;
            }

            _Version           = rp._Version;
            _ExpireDate        = rp._ExpireDate;
            _IssueDate         = rp._IssueDate;
            _IsRoleListCached  = rp._IsRoleListCached;
            _CachedListChanged = false;
            _Username          = rp._Username;
            _Roles             = rp._Roles;



            // will it be the case that _Identity.Name != _Username?

            RenewIfOld();

            if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null)
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", _Identity.Name);
            }

            return;

Exit:
            Init();
            _CachedListChanged = true;
            if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null)
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", _Identity.Name);
            }
            return;
        }
 public KeyValueList SignIn(string username, string password)
 {
     string errorMessage = string.Empty;
     if (password.Length == 0) errorMessage = "Please enter password";
     if (username.Length == 0) errorMessage = "Please enter user name";
     if (errorMessage.Length == 0)
     {
         // Here must be validation with password. You can add third party validation here;
         bool success = Membership.ValidateUser(username, password);
         if (!success) errorMessage = "Validation failed. User name '" + username + "' was not found.";
     }
     var results = new KeyValueList();
     if (errorMessage.Length > 0)
     {
         results.Add("Status", false);
         results.Add("Message", errorMessage);
     }
     else
     {
         FormsAuthentication.Initialize();
         var user = Membership.GetUser(username, true);
         if (user == null)
         {
             results.Add("Status", false);
             results.Add("Message", "'" + username + "' was not found.");
         }
         else
         {
             var roles = Roles.GetRolesForUser(username);
             string rolesString = string.Empty;
             for (int i = 0; i < roles.Length; i++)
             {
                 if (i > 0) rolesString += ",";
                 rolesString += roles[i];
             }
             var loginRememberMinutes = 30;
             var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
             // Encrypt the cookie using the machine key for secure transport.
             var hash = FormsAuthentication.Encrypt(ticket);
             var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket
             // Set the cookie's expiration time to the tickets expiration time
             if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
             HttpContext.Current.Response.Cookies.Add(cookie);
             // Create Identity.
             var identity = new System.Security.Principal.GenericIdentity(user.UserName);
             // Create Principal.
             var principal = new RolePrincipal(identity);
             System.Threading.Thread.CurrentPrincipal = principal;
             // Create User.
             HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
             results.Add("Status", true);
             results.Add("Message", "Welcome!");
         }
     }
     return results;
 }
		public void Contructor_Identity ()
		{
			RolePrincipal rp = new RolePrincipal (GetGenericIdentity ("me"));
		}
Exemple #27
0
        public static string SetCurrentUser(string username)
        {
            string errorMessage = string.Empty;
            // Initialize FormsAuthentication, for what it's worth.
            FormsAuthentication.Initialize();
            MembershipUser user = Membership.GetUser(username, true);
            if (user == null) errorMessage = "Employee '"+username+"' was not found.";
            if (String.IsNullOrEmpty(errorMessage))
            {
                string[] roles = System.Web.Security.Roles.GetRolesForUser(username);
                string rolesString = string.Empty;
                for (int i = 0; i < roles.Length; i++)
                {
                    if (i > 0) rolesString += ",";
                    rolesString += roles[i];
                }
                // Create a new ticket used for authentication. Ticket lasts 30 min by default.
                double loginRememberMinutes = 30;
                if (SecurityContext.Current.CookieRememberMe)
                {
                    loginRememberMinutes = SecurityContext.Current.LoginRememberMinutes;
                }

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
                // Encrypt the cookie using the machine key for secure transport.
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket
                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                // Create Identity.
                System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity(user.UserName);
                // Create Principal.
                RolePrincipal principal = new RolePrincipal(identity);
                System.Threading.Thread.CurrentPrincipal = principal;
                // Create User.
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
            }
            return errorMessage;
        }