Inheritance: System.Security.Claims.ClaimsPrincipal
        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;
            var credentials = app.Context.Request.Headers["Authorization"];
            if (string.IsNullOrEmpty(credentials)) return;
            //var userPassword = System.Convert.FromBase64String(credentials);
            //var userString = (new System.Text.UTF8Encoding()).GetString(userPassword);
            var encodedPassword = AuthenticationHeaderValue.Parse(credentials).Parameter;
            var userPassword = new System.Text.UTF8Encoding().GetString(System.Convert.FromBase64String(encodedPassword));
            var passwordParts = userPassword.Split(':');
            var userName = passwordParts[0];
            var password = passwordParts[1];

            if (!WebSecurity.Initialized)
                throw new System.ApplicationException("WebSecurity database became unitialized");
            if (Membership.Provider.ValidateUser(userName, password))
            {
                var identity = new BasicIdentity(userName);
                var roles = Roles.Provider.GetRolesForUser(userName);
                var principal = new GenericPrincipal(identity, roles);

                app.Context.User = principal;
                if (HttpContext.Current != null)
                    HttpContext.Current.User = principal;

            }
        }
        private ActionResult RedirectToLocal(string returnUrl, System.Security.Principal.GenericPrincipal tempPrincipal = null)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                if (tempPrincipal != null && tempPrincipal.HasAccessToNode(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
            }

            if (tempPrincipal != null)
            {
                if (tempPrincipal.HasAccessToNode(Url.Action("Index", "Home")))
                {
                    RedirectToAction("Index", "Home");
                }

                List <string> allowdNodesKeys = tempPrincipal.GetAuthorizedNodesList(MvcSiteMapProvider.SiteMaps.Current.RootNode, false);
                if (allowdNodesKeys.Count() > 0)
                {
                    return(Redirect(SiteMapHelper.GetUrlByKey(allowdNodesKeys.First())));
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
        protected void Application_AuthenticateRequest()
        {
            if (Context.User == null)
            {
                return;
            } //Exit if the userObj = null

            //get the current user reference
            string emailAddress = Context.User.Identity.Name;

            string[] roles = new string[1];

            using (WSADDbContext context = new WSADDbContext())
            {
                //get the user based on the email address of the current user
                User userDTO = context.Users.FirstOrDefault(row => row.UserEmailAddress == emailAddress);

                //Add Roles to the IPrinicipal Objecct
                if (userDTO != null)
                {
                    roles = context.UserRoles.Where(row => row.UserId == userDTO.UserId)
                            .Select(row => row.role.Name) //fkRole in tblRole
                            .ToArray();
                }
            }

            //Build IPrinicpal Object
            IIdentity  userIdentity = new GenericIdentity(emailAddress);
            IPrincipal newUserObj   = new System.Security.Principal.GenericPrincipal(userIdentity, roles);

            //Update Context.User with IPrinicpal Obj
            Context.User = newUserObj;
        }
Esempio n. 4
0
        protected void Application_AuthenticateRequest()
        {
            if (Context.User == null)
            {
                return;
            }
            //get current user username
            string username = Context.User.Identity.Name;

            //setup a Dbcontext
            string[] roles = null;
            using (WSADDbContext context = new WSADDbContext())
            {
                //add our roles to the iprincipal object
                User userDTO = context.Users.FirstOrDefault(row => row.Username == username);
                if (userDTO != null)
                {
                    roles = context.UserRoles.Where(row => row.UserId == userDTO.Id)
                            .Select(row => row.Role.Name)
                            .ToArray();
                }
            }

            //build iprincipal object
            IIdentity  userIdentity = new GenericIdentity(username);
            IPrincipal newUserObj   = new System.Security.Principal.GenericPrincipal(userIdentity, roles);

            //update the context.user with our Iprincipal
            Context.User = newUserObj;
        }
Esempio n. 5
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;
 }
        /// <summary>
        /// Override to Web API filter method to handle Basic Auth check
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (Active)
            {
                var identity = ParseAuthorizationHeader(actionContext);
                if (identity == null)
                {
                    Challenge(actionContext);
                    return;
                }

                if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
                {
                    Challenge(actionContext);
                    return;
                }

                var principal = new GenericPrincipal(identity, null);

                Thread.CurrentPrincipal = principal;

                // inside of ASP.NET this is also required for some async scenarios
                //if (HttpContext.Current != null)
                //    HttpContext.Current.User = principal;

                base.OnAuthorization(actionContext);
            }
        }
        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);
        }
		private static void OnAuthenticateRequest(object sender, EventArgs e)
		{
			var application = (HttpApplication) sender;

			HttpContext context = application.Context;

			if (context.User != null && context.User.Identity.IsAuthenticated)
				return;

			string cookieName = FormsAuthentication.FormsCookieName;

			HttpCookie cookie = application.Request.Cookies[cookieName.ToUpper()];

			if (cookie == null)
				return;
			try
			{
				FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
				var identity = new CustomIdentity(AccountEntry.Deserialize(ticket.UserData), ticket.Name);
				var principal = new GenericPrincipal(identity, identity.GetRoles());
				context.User = principal;
				Thread.CurrentPrincipal = principal;
			}
			catch
			{
			}
		}
