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


C# ClaimsIdentity.AddClaim方法代码示例

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


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

示例1: HandleTokenRequest

        public override Task HandleTokenRequest(HandleTokenRequestContext context) {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType()) {
                var user = new { Id = "users-123", UserName = "AspNet", Password = "contrib" };

                if (!string.Equals(context.Request.Username, user.UserName, StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, user.Password, StringComparison.Ordinal)) {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");

                    return Task.FromResult(0);
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(ClaimTypes.Name, user.UserName,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                context.Validate(new ClaimsPrincipal(identity));
            }

            return Task.FromResult(0);
        }
开发者ID:aspnet-contrib,项目名称:AspNet.Security.OpenIdConnect.Samples,代码行数:30,代码来源:AuthorizationProvider.cs

示例2: GrantResourceOwnerCredentials

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
开发者ID:LastSun,项目名称:WebApplication,代码行数:33,代码来源:CustomOAuthProvider.cs

示例3: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Allow CORS on the token middleware provider
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //TODO
            // Usually this would be done via dependency injection
            // But I haven't got it to work with the OWIN startup class yet
            AppDBContext _ctx = new AppDBContext();
            UserRepository _repo = new UserRepository(_ctx);

                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
开发者ID:szwork2013,项目名称:pricecomparison,代码行数:26,代码来源:SimpleAuthorizationServerProvider.cs

示例4: GrantCustomExtension

        public override async System.Threading.Tasks.Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if(context.GrantType.ToLower() == "facebook")
            {
                var fbClient = new FacebookClient(context.Parameters.Get("accesstoken"));
                dynamic mainDataResponse = await fbClient.GetTaskAsync("me", new { fields = "first_name, last_name, picture" });
                dynamic friendListResponse = await fbClient.GetTaskAsync("me/friends");
                var friendsResult = (IDictionary<string, object>)friendListResponse;
                var friendsData = (IEnumerable<object>)friendsResult["data"];
                var friendsIdList = new List<string>();
                foreach (var item in friendsData)
                {
                    var friend = (IDictionary<string, object>)item;
                    friendsIdList.Add((string)friend["id"]);
                }
                User user = await CreateOrUpdateUser(mainDataResponse.id, mainDataResponse.first_name, mainDataResponse.last_name, mainDataResponse.picture.data.url, friendsIdList);
                
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(_fbIdKey, mainDataResponse.id));
                identity.AddClaim(new Claim(_idKey, user.Id.ToString()));

                await base.GrantCustomExtension(context);
                context.Validated(identity);
            }
            return;
        }
开发者ID:Mike-Wazowski,项目名称:AgileAPI,代码行数:26,代码来源:AuthTokenProvider.cs

示例5: GrantResourceOwnerCredentials

        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            // Dummy check here, you need to do your DB checks against membership system http://bit.ly/SPAAuthCode
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                //return;
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity("JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

            var props =
                new AuthenticationProperties(
                    new Dictionary<string, string>
                        {
                            {
                                "audience",
                                context.ClientId ?? string.Empty
                            }
                        });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }
开发者ID:AdaskoTheBeAsT,项目名称:JWTAspNetWebApi,代码行数:33,代码来源:CustomOAuthProvider.cs

示例6: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

                var roles = await _repo.FindUserRoles(user.Id);

                foreach (var r in roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, r));
                }
                //identity.AddClaim(new Claim("sub", context.UserName));
                
                context.Validated(identity);
            }
        }
开发者ID:mofajke,项目名称:geopges,代码行数:29,代码来源:SimpleAuthorizationServerProider.cs

示例7: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (var projectContext = new ProjectContext())
            {
                using (var unitOfWork = new UnitOfWork(projectContext))
                {
                    IdentityUser user = await unitOfWork.Users.FindUser(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                }
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
开发者ID:smalpik,项目名称:Store,代码行数:27,代码来源:SimpleAuthorizationServerProvider.cs

示例8: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
			string userId;
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuctionDbRepository repo = new AuctionDbRepository())
            {
                IdentityUser user = await repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

				userId = user.Id;
            }

			//Use this in test propose
			//using (UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new AuctionDb())))
			//{
			//	var ident = manager.Find(context.UserName, context.Password);
			//	var userIdentity = await manager.CreateIdentityAsync(ident, "Bearer");
			//	context.Validated(userIdentity);
			//}

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
			identity.AddClaim(new Claim("userIdString", userId));
			identity.AddClaim(new Claim("sub", context.UserName));
			identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);
        }
开发者ID:CatOkHero,项目名称:GlobalWebAuction,代码行数:32,代码来源:SimpleAuthorizationServerProvider.cs

示例9: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                Usuario user = _usuarioAppService.Get(el => el.Login == context.UserName && el.Senha == context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "Usuário ou Senha inválidos.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.NomeUsuario));

                var roles = new List<string>();
                roles.Add("User");

                foreach (var item in roles)
                    identity.AddClaim(new Claim(ClaimTypes.Role, item));

                GenericPrincipal principal = new GenericPrincipal(identity, roles.ToArray());
                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }
开发者ID:renant,项目名称:LearnAngularDDD,代码行数:33,代码来源:SimpleAuthorizationServerPro2vider.cs

示例10: GrantResourceOwnerCredentials

        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
        /// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
        /// optional "refresh_token". If the web application supports the
        /// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
        /// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
        /// with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers.
        /// The default behavior is to reject this grant type.
        /// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

            string actorType;
            using (var repo = new AuthorisationRepository())
            {
                var user = await repo.FindUser(context.UserName, context.Password); //actual authentication here

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                actorType = user.Claims.First(x => x.ClaimType == ClaimTypes.Actor).ClaimValue;

                context.OwinContext.Set("user_type", actorType);
                //determine if it's a buyer or a seller
            }

            //useful info to include in the token here
           
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            identity.AddClaim(new Claim("actor", actorType));

            context.Validated(identity);
        }
开发者ID:ns6482,项目名称:practice3,代码行数:44,代码来源:PbAuthorizationServerProvider.cs

示例11: GrantResourceOwnerCredentials

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     // SharePoint...
     using (ClientContext ctx = new ClientContext(Constants.SPURL))
     {
         ctx.Credentials = new NetworkCredential(context.UserName, context.Password);
         var u = ctx.Web.CurrentUser;
         ctx.Load(u, _ => _.Title);
         try
         {
             ctx.ExecuteQuery();
             var identity = new ClaimsIdentity(context.Options.AuthenticationType);
             identity.AddClaim(new Claim("user", u.Title));
             identity.AddClaim(new Claim("login", EncryptionHelper.Encrypt(context.UserName)));
             identity.AddClaim(new Claim("pw", EncryptionHelper.Encrypt(context.Password)));
             context.Validated(identity);
         }
         catch (Exception ex)
         {
            
             context.SetError("invalid_grant", "Invalid UserName or Password");
         }
     }
 }
开发者ID:ppedv-MG,项目名称:CrossPlatformDemo,代码行数:25,代码来源:SharePointAuthorizationServerProvider.cs

示例12: GrantResourceOwnerCredentials

        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". 
        /// This occurs when the user has provided name and password credentials directly into the 
        /// client application's user interface, and the client application is using those to acquire an 
        /// "access_token" and optional "refresh_token". If the web application supports the resource owner 
        /// credentials grant type it must validate the context.Username and context.Password as appropriate. 
        /// To issue an access token the context.Validated must be called with a new ticket containing the 
        /// claims about the resource owner which should be associated with the access token. 
        /// The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers. 
        /// The default behavior is to reject this grant type. See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type" });

            if (context.UserName == "Pussy" && context.Password == "Cat")
            {


                // create identity
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", "test"));
                identity.AddClaim(new Claim("role", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

                // create metadata to pass on to refresh token provider
                var props = new AuthenticationProperties(new Dictionary<string, string>
                    {
                        { "as:client_id", context.ClientId }
                    });

                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
                //context.Validated(identity);
                return;
            }
            context.Rejected();
        }
开发者ID:jango2015,项目名称:WebApiBearerToken,代码行数:40,代码来源:SimpleAuthorizationServerProvider.cs

示例13: TokenBuilder

 public TokenBuilder(string userId, string username, string role)
 {
     this.Identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
     Identity.AddClaim(new Claim(ClaimTypes.Name, username));
     Identity.AddClaim(new Claim("role", role));
     Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
 }
开发者ID:dmacan23,项目名称:FireBreathingRubberDuckies---Sensei,代码行数:7,代码来源:TokenBuilder.cs

示例14: DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes

        public void DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes()
        {
            var identity = new ClaimsIdentity();
            identity.AddClaim(new Claim(ClaimTypes.Email, "[email protected]"));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, "some"));
            identity.AddClaim(new Claim(ClaimTypes.Surname, "one"));
#if DNX451
            // CoreCLR doesn't support an 'empty' name
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty));
#endif

            // Arrange
            var claimsIdentity = (ClaimsIdentity)identity;

            // Act
            var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity)
                                                              .ToArray();
            var claims = claimsIdentity.Claims.ToList();
            claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal));

            // Assert
            int index = 0;
            foreach (var claim in claims)
            {
                Assert.Equal(identiferParameters[index++], claim.Type);
                Assert.Equal(identiferParameters[index++], claim.Value);
            }
        }
开发者ID:5280Software,项目名称:Antiforgery,代码行数:28,代码来源:DefaultClaimUidExtractorTest.cs

示例15: GrantResourceOwnerCredentials

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            IdentityUser user;
            using (var _repo = new AuthRepository())
            {
                user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("userId", user.Id));

            if (user.Id == "c417fc8e-5bae-410f-b2ee-463afe2fdeaa")
                identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "userId", user.Id
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);

        }
开发者ID:SashaBezugliy,项目名称:WebAPI,代码行数:34,代码来源:SimpleAuthorizationServerProvider.cs


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