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


C# Principal.GenericIdentity类代码示例

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


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

示例1: OnAuthorization

        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);
        }
开发者ID:WiliamWu,项目名称:Api-Sample,代码行数:29,代码来源:DeveloperHackAuth.cs

示例2: Main

 static void Main(string[] args)
 {
     GenericIdentity genid = new GenericIdentity("Rafael", "");
     Console.WriteLine(genid.IsAuthenticated.ToString());
     
     Console.ReadKey();
 }
开发者ID:Rafael-Miceli,项目名称:ProjectStudiesCert70-536,代码行数:7,代码来源:Program.cs

示例3: ReplacePrincipalWithRoleMappings

        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());
        }
开发者ID:BlythMeister,项目名称:NuGet.Lucene,代码行数:26,代码来源:RoleMappingAuthenticationModule.cs

示例4: Application_AuthenticateRequest

        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();
        }
开发者ID:zitjubiz,项目名称:terryCBM,代码行数:33,代码来源:Global.asax.cs

示例5: 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

示例6: Authenticate

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

示例7: Before

 /// <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;
 }
开发者ID:nulltoken,项目名称:xunit,代码行数:12,代码来源:AssumeIdentityAttribute.cs

示例8: SignIn

        public IPrincipal SignIn(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

            var id = new GenericIdentity(userName);
            return new GenericPrincipal(id, new string[] { });
        }
开发者ID:jijo-paulose,项目名称:bistro-framework,代码行数:7,代码来源:Services.cs

示例9: AuthenticateUser

        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;
            }
        }
开发者ID:Aleph06,项目名称:Supraterra,代码行数:30,代码来源:SupraterraAuth.cs

示例10: setThreadPrincipalWithRoles

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

示例11: ServiceProviderContext

        static ServiceProviderContext()
        {
            Settings = ConfigurationManager.GetSection("oauth.net.serviceprovider") as ServiceProviderSettings;

            if (!string.IsNullOrEmpty(Settings.DummyIdentity))
                DummyIdentity = new GenericIdentity(Settings.DummyIdentity);
        }
开发者ID:rpmcpp,项目名称:oauth-dot-net,代码行数:7,代码来源:ServiceProviderContext.cs

示例12: SendAsync

        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);
        }
开发者ID:ionixNet,项目名称:ionix.ServiceModel,代码行数:33,代码来源:TokenAuthMessageHandlerBase.cs

示例13: Application_AuthenticateRequest

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

示例14: CustomPrincipal

        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 ();
            }
        }
开发者ID:mictlanix,项目名称:mbe,代码行数:33,代码来源:CustomPrincipal.cs

示例15: LeaguePrincipal

 public LeaguePrincipal(int id, string login, string role)
 {
     UserId = id;
     Login = login;
     Role = role;
     Identity = new GenericIdentity(login);
 }
开发者ID:ReszkeM,项目名称:VolleyballLeagueManagement,代码行数:7,代码来源:LeaguePrincipal.cs


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