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


C# ClaimsIdentity.FindFirst方法代码示例

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


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

示例1: Start

 public Operation Start(string name, ClaimsIdentity identity)
 {
     try
     {
         var timestamp = DateTime.UtcNow;
         identity = identity ?? new ClaimsIdentity();
         var sid = identity.FindFirst(UserClaim.Types.UserId);
         var userId = sid == null ? null : (Guid?)Guid.Parse(sid.Value);
         var clientIdClaim = identity.FindFirst(UserClaim.Types.ClientId);
         var clientId = clientIdClaim == null ? null : clientIdClaim.Value;
         var operationId = new SqlParameter("@Id", SqlDbType.UniqueIdentifier) {Direction = ParameterDirection.Output};
         var userIdSql = new SqlParameter("@AppUserId", (object)userId ?? DBNull.Value) {DbType = DbType.Guid};
         var appClientIdSql = new SqlParameter("@AppClientId", (object)clientId ?? DBNull.Value);
         var startedUtc = new SqlParameter("@StartedUtc", timestamp);
         var nameSql = new SqlParameter("@Name", SqlDbType.NVarChar, Restrict.Length.Name) {Value = (object)name ?? DBNull.Value};
         const string sql =
             @"EXEC [App].[StartOperation] @Id = @Id OUTPUT, @StartedUtc = @StartedUtc, @Name = @Name, @AppUserId = @AppUserId, @AppClientId = @AppClientId";
         Context.Database.ExecuteSqlCommand(sql, operationId, userIdSql, appClientIdSql, startedUtc, nameSql);
         var operation = Context.Set<Operation>().Find(operationId.Value);
         return operation;
     }
     catch (Exception ex)
     {
         throw new RepositoryException("Can't take operation marker from the db.", ex);
     }
 }
开发者ID:al-main,项目名称:vabank,代码行数:26,代码来源:OperationRepository.cs

示例2: FromIdentity

        public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
        {
            if (identity == null)
            {
                return null;
            }

            var providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

            if (providerKeyClaim == null || string.IsNullOrWhiteSpace(providerKeyClaim.Issuer) || string.IsNullOrWhiteSpace(providerKeyClaim.Value))
            {
                return null;
            }

            if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
            {
                return null;
            }

            return new ExternalLoginData
            {
                LoginProvider = providerKeyClaim.Issuer,
                ProviderKey = providerKeyClaim.Value,
                Username = identity.FindFirst(ClaimTypes.Name).Value,
                ExternalAccessToken = identity.FindFirst("ExternalAccessToken").Value
            };
        }
开发者ID:huoxudong125,项目名称:Moviepicker,代码行数:27,代码来源:ExternalLoginData.cs

示例3: GetGroups

        public static async Task<List<string>> GetGroups(ClaimsIdentity claimsId)
        {
            if (claimsId.FindFirst("_claim_names") != null
                && (Json.Decode(claimsId.FindFirst("_claim_names").Value)).groups != null)
                return await GetGroupsFromGraphAPI(claimsId);

            return claimsId.FindAll("groups").Select(c => c.Value).ToList();
        }
开发者ID:EgyTechnology,项目名称:WebApp-GroupClaims-DotNet,代码行数:8,代码来源:ClaimHelper.cs

