Inheritance: System.Security.Claims.ClaimsIdentity
Esempio n. 1
0
		public void EmptyName () 
		{
			GenericIdentity gi = new GenericIdentity ("");
			Assert.AreEqual (String.Empty, gi.Name, "Name");
			Assert.AreEqual (String.Empty, gi.AuthenticationType, "AuthenticationType");
			Assert.IsFalse (gi.IsAuthenticated, "IsAuthenticated");
		}
        private static void AuthenticateUser(string credentials)
        {
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                if (CheckPassword(name, password))
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
                else
                {
                    // Invalid username or password.
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                HttpContext.Current.Response.StatusCode = 401;
            }
        }
        public void AuthenticateRequest(HttpApplication httpApplication)
        {
            HttpCookie authCookie = httpApplication.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                try
                {
                    var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    if (authTicket != null)
                    {
                        string[] roles = authTicket.UserData.Split('|');

                        var identity = new GenericIdentity(authTicket.Name);
                        var principal = new GenericPrincipal(identity, roles);

                        httpApplication.Context.User = principal;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Failed to authenticate request.", ex);
                    FormsAuthentication.SignOut();
                }
            }
        }
        private static bool AuthenticateUser(string credentials)
        {
            var encoding = Encoding.GetEncoding("iso-8859-1");
            credentials = encoding.GetString(Convert.FromBase64String(credentials));

            var credentialsArray = credentials.Split(':');
            var username = credentialsArray[0];
            var password = credentialsArray[1];

            try
            {
                using (var proxy = new WSUsuario.UsuarioServiceClient())
                {
                    var usuario = proxy.ObtenerUsuarioPorCorreo(username);
                    if (!(usuario != null && usuario.Clave == password))
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HttpException(401, "Unauthorized", ex);
            }

            var identity = new GenericIdentity(username);
            SetPrincipal(new GenericPrincipal(identity, null));

            return true;
        }
        private void ReplacePrincipalWithRoleMappings(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated || Context.User is ApiUserPrincipal) return;

            var username = Context.User.Identity.Name;
            var apiUser = Store.FindByUsername(username);
            var isNew = false;

            if (apiUser == null)
            {
                isNew = true;
                apiUser = new ApiUser {Username = username};
            }

            var origRoles = (apiUser.Roles ?? Empty).ToArray();
            var missingRoles = RoleNames.All.Except(origRoles);
            apiUser.Roles = (origRoles).Union(GetUserRoles(Context.User, missingRoles)).Distinct().ToArray();

            if (isNew || !apiUser.Roles.SequenceEqual(origRoles))
            {
                Store.Add(apiUser, UserUpdateMode.Overwrite);
            }

            var identity = new GenericIdentity(apiUser.Username, typeof(RoleMappingAuthenticationModule).Name);
            Context.User = new GenericPrincipal(identity, apiUser.Roles.ToArray());
        }
        private static bool AuthenticateUser(string credentials)
        {
            var encoding = Encoding.GetEncoding("iso-8859-1");
            credentials = encoding.GetString(Convert.FromBase64String(credentials));
            var credentialsArray = credentials.Split(':');
            var username = credentialsArray[0];
            var password = credentialsArray[1];

            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            var directoryEntry = new DirectoryEntry(Ldap, username, password);
            var searchAdForUser = new DirectorySearcher(directoryEntry) { Filter = "(&(objectClass=user)(anr=" + username + "))" };
            var retrievedUser = searchAdForUser.FindOne();

            if (retrievedUser == null)
            {
                return false;
            }

            var identity = new GenericIdentity(username);
            SetPrincipal(new GenericPrincipal(identity, null));

            return true;
        }
Esempio n. 7
0
        /// <summary>
        /// Handles the AuthenticateRequest event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                try
                {
                    var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    if (authTicket != null)
                    {
                        var identity = new GenericIdentity(authTicket.Name, "Forms");
                        var roles = authTicket.UserData.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToArray();
                        var principal = new GenericPrincipal(identity, roles);
                        Context.User = principal;
                    }
                }
                catch
                {
                    Session.Clear();
                    FormsAuthentication.SignOut();
                }
            }

            cmsHost.OnAuthenticateRequest(this);
        }
Esempio n. 8
0
        public static bool Login( String uname , String pass , out IUserCtx uc)
        {
            String[] roles;
            uc = null;

            // autentykacja (tu następuje sprawdzenie z tablicą user/pass z Bazy Danych)
            if (uname == "Rafal")
            {
                // autoryzacja (tu następuje pobranie z Bazy Danych wszystkich ról do których user należy)
                roles = new String[] { BizzLogic.Operation1Role, BizzLogic.Operation2Role };

            }

            else if (uname == "Atylla")
            {
                roles = new String[] { BizzLogic.Operation2Role };
            }
            else {
                return false;
            }

            UserCtx ucl = new UserCtx(uname);
            foreach (String s in roles)
                ucl.AddOperRole(s);
            uc = ucl;

            GenericIdentity gi = new GenericIdentity(uname);

            GenericPrincipal gp = new GenericPrincipal(gi, roles);

            // przypisanie kontekstu (żeby działał mechanizm)
            Thread.CurrentPrincipal = gp;
            return true;
        }
Esempio n. 9
0
 public void SetUp( BaseTestFixture fixture )
 {
     IIdentity identity=new GenericIdentity( UserName );
     IPrincipal principal=new GenericPrincipal( identity, Groups );
     originalPrincipal=Thread.CurrentPrincipal;
     Thread.CurrentPrincipal=principal;
 }
 static void Main(string[] args)
 {
     GenericIdentity genid = new GenericIdentity("Rafael", "");
     Console.WriteLine(genid.IsAuthenticated.ToString());
     
     Console.ReadKey();
 }
Esempio n. 11
0
        protected void Application_PostAuthenticateRequest()
        {
            var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null || String.IsNullOrWhiteSpace(cookie.Value))
            {
                return;
            }

            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            Guid id;

            if (ticket == null || !Guid.TryParse(ticket.UserData, out id))
            {
                return;
            }

            var db = new EfContext();
            var account = db.Accounts.Find(id);
            if (account == null)
            {
                return;
            }

            var identity = new GenericIdentity(account.Login);
            HttpContext.Current.User = new GenericPrincipal(identity, new string[0]);
        }
Esempio n. 12
0
        void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];

            if (null == authCookie)
            {
                //There is no authentication cookie.
                return;
            }
            FormsAuthenticationTicket authTicket = null;
            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch (Exception ex)
            {
                //Write the exception to the Event Log.
                return;
            }
            if (null == authTicket)
            {
                //Cookie failed to decrypt.
                return;
            }
            //When the ticket was created, the UserData property was assigned a
            //pipe-delimited string of group names.
            string[] groups = authTicket.UserData.Split(new char[] { '|' });
            //Create an Identity.
            GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
            //This principal flows throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, groups);
            Context.User = principal;
        }
 public LeaguePrincipal(int id, string login, string role)
 {
     UserId = id;
     Login = login;
     Role = role;
     Identity = new GenericIdentity(login);
 }
        public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
        {
            var requestProperties =
                (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];

            var rawAuthHeader = requestProperties.Headers["Authorization"];

            AuthenticationHeader authHeader = null;
            if (AuthenticationHeader.TryDecode(rawAuthHeader, out authHeader));
            {
                var identity = new GenericIdentity(authHeader.Username);
                var principal = new GenericPrincipal(identity, new string[] { });

                var httpContext = new HttpContextWrapper(HttpContext.Current)
                {
                    User = principal,
                };

                if (httpContext.User != null)
                    return authPolicy;
            }

            SendUnauthorizedResponse();

            return base.Authenticate(authPolicy, listenUri, ref message);
        }
        static ServiceProviderContext()
        {
            Settings = ConfigurationManager.GetSection("oauth.net.serviceprovider") as ServiceProviderSettings;

            if (!string.IsNullOrEmpty(Settings.DummyIdentity))
                DummyIdentity = new GenericIdentity(Settings.DummyIdentity);
        }
