• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Principal.GenericIdentity类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: AuthenticateRequest

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


示例17: OnActionExecuting

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


示例18: AuthenticateUser

        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;
        }
开发者ID:prinzo,项目名称:Attack-Of-The-Fines-TA15,代码行数:26,代码来源:BasicAuthHttpModule.cs


示例19: Application_PostAuthenticateRequest

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


示例20: NameAuthenticationType

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Principal.GenericPrincipal类代码示例发布时间:2022-05-26
下一篇:
C# Policy.PolicyStatement类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap