/// <summary> /// Validates credentials with identity name. /// </summary> /// <param name="identityName">Name of the identity.</param> public void Validated(string identityName = null) { IdentityName = identityName; Identity.AddClaim(new Claim(ClaimTypes.Name, identityName)); IsValidated = true; HasError = false; }
public void GivenUserIdentityIsInvalidType_WhenIViewProfile_ThenThrowException() { string userIdentifier = "thisisanewuser"; Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentifier)); MockHttpContext.Expect(m => m.User).Return(new ClaimsPrincipal(new ClaimsIdentity[] { Identity })); Target.ExpectException <InvalidCastException>(() => Target.UserProfile()); }
//public CustomPrincipal(string firstName, string lastName, string badge, string cardNumber, string sessionId) : base(new GenericIdentity(badge)) //{ // Logger.WriteDebug("SessionId:" + sessionId); // var hasAccess = false; // var key = $"{firstName}_{lastName}_{badge}_{cardNumber}_{sessionId}"; // if (Cache.Get(key) is bool cacheFound) // hasAccess = cacheFound; // else // { // hasAccess = AsyncHelpers.RunSync(async () => // { // using (var service = new OperatorHandler()) // { // return await service.IsValidSessionAsync(firstName, lastName, badge, sessionId); // } // }); // Cache.Add(key, hasAccess, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); // } // if (!hasAccess) // throw new UnauthorizedAccessException(); //} public CustomPrincipal(string badge, string deviceGuid, string sessionId) : base(new GenericIdentity(badge)) { Logger.WriteDebug($"Badge: {badge}, SessionId: {sessionId}, deviceGuid: {deviceGuid}"); var hasAccess = false; var jobTitle = ""; var user = ""; var key = $"{badge}_{sessionId}"; if (Cache.Get(key) is Tuple <bool, string, string> cacheFound) { hasAccess = cacheFound.Item1; jobTitle = cacheFound.Item2; user = cacheFound.Item3; } else { hasAccess = AsyncHelpers.RunSync(async() => { using (var service = new OperatorHandler()) { var result = await service.IsValidSessionAsync(badge, deviceGuid, sessionId); jobTitle = result.Item2; user = result.Item3; return(result.Item1); } }); Cache.Add(key, new Tuple <bool, string, string>(hasAccess, jobTitle, user), null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } if (!hasAccess) { throw new UnauthorizedAccessException(); } var claims = new List <Claim>(); Identity.AddClaim(new Claim("JobTitle", jobTitle)); Identity.AddClaim(new Claim("User", user)); }
private async Task BuildTheIdentity(IKeyValueSettings settings, Messages messages, object parameter = null) { // Check if we have a provider registered. if (!Container.TryResolve(settings.Values[ProviderKey], out ITokenProvider provider)) { throw new NotSupportedException($"The principal cannot be created. We are missing an account provider: {settings.Values[ProviderKey]}"); } // Check the settings contains the service url. TokenInfo token = null; try { token = await provider.GetTokenAsync(settings, parameter).ConfigureAwait(true); } catch (Exception ex) { Logger.Technical.From <AppPrincipalFactory>().Exception(ex).Log(); } if (null != token) { // The token has claims filled by the STS. // We can fill the new federated identity with the claims from the token. var jwtToken = new JwtSecurityToken(token.AccessToken); var expTokenClaim = jwtToken.Claims.FirstOrDefault(c => c.Type.Equals(tokenExpirationClaimType, StringComparison.InvariantCultureIgnoreCase)); long expTokenTicks = 0; if (null != expTokenClaim) { long.TryParse(expTokenClaim.Value, out expTokenTicks); } Identity.BootstrapContext = token.AccessToken; // The key for the cache is based on the claims from a ClaimsIdentity => build a dummy identity with the claim from the token. var identity = new ClaimsIdentity(jwtToken.Claims); cachedClaims = GetClaimsFromCache(identity); // if we have a token "cached" from the system, we can take the authorization claims from the cache (if exists)... // so we avoid too many backend calls for nothing. // But every time we have a token that has been refreshed, we will call the backend (if available and reload the claims). var cachedExpiredClaim = cachedClaims.FirstOrDefault(c => c.ClaimType.Equals(tokenExpirationClaimType, StringComparison.InvariantCultureIgnoreCase)); long cachedExpiredTicks = 0; if (null != cachedExpiredClaim) { long.TryParse(cachedExpiredClaim.Value, out cachedExpiredTicks); } // we only call the backend if the ticks are not the same. copyClaimsFromCache = cachedExpiredTicks > 0 && expTokenTicks > 0 && cachedClaims.Count > 0 && cachedExpiredTicks == expTokenTicks; if (copyClaimsFromCache) { Identity.AddClaims(cachedClaims.Select(p => new Claim(p.ClaimType, p.Value))); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, "Create the principal from the cache, token has not been refreshed.")); } else { // Fill the claims based on the token and the backend call Identity.AddClaims(jwtToken.Claims.Where(c => !ClaimsToExclude.Any(arg => arg.Equals(c.Type))).Select(c => new Claim(c.Type, c.Value))); Identity.AddClaim(expTokenClaim); if (Container.TryResolve(out IClaimsFiller claimFiller)) // Fill the claims with more information. { try { // Get the claims and clean any technical claims in case of. var claims = (await claimFiller.GetAsync(Identity, new List <IKeyValueSettings> { settings }, parameter)) .Where(c => !ClaimsToExclude.Any(arg => arg.Equals(c.ClaimType))).ToList(); // We copy the claims from the backend but the exp claim will be the value of the token (front end definition) and not the backend one. Otherwhise there will be always a difference. Identity.AddClaims(claims.Where(c => !Identity.Claims.Any(c1 => c1.Type == c.ClaimType)).Select(c => new Claim(c.ClaimType, c.Value))); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, $"Add {claims.Count()} claims to the principal.")); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, $"Save claims to the cache.")); } catch (Exception e) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, e.ToString())); } } SaveClaimsToCache(Identity.Claims); } } else { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "The call to identify the user has failed. Token is null!")); } }