Esempio n. 16
0
        public IPrincipal SignIn(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

            var id = new GenericIdentity(userName);
            return new GenericPrincipal(id, new string[] { });
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authValue = request.Headers.Authorization;
            if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
            {
                string guidStr = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter));

                Guid token;
                if (Guid.TryParse(guidStr, out token))
                {
                    User user;
                    if (this.Table.TryAuthenticateToken(token, out user) && this.AuthenticateUser(request, user))
                    {
                        var identity = new GenericIdentity(token.ToString(), "Token");
                        IPrincipal principal = new GenericPrincipal(identity, new[] { "User" });
                        Thread.CurrentPrincipal = principal;

                        this.SetHttpContextUser(Thread.CurrentPrincipal);
                    }
                }
            }
            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;
                    if (response.StatusCode == HttpStatusCode.Unauthorized
                        && !response.Headers.Contains(AuthResponseHeader))
                    {
                        response.Headers.Add(AuthResponseHeader, TokenAuthResponseHeaderValue);
                    }
                    return response;
                }, cancellationToken);
        }
 public static IPrincipal setThreadPrincipalWithRoles(this string[] userRoles)
 {
     var newIdentity = new GenericIdentity("TM_User"); // note that this needs to be set or the SecurityAction.Demand for roles will not work
     var newPrincipal = new GenericPrincipal(newIdentity, userRoles);
     System.Threading.Thread.CurrentPrincipal = newPrincipal;
     return newPrincipal;
 }
Esempio n. 19
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                // Get the forms authentication ticket.
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new MyPrincipal(identity);

                // Get the custom user data encrypted in the ticket.
                string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;

                // Deserialize the json data and set it on the custom principal.
                var serializer = new JavaScriptSerializer();
                principal.User = (User)serializer.Deserialize(userData, typeof(User));

                // Set the context user.
                Context.User = principal;
            }
            //else
            //{
            //    //string Url = ConfigurationManager.AppSettings["YetkiGirisSayfasi"] + "?ReturnUrl=" + Request.Url.GetLeftPart(UriPartial.Path).Replace("http:", "http://").Replace("////", "//") + "&UN=" + ConfigurationManager.AppSettings["YetkiProjeUN"];
            //    string Url = ConfigurationManager.AppSettings["YetkiGirisSayfasi"] + "?ReturnUrl=http://localhost:25468/IsEmri"+"&UN=" + ConfigurationManager.AppSettings["YetkiProjeUN"];
            //    Response.Redirect(Url, true);
            //}
        }
Esempio n. 20
0
        public CustomPrincipal(string username, string email, bool administrator, Employee employee, IList<AccessPrivilege> privileges)
        {
            Employee = employee;
            Email = email;
            IsAdministrator = administrator;
            Identity = new GenericIdentity (username);

            if (privileges == null) {
                Roles = new string [0];
            } else {
                var items = new List<string> (privileges.Count);

                foreach (var p in privileges) {
                    if (p.AllowCreate) {
                        items.Add (p.Object + ".Create");
                    }

                    if (p.AllowRead) {
                        items.Add (p.Object + ".Read");
                    }

                    if (p.AllowUpdate) {
                        items.Add (p.Object + ".Update");
                    }

                    if (p.AllowDelete) {
                        items.Add (p.Object + ".Delete");
                    }
                }

                Roles = items.ToArray ();
            }
        }
Esempio n. 21
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!this.enableHack)
            {
                return;
            }

            string clientIp = filterContext.HttpContext.Request.UserHostAddress;
            if (!ipList.Contains(clientIp))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Headers["ApiHack-UserName"]) ||
                string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Headers["ApiHack-Groups"]))
            {
                return;
            }

            var username = filterContext.HttpContext.Request.Headers["ApiHack-UserName"];
            var groups = filterContext.HttpContext.Request.Headers["ApiHack-Groups"].Split(';');

            var identity = new GenericIdentity(username, "Basic");
            var principal = new GenericPrincipal(identity, groups);
            filterContext.HttpContext.User = principal;
            Thread.CurrentPrincipal = principal;

            base.OnAuthorization(filterContext);
        }
Esempio n. 22
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

            if ((authCookie != null)  && (!filterContext.HttpContext.Session.IsNewSession) )
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new GenericPrincipal(identity, new string[] { authTicket.UserData });
                filterContext.HttpContext.User = principal;
            }

            var Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var Action = filterContext.ActionDescriptor.ActionName;
            var User = filterContext.HttpContext.User;

            var IP = filterContext.HttpContext.Request.UserHostAddress;

            var isAccessAllowed = ACL.IsAccessAllowed(Controller, Action, User, IP);
            if (!isAccessAllowed)
            {
                //FormsAuthentication.RedirectToLoginPage();
                filterContext.HttpContext.Response.Redirect("/Pages/Login", true);

               // filterContext.Result = new HttpUnauthorizedResult();
               // return;
            }
        }
Esempio n. 23
0
        private void AuthenticateUser(string credentials)
        {
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));
                log.DebugFormat("Credenciales: {0}", credentials);
                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                if (CheckPassword(name, password))
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
                else
                {
                    log.DebugFormat("Credenciales invalidas {0}", credentials);
                    // Datos invalidos
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }
            catch (FormatException e)
            {
                // No se enviaron correctamente las credenciales
                log.Debug("Error en credenciales", e);
                HttpContext.Current.Response.StatusCode = 401;
            }
        }
 public static GenericPrincipal AgentGenericPrincipal()
 {
     //AgentId = 1,
     var ident = new GenericIdentity("mike");
     var principal = new GenericPrincipal(ident, new[] { LookUpRoles.AgentRole });
     return principal;
 }
Esempio n. 25
0
        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (Context.User == null ) {

                    String cookieName = FormsAuthentication.FormsCookieName;
                    HttpCookie authCookie = Context.Request.Cookies[cookieName];

                    if(null == authCookie) {
                        //There is no authentication cookie.
                        return;
                    }
                    FormsAuthenticationTicket authTicket = null;
                    try {
                        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    }
                    catch (Exception ex) {
                        //Write the exception to the Event Log.
                        return;
                    }
                    if(null == authTicket) {
                        //Cookie failed to decrypt.
                        return;
                    }

                    string[] loginType = authTicket.UserData.Split(new char[]{','});;
                    GenericIdentity id = new GenericIdentity(authTicket.Name, "webAuth");
                    //This principal flows throughout the request.
                    GenericPrincipal principal = new GenericPrincipal(id, loginType);
                    Context.User = principal;

                }
                 //Context.User = (System.Security.Principal.IPrincipal)System.Security.Principal.WindowsIdentity.GetCurrent();
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
            else
            {
                string authToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

                String [] u = checkToken(decodedToken);

                if (u != null)
                {
                    GenericIdentity genericIdentity = new GenericIdentity(u[0] + " " + u[1],"");
                    HttpContext.Current.User = new GenericPrincipal(genericIdentity, new string[] { });
                    base.OnActionExecuting(actionContext);
                }

                else
                {
                    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                }
            }
        }