示例4: GetMemberGroups

        /// <summary>
        /// For access check user's group membership must be determined. 
        /// This method retrieves user's group membership from Azure AD Graph API if not present in the token.
        /// </summary>
        /// <param name="claimsIdentity">The <see cref="ClaimsIdenity" /> object that represents the 
        /// claims-based identity of the currently signed in user and contains thier claims.</param>
        /// <returns>A list of ObjectIDs representing the groups that the user is member of.</returns>
        public static async Task<List<string>> GetMemberGroups(ClaimsIdentity claimsIdentity)
        {
            //check for groups overage claim. If present query graph API for group membership
            if (claimsIdentity.FindFirst("_claim_names") != null
                && (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups != null)
                return await GetGroupsFromGraphAPI(claimsIdentity);

            return claimsIdentity.FindAll("groups").Select(c => c.Value).ToList();
        }
开发者ID:tandis,项目名称:PnP,代码行数:16,代码来源:GraphUtil.cs

示例5: isDeviceAuthorized

 private bool isDeviceAuthorized(ClaimsIdentity identity)
 {
     Claim first1 = identity.FindFirst("Dsvn:DeviceKey");
     if (first1 != null && !string.IsNullOrEmpty(first1.Value))
     {
         if (string.IsNullOrEmpty(this.DeviceGroup))
             return true;
         Claim first2 = identity.FindFirst("Dsvn:DeviceGroups");
         if (first2 != null && !string.IsNullOrEmpty(first2.Value))
             return Enumerable.Contains<string>((IEnumerable<string>)first2.Value.Split(','), this.DeviceGroup);
     }
     return false;
 }
开发者ID:quangnc0503h,项目名称:ecommerce,代码行数:13,代码来源:WebAuthorizeAttribute.cs

示例6: GetGroupsFromGraphAPI

        private static async Task<List<string>> GetGroupsFromGraphAPI(ClaimsIdentity claimsIdentity)
        {
            List<string> groupObjectIds = new List<string>();

            // Acquire the Access Token
            ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);

            // MULTITENANT - Since I've set Tenant=common, we can't use the regular Authority here, we need the user's tenant
            // AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority,
            //    new TokenDbCache(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value));
            string userAuthority = String.Format(CultureInfo.InvariantCulture,
                ConfigHelper.AadInstance,
                ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value);
            AuthenticationContext authContext = new AuthenticationContext(userAuthority,
                new TokenDbCache(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value));

            AuthenticationResult result = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, credential,
                new UserIdentifier(claimsIdentity.FindFirst(Globals.ObjectIdClaimType).Value, UserIdentifierType.UniqueId));

            // Get the GraphAPI Group Endpoint for the specific user from the _claim_sources claim in token
            string groupsClaimSourceIndex = (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups;
            var groupClaimsSource = (Json.Decode(claimsIdentity.FindFirst("_claim_sources").Value))[groupsClaimSourceIndex];
            string requestUrl = groupClaimsSource.endpoint + "?api-version=" + ConfigHelper.GraphApiVersion;

            // Prepare and Make the POST request
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            StringContent content = new StringContent("{\"securityEnabledOnly\": \"false\"}");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content = content;
            HttpResponseMessage response = await client.SendAsync(request);

            // Endpoint returns JSON with an array of Group ObjectIDs
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                var groupsResult = (Json.Decode(responseContent)).value;

                foreach (string groupObjectID in groupsResult)
                    groupObjectIds.Add(groupObjectID);
            }
            else
            {
                throw new WebException();
            }

            return groupObjectIds;
        }
开发者ID:EgyTechnology,项目名称:WebApp-GroupClaims-DotNet,代码行数:49,代码来源:ClaimHelper.cs

示例7: Parse

        public ExternalLoginData Parse(ClaimsIdentity identity)
        {
            if (identity == null)
            {
                return null;
            }

            var nameClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
            if (nameClaim == null || String.IsNullOrEmpty(nameClaim.Issuer) || String.IsNullOrEmpty(nameClaim.Value))
            {
                throw new ApplicationException("Cannot find a claim of ClaimTypes.NameIdentifier");
            }

            if (nameClaim.Issuer == ClaimsIdentity.DefaultIssuer)
            {
                return null;
            }

            var loginData = new ExternalLoginData
                {
                    ProviderName = nameClaim.Issuer,
                    ProviderKey = nameClaim.Value,
                    Name = identity.GetFirstOrDefault(ClaimTypes.Name),
                    Email = identity.GetFirstOrDefault(ClaimTypes.Email),
                };

            ParseDetailLoginData(identity, ref loginData);

            return loginData;
        }
开发者ID:netvietdev,项目名称:RabbitOwinSecurity,代码行数:30,代码来源:OAuthLoginDataParser.cs

示例8: AuthorizeUser

        public async Task<bool> AuthorizeUser(ClaimsIdentity identity, Guid orgId)
        {
            var email = identity.FindFirst(c => c.Type == ClaimTypes.Email)?.Value;
            if (string.IsNullOrEmpty(email) == false)
            {
                using (var session = _store.QuerySession())
                {
                    Organization org = null;

                    var user = await session.Query<User>()
                        .Include<Organization>(u => u.OrganizationId, o => org = o)
                        .Where(u => u.OrganizationId == orgId)
                        .SingleOrDefaultAsync(u => u.EmailAddress.Equals(email, StringComparison.CurrentCultureIgnoreCase));

                    if (user != null)
                    {
                        identity.AddClaim(new Claim("dg:role", user.Role));
                        identity.AddClaim(new Claim("dg:org", org.Slug));
                        identity.AddClaim(new Claim("dg:userId", user.Id.ToString()));
                        
                        return true;
                    }
                }
            }

            // can't find account so return empty claims
            // this will force authentication failure
            return false;
        }
