当前位置: 首页>>代码示例>>C#>>正文


C# Principal.GenericPrincipal类代码示例

本文整理汇总了C#中System.Security.Principal.GenericPrincipal的典型用法代码示例。如果您正苦于以下问题:C# GenericPrincipal类的具体用法?C# GenericPrincipal怎么用?C# GenericPrincipal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


GenericPrincipal类属于System.Security.Principal命名空间,在下文中一共展示了GenericPrincipal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Application_AuthenticateRequest

        /// <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);
        }
开发者ID:wezmag,项目名称:BetterCMS,代码行数:30,代码来源:Global.asax.cs

示例2: OnAuthenticateRequest

        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;

            }
        }
开发者ID:daveh551,项目名称:photoserver,代码行数:27,代码来源:HttpAuthenticationModule.cs

示例3: SendAsync

        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();
        }
开发者ID:Robin--,项目名称:NakedObjectsFramework,代码行数:25,代码来源:BasicAuthenticationHandler.cs

示例4: setupNormalRequestValues

		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;
		}
开发者ID:CallMeSteve,项目名称:O2.Platform.Scripts,代码行数:26,代码来源:API_Moq_HttpContext.cs

示例5: SendAsync

        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;
                      } );
        }
开发者ID:chrisparkeronline,项目名称:site_api,代码行数:31,代码来源:BasicAuthenticationHandler.cs

示例6: CreateLoginUserTicket

        /// <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;//返回票据
        }
开发者ID:gowhy,项目名称:MicroWish,代码行数:29,代码来源:AutheTicketManager.cs

示例7: Application_AuthenticateRequest

        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;
        }
开发者ID:Avaruz,项目名称:Artemisa,代码行数:34,代码来源:Global.asax.cs

示例8: OnAuthenticateRequest

		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
			{
			}
		}
开发者ID:syned,项目名称:ByndyuSoft.Infrastructure,代码行数:27,代码来源:CustomAutentificationModule.cs

示例9: OnAuthorization

        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);
            }
        }
开发者ID:GrzesiekK126,项目名称:Wrocasion,代码行数:26,代码来源:WroController.cs

示例10: NewsletterDaemon

        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");
            }
        }
开发者ID:nuxleus,项目名称:flexwikicore,代码行数:25,代码来源:NewsletterDaemon.cs

示例11: AgentGenericPrincipal

 public static GenericPrincipal AgentGenericPrincipal()
 {
     //AgentId = 1,
     var ident = new GenericIdentity("mike");
     var principal = new GenericPrincipal(ident, new[] { LookUpRoles.AgentRole });
     return principal;
 }
开发者ID:haithemaraissia,项目名称:RentalMVCClean,代码行数:7,代码来源:MockControllerContext.cs

示例12: OnAuthorization

        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;
            }
        }
开发者ID:CarlosLeones,项目名称:vecoweb,代码行数:28,代码来源:SecurityFilter.cs

示例13: Main

        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");
        }
开发者ID:holwerda,项目名称:PluralsightRef-BuildingE2E-SOA-CarRental,代码行数:35,代码来源:Program.cs

示例14: Application_AuthenticateRequest

        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;
        }
开发者ID:ripper234,项目名称:Kuzando,代码行数:26,代码来源:Global.asax.cs

示例15: OnAuthenticateRequest

        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
            {
            }
        }
开发者ID:Eskat0n,项目名称:Frameplate.Security,代码行数:26,代码来源:AuthenticationModule.cs


注:本文中的System.Security.Principal.GenericPrincipal类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。