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


C# ClaimsIdentity.AddClaims方法代码示例

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


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

示例1: ProcessClientCertificate

        public ClaimsIdentity ProcessClientCertificate(X509Certificate2 cert, string ipAddress)
        {
            using (var per = PersistenceFactory())
            {
                var hash = cert.GetCertHash();
                var client = per.ClientGetByCertificateHash(hash);

                // not found? add to pending certificates list
                if (client == null)
                {
                    TraceSource.TraceInformation("Pending certificate:\n{0} ({1})", ByteArrayHelper.ByteArrayToString(hash), ipAddress);
                    per.PendingCertificateAddOrUpdate(hash, ipAddress);
                    per.Save();
                }

                // build identity
                var identity = new ClaimsIdentity("ClientAuthentication");
                identity.AddClaim(new Claim(CertificateHashClaimType, ByteArrayHelper.ByteArrayToString(hash), ClaimValueTypes.HexBinary, ClaimIssuer));
                identity.AddClaim(new Claim(IsKnownClaimType, client == null ? "false" : "true", ClaimValueTypes.Boolean, ClaimIssuer)); // known client?

                // add details only if authenticated
                if (client != null)
                {
                    identity.AddClaim(new Claim(identity.NameClaimType, client.Name, ClaimValueTypes.String, ClaimIssuer)); // nick name
                    identity.AddClaim(new Claim(ClientIdClaimType, client.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer)); // ID
                    identity.AddClaims(client.ClientGroups.Select(group => new Claim(identity.RoleClaimType, group.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer))); // assigned groups
                    identity.AddClaims(client.ClientGroups.Select(group => new Claim(RoleNameClaimType, group.Name, ClaimValueTypes.String, ClaimIssuer))); // assigned groups (names - informative)
                }

                return identity;
            }
        }
开发者ID:jechtom,项目名称:DevUpdater,代码行数:32,代码来源:SecurityService.cs

示例2: ConfigureOAuth

        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientAuthentication = async c=>c.Validated(),
                    OnGrantResourceOwnerCredentials = async c =>
                    {
                        using (var repo = new AuthRepository())
                        {
                            var user = await repo.FindUser(c.UserName, c.Password);
                            if (user == null)
                            {
                                c.Rejected();
                                throw new ApiException("User not existed or wrong password.");
                            }
                        }
                        var identity = new ClaimsIdentity(c.Options.AuthenticationType);
                        identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "user")});
                        if (string.Equals(c.UserName, AppConfig.Manager, StringComparison.InvariantCultureIgnoreCase))
                            identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "manager")});
                        c.Validated(identity);
                    }
                },
            });
        }
开发者ID:Malkiat-Singh,项目名称:webApiAngular,代码行数:32,代码来源:Startup.cs

示例3: GetToken

        //http://blog.asteropesystems.com/securing-web-api-requests-with-json-web-tokens/
        public string GetToken(string username, List<ActivityClaim> activityClaims)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var now = DateTime.UtcNow;
            var claims = new ClaimsIdentity(new[]
                {
                    new Claim( ClaimTypes.UserData, "IsValid", ClaimValueTypes.String ),
                    new Claim( ClaimTypes.Name, username, ClaimValueTypes.String )
                });
            claims.AddClaims(activityClaims.Select(c => new Claim(ClaimTypes.UserData, c.ToString(), ClaimValueTypes.String)));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claims,
                TokenIssuerName = "self",
                AppliesToAddress = "https://api.knowthyshelf.com",
                Lifetime = new Lifetime(now, now.AddYears(10)),
                SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TOKEN_SECURITY_KEY),
                  "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                  "http://www.w3.org/2001/04/xmlenc#sha256"),
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
开发者ID:swebgit,项目名称:know-thy-shelf,代码行数:28,代码来源:JwtProvider.cs

示例4: CreateIdentityAsync

        public Task<ClaimsIdentity> CreateIdentityAsync(User user, string authenticationType, ClaimsIdentity externalIdentity)
        {
            var identity = new ClaimsIdentity(authenticationType, ClaimTypes.Name, ClaimTypes.Role);

            identity.AddClaims(externalIdentity.Claims);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Name, ClaimValueTypes.String));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));

            if (user.IsAdmin)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "admin", ClaimValueTypes.String));
            }

            if (externalIdentity.HasClaim(claim => claim.Type == "urn:reddit:moderator_of"))
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "moderator", ClaimValueTypes.String));
            }

            if (user.IsBanned)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "banned", ClaimValueTypes.String));
            }

            return Task.FromResult(identity);
        }
开发者ID:Bringan,项目名称:RedditRankedFlairs,代码行数:25,代码来源:UserService.cs