Esempio n. 9
0
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            //Zapisanie pryncypala z rolami
            if (HttpContext.User != null && HttpContext.User.Identity!=null && !string.IsNullOrEmpty(HttpContext.User.Identity.Name))
            {
                string[] tablicaRol = new string[1];

                string nazwaUzytkownika = HttpContext.User.Identity.Name;

                var rola = WroBL.Logowanie.RolaUzytkownika(nazwaUzytkownika);

                if (rola != WroBL.Logowanie.Rola.Gosc)
                {
                    tablicaRol[0] = WroBL.Logowanie.NazwaRoli(rola);

                    GenericPrincipal principal = new GenericPrincipal(HttpContext.User.Identity, tablicaRol);
                    HttpContext.User = principal;

                }
                //Update daty ostatniego zalogowania
                if (HttpContext.User.Identity.Name != null && WroBL.Logowanie.UzytkownikIstnieje(nazwaUzytkownika))
                    WroBL.Logowanie.ZaktualizujDateOstatniegoLogowania(nazwaUzytkownika,true);
            }
        }
Esempio n. 10
0
        public NewsletterDaemon(Federation fed, string rootURL, string newslettersFrom,
            string headInsert, bool sendAsAttachments, string authenticateAs)
        {
            _federation = fed;
            _rootUrl = rootURL;
            _newslettersFrom = newslettersFrom;
            _headInsert = headInsert;
            _sendAsAttachments = sendAsAttachments;

            AuthorizationRuleWho who = AuthorizationRuleWho.Parse(authenticateAs);

            if (who.WhoType == AuthorizationRuleWhoType.GenericAnonymous)
            {
                _principal = new GenericPrincipal(new GenericIdentity(""), null);
            }
            else if (who.WhoType == AuthorizationRuleWhoType.User)
            {
                _principal = new GenericPrincipal(new GenericIdentity(who.Who), null);
            }
            else
            {
                throw new ArgumentException("Newsletters can only authenticate as 'anonymous' or as a particular user. Illegal value: " +
                    authenticateAs, "authenticateAs");
            }
        }
 public static GenericPrincipal AgentGenericPrincipal()
 {
     //AgentId = 1,
     var ident = new GenericIdentity("mike");
     var principal = new GenericPrincipal(ident, new[] { LookUpRoles.AgentRole });
     return principal;
 }
        static void Main(string[] args)
        {
            GenericPrincipal principal = new GenericPrincipal(new GenericIdentity("Miguel"), new string[] { "CarRentalAdmin" });

            Thread.CurrentPrincipal = principal;

            ObjectBase.Container = MEFLoader.Init();

            Console.WriteLine("Starting up services");
            Console.WriteLine("");

            SM.ServiceHost hostInventoryManager = new SM.ServiceHost(typeof(InventoryManager));
            SM.ServiceHost hostRentalManager = new SM.ServiceHost(typeof(RentalManager));
            SM.ServiceHost hostAccountManager = new SM.ServiceHost(typeof(AccountManager));

            StartService(hostInventoryManager, "InventoryManager");
            StartService(hostRentalManager, "RentalManager");
            StartService(hostAccountManager, "AccountManager");

            System.Timers.Timer timer = new Timer(10000);
            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            Console.WriteLine("");
            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();

            timer.Stop();

            Console.WriteLine("Reservation Monitor Stopped");

            StopService(hostInventoryManager, "InventoryManager");
            StopService(hostRentalManager, "RentalManager");
            StopService(hostAccountManager, "AccountManager");
        }
Esempio n. 13
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. 14
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if ((HttpContext.Current.User == null) ||
                (!HttpContext.Current.User.Identity.IsAuthenticated)) return;

            // Get Forms Identity From Current User
            var id = (FormsIdentity)HttpContext.Current.User.Identity;

            // Create a custom Principal Instance and assign to Current User (with caching)
            var principal = (GenericPrincipal)HttpContext.Current.Cache.Get(id.Name);
            if (principal == null)
            {
                // Create and populate your Principal object with the needed data and Roles.
                principal = new GenericPrincipal(id, new string[0]);
                HttpContext.Current.Cache.Add(
                    id.Name,
                    principal,
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    new TimeSpan(0, 30, 0),
                    System.Web.Caching.CacheItemPriority.Default,
                    null);
            }

            HttpContext.Current.User = principal;
        }
Esempio n. 15
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);
        }
       public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
           if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
           {
               return;
           }
           var authHeader = actionContext.Request.Headers.Authorization;
           if(authHeader!=null)
           {
               if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
 !string.IsNullOrWhiteSpace(authHeader.Parameter))
               {
                   var rawCredentials = authHeader.Parameter;
                   var encoding = Encoding.GetEncoding("iso-8859-1");
                   var credentials = encoding.GetString(Convert.FromBase64String(rawCredentials));
                   var split = credentials.Split(':');
                   var username = split[0];
                   var password = split[1];
                   if(checkLogin(username,password))
                   {
                       var principal = new GenericPrincipal(new GenericIdentity(username), null);
                       Thread.CurrentPrincipal = principal;
                       return;
                   }
               }
           }
           RespondUnAuthorize(actionContext);
       }
Esempio n. 17
0
        public IPrincipal GetMember()
        {
            var principalName = GetPrincipalName(_site);
            IPrincipal memberPrincipal = (IPrincipal)HttpContext.Current.Items[principalName];
            if (memberPrincipal == null)
            {
                memberPrincipal = DefaultPrincipal();

                var authCookie = GetAuthCookie(_site, _httpContext.Request.Cookies);
                if (authCookie != null && authCookie.Expires < DateTime.Now)
                {
                    var encryptedTicket = authCookie.Value;
                    var ticket = FormsAuthentication.Decrypt(encryptedTicket);
                    if (!ticket.Expired)
                    {
                        var membershipUser = GetMembershipUser(ticket.Name);
                        if (membershipUser != null)
                        {
                            memberPrincipal = new GenericPrincipal(new FormsIdentity(ticket), membershipUser.MembershipGroups);
                        }
                    }
                }

                HttpContext.Current.Items[principalName] = memberPrincipal;
            }
            return memberPrincipal;
        }
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var isAuthenticated = base.AuthorizeCore(httpContext);
            if (isAuthenticated)
            {
                string cookieName = FormsAuthentication.FormsCookieName;

                if (!httpContext.User.Identity.IsAuthenticated ||
                    httpContext.Request.Cookies == null ||
                    httpContext.Request.Cookies[cookieName] == null)
                {
                    return false;
                }
                
                var authCookie = httpContext.Request.Cookies[cookieName];
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                // This is where you can read the userData part of the authentication
                // cookie and fetch the token
                string webServiceToken = authTicket.UserData;
				if (string.IsNullOrEmpty(webServiceToken))
				{
					return false;
				}
                GenericIdentity identity = new TokenIdentity(httpContext.User.Identity.Name, httpContext.User.Identity.AuthenticationType, webServiceToken);

                IPrincipal userPrincipal = new GenericPrincipal(identity, null);

                // Inject the custom principal in the httpcontext
                httpContext.User = userPrincipal;
            }
            return isAuthenticated;

        }
Esempio n. 19
0
        public static void SetUserAndCookie(this HttpContext context, string login, bool isSetCookie = true)
        {
            if (login == null)
            {
                System.Web.Security.FormsAuthentication.SignOut();
                context.User = null;
            }
            else
            {
                if (isSetCookie)
                {
                    var authTicket = new System.Web.Security.FormsAuthenticationTicket
                                     (
                        1,                         //version
                        login,                     // user name
                        DateTime.Now,              //creation
                        DateTime.Now.AddYears(50), //Expiration (you can set it to 1 month
                        true,                      //Persistent
                        login
                                     );            // additional informations
                    var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);

                    var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);

                    authCookie.Expires  = authTicket.Expiration;
                    authCookie.HttpOnly = true;

                    context.Response.SetCookie(authCookie);
                }
                var principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(login), Array <string> .Empty);
                context.User = principal;
            }
        }
Esempio n. 20
0
        public static HttpContextBase FakeHttpContext() {

            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);


            var form = new NameValueCollection();
            var querystring = new NameValueCollection();
            var cookies = new HttpCookieCollection();
            var user = new GenericPrincipal(new GenericIdentity("testuser"),new string[]{"Administrator"});
            
            request.Expect(r => r.Cookies).Returns(cookies);
            request.Expect(r => r.Form).Returns(form);
            request.Expect(q => q.QueryString).Returns(querystring);
            context.Expect(u => u.User).Returns(user);
            return context.Object;
        }
Esempio n. 21
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;
        }
        protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, System.Threading.CancellationToken cancellationToken )
        {
            var authHeader = request.Headers.Authorization;

            if ( authHeader != null )
            {
                if ( authHeader.Scheme.Equals( "encryptKey", StringComparison.OrdinalIgnoreCase ) &&
                !String.IsNullOrWhiteSpace( authHeader.Parameter ) )
                {
                    var key = authHeader.Parameter;

                    if ( IsVerified( key ) )
                    {
                        var currentPrincipal = new GenericPrincipal( new GenericIdentity( "User" ), null );
                        request.GetRequestContext().Principal = currentPrincipal;
                    }
                }
            }

            return await base.SendAsync( request, cancellationToken )
                      .ContinueWith( task =>
                      {
                          var response = task.Result;

                          if ( response.StatusCode == HttpStatusCode.Unauthorized &&
                              !response.Headers.Contains( basicAuthResponseHeader ) )
                              response.Headers.Add( basicAuthResponseHeader, basicAuthResponseHeaderValue );

                          return response;
                      } );
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;
            if (authHeader != null)
            {
                if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase)
                    && !string.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    var rawCredentials = authHeader.Parameter;
                    var encoding = Encoding.GetEncoding("iso-8859-1");
                    var credentials = encoding.GetString(Convert.FromBase64String(rawCredentials));

                    // TODO: Maybe log in just using e-mail address
                    var split = credentials.Split('|');
                    var username = split[0];
                    var password = split[1];

                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("CrisisCheckin", "User", "Id", "UserName", autoCreateTables: true);
                    }

                    if (WebSecurity.Login(username, password))
                    {
                        var principal = new GenericPrincipal(new GenericIdentity(username), null);
                        Thread.CurrentPrincipal = principal;
                        return;
                    }
                }
            }

            HandleUnauthorized(actionContext);
        }
		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;
		}
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();
        }
        private HttpRequestMessage SetUpAuthTestInfrastructure(
            string username, string password)
        {

            var principal = new GenericPrincipal(
                new GenericIdentity(username),
                new[] { "Admin" });

            var request = new HttpRequestMessage();

            var membershipServiceMock = new Mock<IMembershipService>();
            membershipServiceMock.Setup(ms =>
                ms.ValidateUser(It.IsAny<string>(), It.IsAny<string>())
            ).Returns<string, string>((u, p) =>
                (u == username && p == password) ?
                new ValidUserContext
                {
                    Principal = principal
                }
                : new ValidUserContext()
            );

            var dependencyScopeMock = new Mock<IDependencyScope>();
            dependencyScopeMock.Setup(
                ds => ds.GetService(typeof(IMembershipService))
            ).Returns(membershipServiceMock.Object);

            request.Properties[HttpPropertyKeys.DependencyScope] =
                dependencyScopeMock.Object;

            return request;
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (!SkipAuthorisation(actionContext))
            {
                var identity = ParseAuthorizationHeader(actionContext);
                if (identity == null)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                    return;
                }

                if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
                {
                    actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                    return;
                }

                var principal = new GenericPrincipal(identity, null);

                Thread.CurrentPrincipal = principal;
                HttpContext.Current.User = principal;

                base.OnAuthorization(actionContext);
            }
        }