Esempio n. 27
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (UserBAL userBAL = new UserBAL(ContextInfo))
            {
                userBAL.Login(model);
            }
            if (model.HasErrorByType())
            {
                return(View(model));
            }

            ApplicationUser user = await UserManager.FindByNameAsync(model.UserName);

            await SignInManager.SignInAsync(user, model.RememberMe, model.RememberMe);

            System.Security.Principal.GenericIdentity genericIdentity = new System.Security.Principal.GenericIdentity(user.UserName, "ApplicationCookie");
            string[] roles = user.Roles.Select(x => x.RoleId).ToArray();
            System.Security.Principal.GenericPrincipal genericPrincipal = new GenericPrincipal(genericIdentity, user.Roles.Select(x => x.RoleId).ToArray());

            return(RedirectToLocal(returnUrl, genericPrincipal));

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
        }
		public API_Moq_HttpContext setupNormalRequestValues()		
		{							        
	        var genericIdentity = new GenericIdentity("genericIdentity");
	        var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] {});
			MockContext.Setup(context => context.User).Returns(genericPrincipal);	     	
	     	MockContext.Setup(context => context.Cache).Returns(HttpRuntime.Cache);
			MockContext.Setup(context => context.Server.MapPath(It.IsAny<string>())).Returns((string path) =>  this.BaseDir.pathCombine(path));
			
	     	//Request
	     	MockRequest.Setup(request =>request.InputStream	).Returns(new MemoryStream()); 
	     	MockRequest.Setup(request =>request.Headers		).Returns(new NameValueCollection()); 
	     	MockRequest.Setup(request =>request.QueryString	).Returns(new NameValueCollection()); 
	     	MockRequest.Setup(request =>request.Form		).Returns(new NameValueCollection()); 
	     	
	     	//Response
	     	var outputStream = new MemoryStream();
	     	MockResponse.Setup(response =>response.OutputStream).Returns(outputStream); 
	     	
	     	//var writer = new StringWriter();
//			context.Expect(ctx => ctx.Response.Output).Returns(writer);
	     	
	     	MockResponse.Setup(response =>response.Write(It.IsAny<string>())).Callback((string code) => outputStream.Write(code.asciiBytes(), 0, code.size()));
	     	var cache = new Mock<HttpCachePolicyBase>();
            MockResponse.SetupGet(response => response.Cache).Returns(cache.Object);
	     	return this;
		}
        private static bool AuthenticateUser(string credentials)
        {
            bool validated = false;
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                validated = CheckPassword(name, password);
                if (validated)
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                validated = false;

            }
            return validated;
        }
Esempio n. 30
0
 /// <summary>
 /// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with
 /// a new role identified in constructor.
 /// </summary>
 /// <param name="methodUnderTest">The method under test</param>
 public override void Before(MethodInfo methodUnderTest)
 {
     originalPrincipal = Thread.CurrentPrincipal;
     GenericIdentity identity = new GenericIdentity("xUnit");
     GenericPrincipal principal = new GenericPrincipal(identity, new string[] { name });
     Thread.CurrentPrincipal = principal;
 }
Esempio n. 31
0
		public void NameAuthenticationType () 
		{
			GenericIdentity gi = new GenericIdentity ("user", "blood oath");
			Assert.AreEqual ("user", gi.Name, "Name");
			Assert.AreEqual ("blood oath", gi.AuthenticationType, "AuthenticationType");
			Assert.IsTrue (gi.IsAuthenticated, "IsAuthenticated");
		}
        public void RunBeforeEachTest()
        {
            System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity("unittest\\user", "UnitTestAuth");

            System.Security.Principal.GenericPrincipal gp = new System.Security.Principal.GenericPrincipal(identity, new string[] { "FirstRole", "ThirdRole" });

            System.Threading.Thread.CurrentPrincipal = gp;
        }