示例5: CustomGrantValidationResult

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomGrantValidationResult"/> class.
        /// </summary>
        /// <param name="subject">The subject claim used to uniquely identifier the user.</param>
        /// <param name="authenticationMethod">The authentication method which describes the custom grant type.</param>
        /// <param name="claims">Additional claims that will be maintained in the principal.</param>
        /// <param name="identityProvider">The identity provider.</param>
        public CustomGrantValidationResult(
            string subject, 
            string authenticationMethod,
            IEnumerable<Claim> claims = null,
            string identityProvider = Constants.BuiltInIdentityProvider)
        {
            var resultClaims = new List<Claim>
            {
                new Claim(Constants.ClaimTypes.Subject, subject),
                new Claim(Constants.ClaimTypes.AuthenticationMethod, authenticationMethod),
                new Claim(Constants.ClaimTypes.IdentityProvider, identityProvider),
                new Claim(Constants.ClaimTypes.AuthenticationTime, DateTimeOffsetHelper.UtcNow.ToEpochTime().ToString(), ClaimValueTypes.Integer)
            };

            if (claims != null && claims.Any())
            {
                resultClaims.AddRange(claims.Where(x => !Constants.OidcProtocolClaimTypes.Contains(x.Type)));
            }

            var id = new ClaimsIdentity(authenticationMethod);
            id.AddClaims(resultClaims.Distinct(new ClaimComparer()));

            Principal = new ClaimsPrincipal(id);

            IsError = false;
        }
开发者ID:Rolosoft,项目名称:IdentityServer3,代码行数:33,代码来源:CustomGrantValidationResult.cs

示例6: GetOutputClaimsIdentity

        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            var outputIdentity = new ClaimsIdentity();
            IEnumerable<Claim> outputClaims;

            if (this.scopeModel.UseClaimsPolicyEngine)
            {
                IClaimsPolicyEvaluator evaluator = new ClaimsPolicyEvaluator(PolicyStoreFactory.Instance);
                outputClaims = evaluator.Evaluate(new Uri(scope.AppliesToAddress), ((ClaimsIdentity)principal.Identity).Claims);
            }
            else
            {
                outputClaims = ((ClaimsIdentity)principal.Identity).Claims;
            }

            outputIdentity.AddClaims(outputClaims);
            if (outputIdentity.Name == null && outputIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier) != null)
                outputIdentity.AddClaim(new Claim(ClaimTypes.Name, outputIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value));

            var isPersistent =
                ((ClaimsIdentity)principal.Identity).Claims.SingleOrDefault(c => c.Type == ClaimTypes.IsPersistent);
            if (isPersistent != null)
            {
                outputIdentity.AddClaim(new Claim(ClaimTypes.IsPersistent, isPersistent.Value));
            }

            return outputIdentity;
        }
开发者ID:Teleopti,项目名称:authbridge,代码行数:33,代码来源:MultiProtocolSecurityTokenService.cs

示例7: Unauthorized

        public async Task<IActionResult> Unauthorized(string returnUrl = null)
        {
            const string Issuer = "https://contoso.com";
            
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
            claims.Add(new Claim("BadgeNumber", "123456", ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(1).ToString(), ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(-1).ToString(), ClaimValueTypes.String, Issuer));
            var userIdentity = new ClaimsIdentity("SuperSecureLogin");
            userIdentity.AddClaims(claims);

            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

            return RedirectToLocal(returnUrl);
        }
开发者ID:eaardal,项目名称:AspNetAuthorizationWorkshop,代码行数:27,代码来源:AccountController.cs

示例8: Index

        public async Task<ActionResult> Index(string code)
        {
            var ctx = Request.GetOwinContext();
            var user = await ctx.Environment.GetIdentityServerPartialLoginAsync();

            if (user == null)
            {
                return View("Error");
            }

            var id = user.FindFirst("sub").Value;
            if (!(await this.userMgr.VerifyTwoFactorTokenAsync(id, "sms", code)))
            {
                ViewData["message"] = "Incorrect code";
                return View("Index");
            }

            var resumeUrl = user.FindFirst(Constants.ClaimTypes.PartialLoginReturnUrl).Value;
            var newUser = new ClaimsIdentity(user.AuthenticationType);

            var claims = user.Claims.Where(c => c.Type != "amr").ToList();
            claims.Add(new Claim("amr", "2fa"));
            newUser.AddClaims(claims);

            Request.GetOwinContext().Authentication.SignIn(newUser);
            return Redirect(resumeUrl);
        }
开发者ID:okusnadi,项目名称:eXpressIdentityServer,代码行数:27,代码来源:TwoFactorController.cs

示例9: TransformClaims

        private Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
        {
            if (!incoming.Identity.IsAuthenticated)
            {
                return Task.FromResult<ClaimsPrincipal>(incoming);
            }

            // parse incoming claims - create new principal with app claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "foo"),
                new Claim(ClaimTypes.Role, "bar")
            };

            var nameId = incoming.FindFirst(ClaimTypes.NameIdentifier);
            if (nameId != null)
            {
                claims.Add(nameId);
            }

            var thumbprint = incoming.FindFirst(ClaimTypes.Thumbprint);
            if (thumbprint != null)
            {
                claims.Add(thumbprint);
            }

            var id = new ClaimsIdentity("Application");
            id.AddClaims(claims);

            return Task.FromResult<ClaimsPrincipal>(new ClaimsPrincipal(id));
        }
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:31,代码来源:Startup.cs

示例10: GetClaimsIdentity

        private static ClaimsIdentity GetClaimsIdentity()
        {
            var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Password);

            claimsIdentity.AddClaims(GetClaims());

            return claimsIdentity;
        }
开发者ID:c4rm4x,项目名称:C4rm4x.WebApi.Test,代码行数:8,代码来源:ClaimsIdentityRetriever.cs

示例11: Configuration

        public void Configuration(IAppBuilder app) {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.Map("/identity", idsrvApp => {
                idsrvApp.UseIdentityServer(new IdentityServerOptions {
                    SiteName = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),
                    Factory = InMemoryFactory.Create(
                        users: Users.Get(),
                        clients: Clients.Get(),
                        scopes: Scopes.Get())
                });
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
                Authority = "https://localhost:44301/identity",
                ClientId = "mvc",
                Scope = "openid profile roles",
                RedirectUri = "https://localhost:44301/",
                ResponseType = "id_token",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications {
                    SecurityTokenValidated = async n => {
                        var id = n.AuthenticationTicket.Identity;

                        // we want to keep first name, last name, subject and roles
                        var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        nid.AddClaim(givenName);
                        nid.AddClaim(familyName);
                        nid.AddClaim(sub);
                        nid.AddClaims(roles);

                        // add some other app specific claim
                        nid.AddClaim(new Claim("app_specific", "some data"));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                    }
                }
            });
        }
开发者ID:daishisystems,项目名称:Daishi.Identity,代码行数:58,代码来源:Startup.cs

示例12: FindByUserId

        /// <summary>
        /// Returns a ClaimsIdentity instance given a userId
        /// </summary>
        /// <param name="userId">The user's id</param>
        /// <returns></returns>
        public ClaimsIdentity FindByUserId(string userId)
        {
            ClaimsIdentity claimsIdentity = new ClaimsIdentity();
            string commandText = "Select * from userclaims where UserId = @UserId";
            Dictionary<string, object> parameters = new Dictionary<string, object>() { { "@UserId", userId } };

            var claims = _database.ExecuteReader(commandText, parameters, this.ReadClaim);
            claimsIdentity.AddClaims(claims);

            return claimsIdentity;
        }
开发者ID:Nicholi,项目名称:AspNet.Identity.MySQL,代码行数:16,代码来源:UserClaimsTable.cs

示例13: GrantClientCredentials

        /// <summary>
        /// 当客户端Id与客户端密钥验证通过后,生成在线票据令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            identity.AddClaims(context.Scope.Select(m => new Claim("urn:oauth:scope", m)));

            AuthenticationProperties properties = new AuthenticationProperties(
                new Dictionary<string, string>() { { "as:client_id", context.ClientId } });
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
            context.Validated(ticket);
            return Task.FromResult(0);
        }
开发者ID:Dianerxiaobu,项目名称:osharp,代码行数:17,代码来源:OsharpAuthorizationServerProvider.cs

示例14: FindClaimsByUserId

        public ClaimsIdentity FindClaimsByUserId(string userId)
        {
            var result = _database.QuerySql(
                "SELECT * FROM AspNetUserClaims WHERE UserId = @userId",
                new { userId });

            var claims = new ClaimsIdentity();

            claims.AddClaims(
                result.Select(x => new Claim(x["ClaimType"].ToString(), x["ClaimValue"].ToString()))
                    .ToList());

            return claims;
        }
开发者ID:JCasterline,项目名称:AspNet.Identity.Insight,代码行数:14,代码来源:UserClaimsRepository.cs

示例15: GetOutputClaimsIdentity

        protected override ClaimsIdentity GetOutputClaimsIdentity( ClaimsPrincipal principal, RequestSecurityToken request, Scope scope )
        {
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();
            outgoingIdentity.AddClaims(principal.Claims);

            List<Role> roles = (List<Role>)HttpContext.Current.Session["User_Roles_" + principal.Identity.Name];

            RBACHelper rbacHelper = new RBACHelper();
            Permission[] permissions = rbacHelper.GetUserPermissions(Factory.Session(Factory.User(principal.Identity.Name), roles.ToArray()));

            outgoingIdentity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/permissions", Serialize(permissions)));

            return outgoingIdentity;
        }
开发者ID:driverpt,项目名称:SI-1213SI,代码行数:14,代码来源:CustomSecurityTokenService.cs


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