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

C# Claims.Claim类代码示例

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

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



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

示例1: GenerateUserToken

        /// <summary>
        /// Generate Token from user information
        /// </summary>
        /// <param name="Id">User id</param>
        /// <param name="username">UserName</param>
        /// <returns>TokenResponse</returns>
        public TokenResponse GenerateUserToken(long Id, string username)
        {
            var now = DateTime.UtcNow;

            var claims = new Claim[]
            {
                new Claim("id", Id.ToString()),
                new Claim("name", username),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64)
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: this.options.Issuer,
                audience: this.options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(this.options.Expiration),
                signingCredentials: this.options.SigningCredentials ?? TokenProvider.DefaultSigningCredentials());

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return new TokenResponse
            {
                access_token = encodedJwt,
                expires_in = (ulong)this.options.Expiration.TotalSeconds
            };
        }
开发者ID:ychebotarev,项目名称:InColUn_V0_1,代码行数:34,代码来源:TokenProvider.cs


示例2: JsonClaim

 public JsonClaim(Claim claim)
 {
     if (claim == null) throw new ArgumentNullException("claim");
     if (!claim.ValueType.StartsWith("Json:"))
         throw new ArgumentException("Claim has unsupported ValueType", "claim");
     Claim = claim;
 }
开发者ID:thomas-parrish,项目名称:BugTracker,代码行数:7,代码来源:JsonClaim.cs


示例3: Main

        static void Main(string[] args)
        {
            // NOTE: The below is a sample of how we may construct a ClaimsPrincipal instance over two ClaimsIdentity instances:
            //       one for the tenant identity and the the other for the user idenetity. When a request come to the web server, we can determine the
            //       tenant's identity at the very early stages of the request lifecycle. Then, we can try to authenticate the user based on the
            //       information passed through the request headers (this could be bearer token, basic auth, etc.).

            const string tenantId = "f35fe69d-7aef-4f1a-b645-0de4176cd441";
            const string tenantName = "bigcompany";
            IEnumerable<Claim> tenantClaims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, tenantId, ClaimValueTypes.String, AuthServerName),
                new Claim(ClaimTypes.Name, tenantName, ClaimValueTypes.String, AuthServerName)
            };

            const string userId = "d4903f71-ca06-4671-a3df-14f7e02a0008";
            const string userName = "tugberk";
            const string twitterToken = "30807826f0d74ed29d69368ea5faee2638b0e931566b4e4092c1aca9b4db04fe";
            const string facebookToken = "35037356a183470691504cd163ce2f835419978ed81c4b7781ae3bbefdea176a";
            IEnumerable<Claim> userClaims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, AuthServerName),
                new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String, AuthServerName),
                new Claim("token", twitterToken, ClaimValueTypes.String, AuthServerName, "Twitter"),
                new Claim("token", facebookToken, ClaimValueTypes.String, AuthServerName, "Facebook")
            };

            ClaimsIdentity tenantIdentity = new ClaimsIdentity(tenantClaims, TenantAuthType, ClaimTypes.Name, ClaimTypes.Role);
            ClaimsIdentity userIdentity = new ClaimsIdentity(userClaims, UserAuthType, ClaimTypes.Name, ClaimTypes.Role);

            ClaimsPrincipal principal = new ClaimsPrincipal(new[] { tenantIdentity, userIdentity });
        }
开发者ID:shcheahgmail,项目名称:DotNetSamples,代码行数:32,代码来源:Program.cs


示例4: CreateWithUserId

 public static ClaimsPrincipal CreateWithUserId(long authorId)
 {
     var claim = new Claim(ToBeImplementedClaims.IdClaim, authorId.ToString());
     var identity = new ClaimsIdentity(Enumerable.Repeat(claim, 1));
     var claimsprincipal = new ClaimsPrincipal(identity);
     return claimsprincipal;
 }
开发者ID:jstadnicki,项目名称:tbi,代码行数:7,代码来源:ClaimsPrincipalFactory.cs


示例5: GetValue

        private static object GetValue(Claim claim)
        {
            if (claim.ValueType == ClaimValueTypes.Integer ||
                claim.ValueType == ClaimValueTypes.Integer32)
            {
                Int32 value;
                if (Int32.TryParse(claim.Value, out value))
                {
                    return value;
                }
            }

            if (claim.ValueType == ClaimValueTypes.Integer64)
            {
                Int64 value;
                if (Int64.TryParse(claim.Value, out value))
                {
                    return value;
                }
            }

            if (claim.ValueType == ClaimValueTypes.Boolean)
            {
                bool value;
                if (bool.TryParse(claim.Value, out value))
                {
                    return value;
                }
            }

            return claim.Value;
        }
开发者ID:ianlovell,项目名称:openidconnect,代码行数:32,代码来源:Extensions.cs


示例6: UserClaim

        public UserClaim(Claim claim)
        {
            if (claim == null) throw new ArgumentNullException("claim");

            Type = claim.Type;
            Value = claim.Value;
        }
开发者ID:hnrkhlmr,项目名称:AspNetIdentityCustomDb,代码行数:7,代码来源:UserClaim.cs


示例7: ValidatePrincipal

        public Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            // 
            // TODO: uncomment this after next release of aspnet core
            // and fix the broken
            // it needs to resolve options per tenant
            //await securityStampValidator.ValidateAsync(context);

            var tenant = context.HttpContext.GetTenant<SiteContext>();

            if (tenant == null)
            {
                context.RejectPrincipal();
            }

            var siteGuidClaim = new Claim("SiteGuid", tenant.Id.ToString());

            if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value))
            {
                logger.LogInformation("rejecting principal because it does not have siteguid");
                context.RejectPrincipal();
            }

            //TODO: should we lookup the user here and reject if locked out or deleted?

            return Task.FromResult(0);
        }
开发者ID:joeaudette,项目名称:cloudscribe,代码行数:27,代码来源:SiteCookieAuthenticationEvents.cs


示例8: BackendCredentialsClaim

        public BackendCredentialsClaim(Claim claim)
            : base(claim.Type, claim.Value)
        {
            Contract.Requires<ArgumentException>(claim.Type == TYPE, "Invalid Claim Type");

            SplitValue(claim.Value, out User, out Password);
        }
开发者ID:rollingthunder,项目名称:DiversityAPI,代码行数:7,代码来源:BackendClaims.cs


示例9: CreateIdentity

        public static ClaimsIdentity CreateIdentity(Data.User user)
        {
            var claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, user.EmailAddress));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            claimsIdentity.AddClaim(
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                        "ASP.NET Identity",
                        "http://www.w3.org/2001/XMLSchema#string"));

            if (user.IsAdmin)
            {
                var adminClaim = new Claim(ClaimTypes.Role, AdministratorRole); // , null, ClaimIssuerName);
                claimsIdentity.AddClaim(adminClaim);
            }

            // Cannot assign null-value to new claim
            if (null != user.Cultures)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.UserData, user.Cultures));
            }

            return claimsIdentity;
        }
开发者ID:transformersprimeabcxyz,项目名称:ResourceFirstTranslations,代码行数:25,代码来源:RftAuthenticationManager.cs


示例10: Should_remove_claim

        public void Should_remove_claim()
        {
            var user = TestData.GetTestUserJohn();
            var claimToDelete = new Claim(ClaimTypes.Email, "[email protected]");

            var task = _target.RemoveClaimAsync(user, claimToDelete);

            task.Wait();


            var db = Database.Open();
            var claims = db.AspNetUserClaims.FindAllByUserId(TestData.John_UserId).ToList();

            Assert.That(claims.Count, Is.EqualTo(1));

            bool foundClaim=false;
            foreach (var claim in claims)
            {
                if (claim.ClaimType == ClaimTypes.Email)
                {
                    foundClaim = true;
                }   
            }

            Assert.That(foundClaim, Is.False);;
        }
开发者ID:rioka,项目名称:Simple.Data.AspNet.Identity,代码行数:26,代码来源:When_removing_a_claim.cs


示例11: ValidateToken

        private async Task<IEnumerable<Claim>> ValidateToken(string token)
        {
            HttpClient clientRequest = new HttpClient();
            clientRequest.BaseAddress = new Uri("http://localhost:10100/");

            clientRequest.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var response = clientRequest.PostAsJsonAsync("authorize/verify", token).Result;

            if (!response.IsSuccessStatusCode)
            {
                return null;
            }

            var content = await response.Content.ReadAsStringAsync();
            ValidateResult result = JsonConvert.DeserializeObject<ValidateResult>(content);

            var claim = new Claim(result.Type, result.Value);
            List<Claim> claims = new List<Claim>(1);

            claims.Add(claim);

            return claims;

        }
开发者ID:pplavetzki,项目名称:LanguageExchange,代码行数:26,代码来源:ClientAuthenticationFilter.cs


示例12: ValidateToken

        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {

            //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6Ikphc29uIExlZSIsInN1YiI6Ikphc29uIExlZSIsInJvbGUiOlsiTWFuYWdlciIsIlN1cGVydmlzb3IiXSwiaXNzIjoiaHR0cDovL2p3dGF1dGh6c3J2LmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiUm9ja2V0IiwiZXhwIjoxNDQxOTgwMjE5LCJuYmYiOjE0NDE5NzY2MTl9.yegylhGkz5uasu5E--aEbCAHfi5aE9Z17_pZAE63Bog

            validatedToken = null;


            var key = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
            
            try
            {
                var raw = JsonWebToken.Decode(securityToken, key);

                var payLoad = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(raw);

                var claims = new List<Claim>();

                foreach (var row in payLoad)
                {
                    var claim = new Claim(row.Key, row.Value);
                    claims.Add(claim);
                }

                var claimsIdentity = new ClaimsIdentity(claims, "jwt");

                return new ClaimsPrincipal(claimsIdentity);
            }
            catch (Exception ex)
            {
                return null;

            }
            
        }
开发者ID:JasonSoft,项目名称:single-sign-on,代码行数:35,代码来源:CustomJwtSecurityTokenHandler.cs


示例13: Setup

 private void Setup()
 {
     var myClaim = new Claim("http://myclaims/customer", "add");
     var currentIdentity = new CorpIdentity("stevenh", myClaim);
     var principal = new ClaimsPrincipal(currentIdentity);
     Thread.CurrentPrincipal = principal;
 }
开发者ID:stevenh77,项目名称:ClaimsBasedSecurityDemo,代码行数:7,代码来源:CustomAuthorisationManagerExample.cs


示例14: CreateAsync

        public virtual Task<ClaimsIdentity> CreateAsync(User user, string authenticationType, IEnumerable<string> userRoles, IEnumerable<Claim> userClaims)
        {
            var claimsIdentity = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
            claimsIdentity.AddClaim(new Claim(this.UserIdClaimType, user.Id, DefaultClaimValueType));
            claimsIdentity.AddClaim(new Claim(this.UserNameClaimType, user.UserName, DefaultClaimValueType));
            claimsIdentity.AddClaim(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, DefaultClaimValueType));

            // TODO: Support Security Stamp.
            var claim = new Claim(this.SecurityStampClaimType, user.SecurityStamp);
            claimsIdentity.AddClaim(claim);

            // TODO: Support User Roles, Ensure Roles are loaded.
            if (userRoles != null)
            {
                foreach (var userRole in userRoles)
                {
                    claimsIdentity.AddClaim(new Claim(this.RoleClaimType, userRole, DefaultClaimValueType));
                }
            }

            // TODO: Support User Claims.
            if (userClaims != null)
            {
                foreach (var userClaim in userClaims)
                {
                    claimsIdentity.AddClaim(userClaim);
                }
            }

            return Task.FromResult(claimsIdentity);
        }
开发者ID:Perfectial,项目名称:Perfectial.EntityFramework.Enterprise.Sample,代码行数:31,代码来源:ClaimsIdentityFactory.cs


示例15: ProcessLogoutNameIdentifier

        private static Saml2NameIdentifier ProcessLogoutNameIdentifier(Claim claim)
        {
            var fields = DelimitedString.Split(claim.Value);

            var saml2NameIdentifier = new Saml2NameIdentifier(fields[4]);

            if (!string.IsNullOrEmpty(fields[0]))
            {
                saml2NameIdentifier.NameQualifier = fields[0];
            }
            if (!string.IsNullOrEmpty(fields[1]))
            {
                saml2NameIdentifier.SPNameQualifier = fields[1];
            }
            if (!string.IsNullOrEmpty(fields[2]))
            {
                saml2NameIdentifier.Format = new Uri(fields[2]);
            }
            if (!string.IsNullOrEmpty(fields[3]))
            {
                saml2NameIdentifier.SPProvidedId = fields[3];
            }

            return saml2NameIdentifier;
        }
开发者ID:CDHDeveloper,项目名称:authservices,代码行数:25,代码来源:ClaimsExtensions.cs


示例16: ValidatePrincipal

        public async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            // TODO: uncomment this after next release of aspnet core
            // and fix the broken
            // it needs to resolve options per tenant
            //await securityStampValidator.ValidateAsync(context);


            TenantContext<SiteSettings> siteContext
                = await siteResolver.ResolveAsync(contextAccessor.HttpContext);
            
            if (siteContext == null)
            {
                context.RejectPrincipal();
            }

            if (siteContext.Tenant == null)
            {
                context.RejectPrincipal();
            }

            Claim siteGuidClaim = new Claim("SiteGuid", siteContext.Tenant.SiteGuid.ToString());

            if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value))
            {
                log.LogInformation("rejecting principal because it does not have siteguid");
                context.RejectPrincipal();
            }
            
           // return Task.FromResult(0);
        }
开发者ID:lespera,项目名称:cloudscribe,代码行数:31,代码来源:MultiTenantAuthCookieValidator.cs


示例17: ExternalCallback

        public async Task<IActionResult> ExternalCallback()
        {
            var externalId = await Context.Authentication.AuthenticateAsync("Temp");

            // check external identity - e.g. to see if registration is required
            // or to associate account with current login etc
            // name identifier is the unique id of the user in the context of the external provider
            var userId = externalId.FindFirst(ClaimTypes.NameIdentifier).Value;

            var name = externalId.FindFirst(ClaimTypes.Name).Value;
            var email = externalId.FindFirst(ClaimTypes.Email).Value;

            // add some application claims from profile database
            var role = new Claim("role", "PremiumUser");

            var newId = new ClaimsIdentity("application", "name", "role");
            newId.AddClaim(new Claim("name", name));
            newId.AddClaim(new Claim("email", email));
            newId.AddClaim(role);

            // sign in user with main cookie
            await Context.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(newId));

            // delete temp cookie
            await Context.Authentication.SignOutAsync("Temp");

            return Redirect("/home/secure");
        }
开发者ID:okusnadi,项目名称:AspNet5TemplateExternalWithCallback,代码行数:28,代码来源:AccountController.cs


示例18: ApiControllerExtensionsTests

        public ApiControllerExtensionsTests()
        {
            HttpConfiguration config = new HttpConfiguration();
            IWebHookUser user = new WebHookUser();

            _managerMock = new Mock<IWebHookManager>();
            _resolverMock = new Mock<IDependencyResolver>();
            _resolverMock.Setup(r => r.GetService(typeof(IWebHookManager)))
                .Returns(_managerMock.Object)
                .Verifiable();
            _resolverMock.Setup(r => r.GetService(typeof(IWebHookUser)))
                .Returns(user)
                .Verifiable();

            config.DependencyResolver = _resolverMock.Object;

            ClaimsIdentity identity = new ClaimsIdentity();
            Claim claim = new Claim(ClaimTypes.Name, "TestUser");
            identity.AddClaim(claim);
            _principal = new ClaimsPrincipal(identity);

            _context = new HttpRequestContext()
            {
                Configuration = config,
                Principal = _principal
            };
            _controller = new TestController()
            {
                RequestContext = _context
            };
        }
开发者ID:Joshzx,项目名称:WebHooks,代码行数:31,代码来源:ApiControllerExtensionsTests.cs


示例19: ClaimsAuthorizedClient

        private static bool ClaimsAuthorizedClient(Claim claim, TokenValidationParameters tokenValidationParameters)
        {
            if (null == claim)
            {
                return false;
            }

            if (!TokenHandler.ClaimFromValidIssuer(claim, tokenValidationParameters))
            {
                return false;
            }

            if (!TokenHandler.ClaimsApplicationIdentifier(claim))
            {
                return false;
            }

            if (string.IsNullOrWhiteSpace(claim.Value))
            {
                return false;
            }

            bool result =
                TokenHandler
                .AuthorizedClientApplicationIdentifiers
                .Value
                .Any(
                    (string item) =>
                        string.Equals(item, claim.Value, StringComparison.OrdinalIgnoreCase));
            return result;
        }
开发者ID:belaie,项目名称:AzureAD-BYOA-Provisioning-Samples,代码行数:31,代码来源:TokenHandler.cs


示例20: ReadJson

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var source = serializer.Deserialize<ClaimModel>(reader);
            var target = new Claim(source.Type, source.Value, source.ValueType);

            return target;
        }
开发者ID:jvandertil,项目名称:IdentityServer3.Postgres,代码行数:7,代码来源:ClaimConverter.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Claims.ClaimsIdentity类代码示例发布时间:2022-05-26
下一篇:
C# ExtendedProtection.ExtendedProtectionPolicy类代码示例发布时间: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