开发者ID:HopeNB,项目名称:web,代码行数:29,代码来源:AuthManager.cs

示例9: GetUniqueIdentifierParameters

        internal static IEnumerable<string> GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity)
        {
            var nameIdentifierClaim = claimsIdentity.FindFirst(claim =>
                                                            String.Equals(ClaimTypes.NameIdentifier,
                                                                        claim.Type, StringComparison.Ordinal));
            if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value))
            {
                return new string[]
                {
                    ClaimTypes.NameIdentifier,
                    nameIdentifierClaim.Value
                };
            }

            // We Do not understand this claimsIdentity, fallback on serializing the entire claims Identity.
            var claims = claimsIdentity.Claims.ToList();
            claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal));
            var identifierParameters = new List<string>();
            foreach (var claim in claims)
            {
                identifierParameters.Add(claim.Type);
                identifierParameters.Add(claim.Value);
            }

            return identifierParameters;
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:26,代码来源:DefaultClaimUidExtractor.cs

示例10: GetRegisteredUserInfo

        public XcendentUser GetRegisteredUserInfo(ClaimsIdentity identity)
        {
            var url = @"https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + identity.FindFirst("ExternalAccessToken");


            throw new NotImplementedException();
        }
开发者ID:nandithakw,项目名称:hasl,代码行数:7,代码来源:GoogleUserDetailsProvider.cs

示例11: FromIdentity

        public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
        {
            if (identity == null)
            {
                return null;
            }

            Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

            if (providerKeyClaim == null || string.IsNullOrEmpty(providerKeyClaim.Issuer)
                || string.IsNullOrEmpty(providerKeyClaim.Value))
            {
                return null;
            }

            if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
            {
                return null;
            }

            return new ExternalLoginData
            {
                LoginProvider = providerKeyClaim.Issuer,
                ProviderKey = providerKeyClaim.Value,
                UserName = identity.FindFirstValue(ClaimTypes.Name)
            };
        }
开发者ID:kidroca,项目名称:project-quiz-mvc,代码行数:27,代码来源:ExternalLoginData.cs

示例12: CreateLoginToken

        public virtual JwtSecurityToken CreateLoginToken(string secretKey, ClaimsIdentity claimsIdentity, ProviderCredentials providerCredentials)
        {
            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentNullException("secretKey");
            }

            if (claimsIdentity == null)
            {
                throw new ArgumentNullException("claimsIdentity");
            }

            if (providerCredentials == null)
            {
                throw new ArgumentNullException("providerCredentials");
            }

            var providerKeyClaim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
            if (providerKeyClaim == null)
            {
                throw new ArgumentException("RResources.Token_Invalid.FormatForUser(claimsIdentity.Name, ClaimTypes.NameIdentifier)");
            }

            var uid = providerKeyClaim.Value;
            var credentialsClaimJson = JsonConvert.SerializeObject(providerCredentials, Formatting.None, this.tokenSerializerSettings);

            var claims = new List<Claim>();
            claims.Add(new Claim(ProviderCredentialsClaimName, credentialsClaimJson));
            claims.Add(new Claim("uid", uid));
            claims.Add(new Claim("ver", "1"));

            return this.CreateTokenFromClaims(claims, secretKey, ZumoAudienceValue, ZumoIssuerValue);
        }
开发者ID:NewforceComputerTechnologies,项目名称:DevCamp,代码行数:33,代码来源:TokenUtility.cs

示例13: FromIdentity

        public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
        {
            if (identity == null)
            {
                return null;
            }

            Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

            if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value))
            {
                return null;
            }

            if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
            {
                return null;
            }

            return new ExternalLoginData
            {
                LoginProvider = providerKeyClaim.Issuer,
                ProviderKey = providerKeyClaim.Value,
                UserName = identity.FindFirstValue(ClaimTypes.Name),
                ExternalAccessToken = identity.FindFirstValue(GenericNames.AUTHENTICATION_EXTERNAL_LOGIN),
            };
        }