Esempio n. 28
0
        /// <summary>  
        /// 创建登录用户的票据信息  
        /// </summary>  
        /// <param name="strUserName"></param>  
        public static string CreateLoginUserTicket(string userId)
        {
            DateTime loginTime = DateTime.Now;//用户的登录时间
            //构造Form验证的票据信息
            ///把登录时间和用户ID写进Cookie中,后面可以用于判断用户的登录时间间隔
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(90),
                true, string.Format("{0}:{1}", userId, loginTime), FormsAuthentication.FormsCookiePath);

            string ticString = FormsAuthentication.Encrypt(ticket);

            //把票据信息写入Cookie和Session
            //SetAuthCookie方法用于标识用户的Identity状态为true
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserLoginCookieToken", ticString));
            FormsAuthentication.SetAuthCookie(userId, true);
            HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;

            //重写HttpContext中的用户身份,可以封装自定义角色数据;
            //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
            string[] roles = ticket.UserData.Split(',');
            IIdentity identity = new FormsIdentity(ticket);
            IPrincipal principal = new GenericPrincipal(identity, roles);
            HttpContext.Current.User = principal;

            return ticString;//返回票据
        }
Esempio n. 29
0
 /// <summary>
 /// Example to show how you could create identities from any data store, based on strings.
 /// </summary>
 /// <returns>GenericPrincipal for bob</returns>
 public static GenericPrincipal CreateIdentity()
 {
     // attached roles
     var roles = new string[] { "Sales", "Marketing" };
     var user = new GenericPrincipal(new GenericIdentity("bob"), roles);
     return user;
 }
        private static void OnAuthenticateRequest(object sender, EventArgs eventArgs)
        {
            var httpApplication = (HttpApplication)sender;

            var cookieName = FormsAuthentication.FormsCookieName;
            var cookie = httpApplication.Request.Cookies[cookieName.ToUpper()];
            if (cookie == null)
                return;

            try
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                if (ticket == null || ticket.Expired)
                    return;

                var accountData = AccountData.Deserialize(ticket.UserData);
                var identity = new FrameplateIdentity(accountData, ticket.Name);
                var principal = new GenericPrincipal(identity, accountData.Roles);

                httpApplication.Context.User = principal;
                Thread.CurrentPrincipal = principal;
            }
            catch
            {
            }
        }
        protected void Application_AuthenticateRequest()
        {
            if (Context.User == null)
            {
                return;
            }                                     //no user set
            //Get Current User Username
            string username = Context.User.Identity.Name;



            //Setup DbContext
            string[] roles = null;
            using (WSADDbContext context = new WSADDbContext())
            {
                //Add roles to IPrincipal Object
                User userDTO = context.Users.FirstOrDefault(row => row.Username == username);
                if (userDTO != null)
                {
                    roles = context.UserRoles.Where(row => row.UserId == userDTO.Id)
                            .Select(row => row.Role.Name)
                            .ToArray();
                }
            }

            //Build IPrincipal Object
            IIdentity  userIdentity = new GenericIdentity(username);
            IPrincipal newUserObj   = new System.Security.Principal.GenericPrincipal(userIdentity, roles);

            //Update Context.User with Iprincipal
            Context.User = newUserObj;
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            HttpRequestMessage r = request;

            if (r.Headers.Authorization == null) {
                return Login();
            }

            AuthenticationHeaderValue auth = r.Headers.Authorization;

            byte[] decodedBytes = Convert.FromBase64String(auth.Parameter);
            string decodedUserAndPassword = Encoding.UTF8.GetString(decodedBytes);
            string[] userAndPassword = decodedUserAndPassword.Split(':');

            string user = userAndPassword[0];
            string password = userAndPassword[1];
            UserCredentials credentials = Validate(user, password);
            if (credentials != null) {
                var p = new GenericPrincipal(new GenericIdentity(credentials.User), credentials.Roles.ToArray());
                Thread.CurrentPrincipal = p;
                return base.SendAsync(request, cancellationToken);
            }

            // fail 
            return Login();
        }
Esempio n. 33
0
 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
 {
     if (Request.IsAuthenticated == true)
     {
         HttpCookie authenCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
         if (authenCookie == null)
         {
             FormsAuthentication.SignOut();
             HttpContext.Current.User = null;
             return;
         }
         FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authenCookie.Value);
         FormsIdentity id = new FormsIdentity(ticket);
         UserToken token = SiteSecurity.GetToken(ticket.Name);
         if (token != null)
         {
             GenericPrincipal principal = new GenericPrincipal(id, new string[] {token.Role});
             HttpContext.Current.User = principal;
         }
         else
         {
             FormsAuthentication.SignOut();
             HttpContext.Current.User = null;
         }
     }
 }