Esempio n. 33
0
        public SharpZipHelper()
        {
            FormsAuthenticationModule module = new FormsAuthenticationModule();

            module.Authenticate += new FormsAuthenticationEventHandler(module_Authenticate);
            FormsAuthenticationTicket ticket   = new FormsAuthenticationTicket("acheng", true, 20);
            FormsIdentity             identity = new FormsIdentity(ticket);

            System.Security.Principal.GenericIdentity gIdentity = new System.Security.Principal.GenericIdentity("acheng", "generic");
            GenericPrincipal pricipal = new GenericPrincipal(gIdentity, new string[] { "admin", "superadmin" });
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //prevent login to the not confirmed email
            //by moh said 26/9/2020
            var user = await UserManager.FindByEmailAsync(model.Email);

            //if  we want ID direct [var userid = UserManager.FindByEmail(model.Email).Id;]
            if (user == null)
            {
                return(View("EmailNotExist_moh"));
                //return RedirectToAction("EmailNotExist_moh", "Account"); //لازم وجود function
            }
            else if (!UserManager.IsEmailConfirmed(user.Id))
            {
                return(View("EmailNotConfirmed_moh"));
                //return RedirectToAction("RegisterConfirmation_moh", "Account");
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                ///////////add by Baker in 14/11/2020
                var identity  = new System.Security.Principal.GenericIdentity(user.UserName);
                var principal = new GenericPrincipal(identity, new string[0]);
                System.Web.HttpContext.Current.User = principal;
                Thread.CurrentPrincipal             = principal;
                Helper.MigrateCart(user.Id);
                //////////////
                return(RedirectToLocal(returnUrl));
            }

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            var identity = new System.Security.Principal.GenericIdentity("Sima");

            Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(identity, new[] { "administrator" });

            Console.WriteLine("Hello World!");

            var t = TestRpcServer();

            var t2 = Task.Run(TestRpcClient);

            Task.WaitAll(t, t2);
        }
Esempio n. 36
0
        public ActionResult SetLogin(AdminUser usr)
        {
            if (!string.IsNullOrEmpty(usr.UserName) && !string.IsNullOrEmpty(usr.UserPassword))
            {
                if (this.IsCaptchaValid("Captcha is not valid"))
                {
                    bool result = false;
                    usr.UserRole = "Admin";
                    string userName = ConfigurationManager.AppSettings["AdminUser"].Trim();
                    string userpwd  = ConfigurationManager.AppSettings["AdminPwd"].Trim();
                    if (usr.UserName.ToUpper().Trim() == userName.Trim().ToUpper() &&
                        usr.UserPassword.ToUpper().Trim() == userpwd.Trim().ToUpper())
                    {
                        result = true;
                    }

                    if (result)
                    {
                        var identity  = new System.Security.Principal.GenericIdentity(usr.UserName);
                        var principal = new GenericPrincipal(identity, new string[0]);
                        HttpContext.User        = principal;
                        Thread.CurrentPrincipal = principal;

                        string loggedUser = HttpContext.User.Identity.Name;
                        System.Web.Security.FormsAuthentication.SetAuthCookie(loggedUser, false);
                        var name   = System.Web.Security.FormsAuthentication.FormsCookieName;
                        var cookie = Response.Cookies[name];
                        if (cookie != null)
                        {
                            var ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value);
                            if (ticket != null && !ticket.Expired)
                            {
                                string[] roles = (ticket.UserData as string ?? "").Split(',');
                                System.Web.HttpContext.Current.User = new GenericPrincipal(new System.Web.Security.FormsIdentity(ticket), roles);
                            }
                        }
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        TempData["failedMessage"] = "Successfully Login Profile has been set for TCA Mobile Application";
                        return(RedirectToAction("LoginFailed"));
                    }
                }
            }

            ViewBag.ErrMessage = "Error: captcha is not valid.";
            return(View(usr));
        }