开发者ID:charla-n,项目名称:ManahostManager,代码行数:27,代码来源:ExternalLoginData.cs

示例14: GetGroupsFromGraphAPI

        /// <summary>
        /// In the case of Groups claim overage, we must query the GraphAPI to obtain the group membership.
        /// Here we use the GraphAPI Client Library to do so.
        /// </summary>
        /// <param name="claimsIdentity">The <see cref="ClaimsIdenity" /> object that represents the 
        /// claims-based identity of the currently signed in user and contains thier claims.</param>
        /// <returns>A list of ObjectIDs representing the groups that the user is member of.</returns>
        private static async Task<List<string>> GetGroupsFromGraphAPI(ClaimsIdentity claimsIdentity)
        {
            List<string> groupObjectIds = new List<string>();

            string tenantId = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserID = claimsIdentity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
            string userObjectID = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // Aquire Access Token to call Graph
            ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);
            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
            AuthenticationContext authContext = new AuthenticationContext(
                string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserID));
            AuthenticationResult result = authContext.AcquireTokenSilent(
                ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"], credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            // Get the GraphAPI Group Endpoint for the specific user from the _claim_sources claim in token
            string groupsClaimSourceIndex = (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups;
            var groupClaimsSource = (Json.Decode(claimsIdentity.FindFirst("_claim_sources").Value))[groupsClaimSourceIndex];
            string requestUrl = groupClaimsSource.endpoint + "?api-version=" + ConfigurationManager.AppSettings["ida:GraphAPIVersion"];

            // Prepare and Make the POST request
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            StringContent content = new StringContent("{\"securityEnabledOnly\": \"false\"}");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content = content;
            HttpResponseMessage response = await client.SendAsync(request);

            // Endpoint returns JSON with an array of Group ObjectIDs
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                var groupsResult = (Json.Decode(responseContent)).value;

                foreach (string groupObjectID in groupsResult)
                    groupObjectIds.Add(groupObjectID);
            }
            else
            {
                throw new WebException();
            }

            return groupObjectIds;
        }
开发者ID:bstearns,项目名称:VipSwapper,代码行数:54,代码来源:GraphUtil.cs

示例15: CheckAndPossiblyRefreshToken

        private static async void CheckAndPossiblyRefreshToken(ClaimsIdentity id)
        {
            // check if the access token hasn't expired.
            if (DateTime.Now.ToLocalTime() >=
                 (DateTime.Parse(id.FindFirst("expires_at").Value)))
            {
                // expired.  Get a new one.
                var tokenEndpointClient = new OAuth2Client(
                    new Uri(ExpenseTrackerConstants.IdSrvToken),
                    "mvc",
                    "secret");

                var tokenEndpointResponse = 
                    await tokenEndpointClient
                    .RequestRefreshTokenAsync(id.FindFirst("refresh_token").Value);

                if (!tokenEndpointResponse.IsError)
                {
                    // replace the claims with the new values - this means creating a 
                    // new identity!                              
                    var result = from claim in id.Claims
                                 where claim.Type != "access_token" && claim.Type != "refresh_token" &&
                                       claim.Type != "expires_at"
                                 select claim;

                    var claims = result.ToList();

                    claims.Add(new Claim("access_token", tokenEndpointResponse.AccessToken));
                    claims.Add(new Claim("expires_at",
                                 DateTime.Now.AddSeconds(tokenEndpointResponse.ExpiresIn)
                                 .ToLocalTime().ToString()));
                    claims.Add(new Claim("refresh_token", tokenEndpointResponse.RefreshToken));

                    var newIdentity = new ClaimsIdentity(claims, "Cookies");
                    var wrapper = new HttpRequestWrapper(HttpContext.Current.Request);
                    wrapper.GetOwinContext().Authentication.SignIn(newIdentity);
                }
                else
                {
                    // log, ...
                    throw new Exception("An error has occurred");
                }
            }
             

           
        }
开发者ID:bkcrux,项目名称:WebAPIDemo,代码行数:47,代码来源:ExpenseTrackerHttpClient.cs


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