Esempio n. 34
0
        public void Initialize()
        {
            var principal = new GenericPrincipal(
                new GenericIdentity("Felipe"), new string[] { "CarRentalAdmin" });

            Thread.CurrentPrincipal = principal;
        }
Esempio n. 35
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 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;
        }
        private void SetPrincipal(Users user)
        {
            IPrincipal principal = new System.Security.Principal.GenericPrincipal(
                new System.Security.Principal.GenericIdentity(user.email),
                new string[] { /* fill roles if any */ });

            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }
Esempio n. 38
0
        public void GlobalNotificationToggle_SendPublicTweet_True_Correct()
        {
            var db   = new TestTweetHarborDbContext();
            var user = UserHelper.ArrangeNewUserDefault();

            db.Users.Add(user);

            var proj = new Project()
            {
                ProjectName = "The Test Project",
                SendPrivateTweetOnFailure = true,
                SendPrivateTweetOnSuccess = true,
                SendPublicTweetOnFailure  = false,
                SendPublicTweetOnSuccess  = true,
                User = user
            };

            db.Projects.Add(proj);
            var ts = new TestTweetHarborTwitterService();


            var auth = new Mock <IFormsAuthenticationWrapper>();

            var controller = new AccountController(db, ts, auth.Object);

            var ident = new GenericIdentity("localtestuser");

            System.Security.Principal.GenericPrincipal c = new System.Security.Principal.GenericPrincipal(ident, new string[] { });

            controller.SetFakeControllerContext(c);

            var res = controller.GlobalNotificationToggle("SendPublicTweet", true);

            Assert.IsInstanceOfType(res.Data, typeof(JsonResultModel));
            var rm = (JsonResultModel)res.Data;

            Assert.IsTrue(rm.Success);
            Assert.IsTrue(rm.Message == "Value has been updated");

            Assert.AreEqual(true, db.Users.FirstOrDefault(u => u.UserName == ident.Name).SendPublicTweet);
        }
Esempio n. 39
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="name">账户名</param>
        /// <param name="psd">账户密码</param>
        /// <returns>Account</returns>
        public Account Logon(UserLogOnModel model)
        {
            Account user = null;
            //创建账户仓储
            IRepository <Account> accountRep = FBS.Factory.Factory <IRepository <Account> > .GetConcrete <Account>();

            ISpecification <Account> namespec;

            if (string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.UserName))
            {
                //昵称登录
                namespec = new Specification <Account>(o => o.UserName == model.UserName);
            }
            else if (string.IsNullOrEmpty(model.UserName) && !string.IsNullOrEmpty(model.Email))
            {
                //邮箱登录
                namespec = new Specification <Account>(o => o.Email == model.Email);//查询条件
            }
            else
            {
                throw new NullReferenceException("用户登录时,用户名和邮箱至少使用一个");
            }

            if (accountRep.Exists(namespec))//这个账户是否存在
            {
                user = accountRep.Find(namespec);
                if (!user.CheckPsd(model.Password))
                {
                    throw new LogonException("密码错误");//账户存在,密码错误
                }
                else
                {
                    if (new UserEntryService().CheckForbidden(user.Id))
                    {
                        throw new LogonException("您由于不遵守相关规定,账户被禁用");//您由于不遵守相关规定,账户被禁用
                    }
                    //将Identify更新到HttpContext中
                    UserIdentity u = new UserIdentity("Forms", true, user.Id.ToString());

                    /*UserInfoService uis=new UserInfoService();
                     * string[] roles=uis.GetUserRoles(user.Id);*/
                    string[] roles = user.Roles.Split('|');
                    if (roles == null)
                    {
                        roles = new string[1] {
                            string.Empty
                        }
                    }
                    ;

                    System.Security.Principal.GenericPrincipal gp = new System.Security.Principal.GenericPrincipal(u, roles);
                    HttpContext.Current.User = gp;

                    //添加ticket到cookie
                    FormsAuthenticationTicket ticket = AuthenticationHelper.CreateAuthenticationTicket(user.Id.ToString(), user.UserName, model.RememberMe);
                    AuthenticationHelper.SetAuthenticalCookie(ticket);
                }
            }
            else
            {
                throw new LogonException("账户不存在");//账户不存在
            }
            return(user);
        }