Esempio n. 37
0
        public async Task <ResultVM> Login([FromBody] LoginVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.UserName);

                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    var identity = new ClaimsIdentity("Cookies");
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                    identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
                    var ceva = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync("Cookies", ceva);

                    var identitySecurity = new System.Security.Principal.GenericIdentity(user.UserName);
                    var principal        = new GenericPrincipal(identitySecurity, new string[0]);
                    HttpContext.User = principal;

                    var flag = HttpContext.User.Identity.IsAuthenticated;
                    return(new ResultVM
                    {
                        Status = Status.Success,
                        Message = "Succesfull login",
                        Data = model
                    });
                }

                return(new ResultVM
                {
                    Status = Status.Error,
                    Message = "Invalid data",
                    Data = "<li> Invalid Username or Password </li>"
                });
            }

            var errors = ModelState.Keys.Select(e => "<li>" + e + "</li>");

            return(new ResultVM
            {
                Status = Status.Error,
                Message = "Invalid data",
                Data = string.Join("", errors)
            });
        }
Esempio n. 38
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var identity = new System.Security.Principal.GenericIdentity("Me");
            // in this dummy authentication scheme, we assume that the permissions granted
            // to the user are stored as a comma-separate list in a header called Permissions
            var scopeValues = Request.Headers["Permissions"];

            if (scopeValues.Count != 0)
            {
                var scopes = scopeValues.ToArray()[0].Split(",").Select(s => s.Trim());
                var claims = scopes.Select(scope => new Claim("Permission", scope));
                identity.AddClaims(claims);
            }

            var principal = new GenericPrincipal(identity, Array.Empty <string>());
            // we use the same auhentication scheme as the one specified in the OData model permissions
            var ticket = new AuthenticationTicket(principal, "AuthScheme");

            return(Task.FromResult(AuthenticateResult.Success(ticket)));
        }
Esempio n. 39
0
        private static void AuthenticateUser(string credentials)
        {
            try
            {
                var encoding = System.Text.Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int    separator = credentials.IndexOf(':');
                string name      = credentials.Substring(0, separator);
                string password  = credentials.Substring(separator + 1);

                if (CheckPassword(name, password))
                {
                    var identity = new System.Security.Principal.GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
                else
                {
                    // Invalid username or password.
                    dynamic Response = new System.Dynamic.ExpandoObject();
                    Response.success    = false;
                    Response.error_code = HttpStatusCode.Unauthorized;
                    Response.error_msg  = "Not authorized";
                    var json = new JavaScriptSerializer().Serialize(Response);
                    HttpContext.Current.Response.Output.Write(json);
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                dynamic Response = new System.Dynamic.ExpandoObject();
                Response.success    = false;
                Response.error_code = HttpStatusCode.Unauthorized;
                Response.error_msg  = "Not authorized";
                // Invalid username or password.
                var json = new JavaScriptSerializer().Serialize(Response);
                HttpContext.Current.Response.Output.Write(json);
                HttpContext.Current.Response.StatusCode = 401;
            }
        }
Esempio n. 40
0
 /// <summary>Initializes a new instance of the <see cref="T:System.Security.Principal.GenericIdentity" /> class by using the specified <see cref="T:System.Security.Principal.GenericIdentity" /> object.</summary><param name="identity">The object from which to construct the new instance of <see cref="T:System.Security.Principal.GenericIdentity" />.</param>
 protected GenericIdentity(GenericIdentity identity)
 {
     throw new NotImplementedException();
 }
Esempio n. 41
0
 /// <summary>使用指定的 <see cref="T:System.Security.Principal.GenericIdentity" /> 对象初始化 <see cref="T:System.Security.Principal.GenericIdentity" /> 类的新实例。</summary>
 /// <param name="identity">根据其构造 <see cref="T:System.Security.Principal.GenericIdentity" /> 新实例的对象。</param>
 protected GenericIdentity(GenericIdentity identity)
     : base((ClaimsIdentity)identity)
 {
     this.m_name = identity.m_name;
     this.m_type = identity.m_type;
 }
Esempio n. 42
0
 protected GenericIdentity(GenericIdentity identity)
     : base(identity)
 {
 }
Esempio n. 43
0
 protected GenericIdentity(GenericIdentity identity)
     : base(identity)
 {
     m_name = identity.m_name;
     m_type = identity.m_type;
 }