/// <summary> /// Add a claim /// </summary> public void AddClaim(IClaim claim) { if (!this.m_claims.Any(c => c.Type == claim.Type && c.Value == claim.Value)) { this.m_claims.Add(claim); } }
private IClaim GetTestClaim() { claim = new Claim(); var claimant = MockRepository.GenerateStub<IClaimant>(); claim.Claimant = claimant; return claim; }
public void Unclaim(IClaim claim) { BB.AssertNotNull(claim); BB.Assert(claims.Contains(claim)); claim.Unclaim(); claims.Remove(claim); }
public void Should_increase_original_premium_by_20_percent_when_driver_is_24() { const double expected = 600.00; const double increaseAmount = 0.2; const int startingYoungAge = 21; const int endingYoungAge = 25; const string driverName = "name"; const string occupation = "occupation"; const string secondDriverName = "name2"; const double premium = 500.00; var todayProvider = new GenericStubProvider <DateTime>(new[] { DateTime.Today, DateTime.Today }); var driverDateOfBirth = DateTime.Now.AddYears(-25); var driversDateOfBirth = DateTime.Now.AddYears(-40); var driverClaims = new IClaim[0]; var secondDriversClaims = new IClaim[0]; var driversAndPremiumToUpdatedPremiumForYoungDrivers = new DriversAndPremiumToUpdatedPremiumForYoungDrivers(startingYoungAge, endingYoungAge, todayProvider, increaseAmount); var firstDriver = new DriverStub(driverName, occupation, driverDateOfBirth, driverClaims); var secondDriver = new DriverStub(secondDriverName, occupation, driversDateOfBirth, secondDriversClaims); var drivers = new [] { firstDriver, secondDriver }; var driversAndPremium = new DriverAndPremium(firstDriver, premium); var actual = driversAndPremiumToUpdatedPremiumForYoungDrivers.Transform(driversAndPremium); Assert.AreEqual(expected, actual); }
/// <summary> /// Suppression d'un droit à l'utilisateur. /// </summary> /// <param name="claim">Droit.</param> public void RemoveClaim(IClaim claim) { if (claims.ContainsKey(claim.Id)) { claims.Remove(claim.Id); } }
/// <summary> /// Ajout d'un droit. /// </summary> /// <param name="claim">Droit.</param> public void AddClaim(IClaim claim) { if (!claims.ContainsKey(claim.Id)) { claims[claim.Id] = claim; } }
public LikeArticleController(IArticleRepository repo, IUserRepository userRepo, ILikeRepository likeRepo, IClaim clame) { _repo = repo; _userRepo = userRepo; _likeRepo = likeRepo; _clame = clame; }
public IClaim ClaimConfiguration(IClaim claim) { claim.Product = mSettings.Product; claim.Version = mSettings.Version; claim.Context = mSettings.Context; claim.Process = mSettings.Process; return(claim); }
public void Set <T>(IClaim <T> claim) { if (claims.ContainsKey(claim.Name)) { claims[claim.Name] = claim; } else { claims.Add(claim.Name, claim); } }
public IClaim Read(Guid id) { var contacts = _dbContext.contact.ToList(); var vehicles = _dbContext.vehicle.ToList(); var claimContactVehicles = _dbContext.claimContactVehicle.ToList(); Claim fromDb = _dbContext.claim.FirstOrDefault(x => x.ClaimId == id) ?? throw new Exception("Claim not found"); IClaim viewModel = ConvertToViewModel(fromDb); return(viewModel); }
public string GetToken(IClaim credentialClaim) { var token = new JwtSecurityToken (issuer: "http://www.example.com" , audience: "MyAudience" , claims: credentialClaim.GetClaims() , notBefore: DateTime.UtcNow , expires: DateTime.UtcNow.AddHours(24) , signingCredentials: CreateSigningCredentials()); var tokenHandler = new JwtSecurityTokenHandler(); string tokenString = tokenHandler.WriteToken(token); return(tokenString); }
/// <summary> /// As date time /// </summary> public static DateTime AsDateTime(this IClaim me) { if (!DateTime.TryParse(me.Value, out var value)) { if (Int32.TryParse(me.Value, out int offset)) { value = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(offset).ToLocalTime(); } else { throw new ArgumentOutOfRangeException(nameof(IClaim.Value)); } } return(value); }
public void Should_return_original_premium_when_driver_is_not_an_Accountant() { const double expected = 500.00; const double decreaseAmount = 0.1; const string driversName = "name"; const string driversOccupation = "Electrician"; var driversDateOfBirth = DateTime.Now; var driversClaims = new IClaim[0]; var jobsWherePremiumIsDecreased = new [] { "Accountant" }; var driversAndPremiumToDecreasedPremiumBasedOnOccupationTransform = new DriversAndPremiumToDecreasedPremiumBasedOnOccupationTransform(jobsWherePremiumIsDecreased, decreaseAmount); var firstDriver = new DriverStub(driversName, driversOccupation, driversDateOfBirth, driversClaims); var driverAndPremium = new DriverAndPremium(firstDriver, expected); var actual = driversAndPremiumToDecreasedPremiumBasedOnOccupationTransform.Transform(driverAndPremium); Assert.AreEqual(expected, actual); }
public void Should_return_original_premium_when_neither_driver_is_a_chauffeur() { const double increaseAmount = 0.1; const double expected = 500.00; const string driversName = "name"; const string driversOccupation = "Mechanic"; var driversDateOfBirth = DateTime.Now; var driversClaims = new IClaim[0]; var jobsWherePremiumIsIncreased = new [] { "Chauffeur" }; var driversAndPremiumToIncreasedPremiumBasedOnOccupationTransform = new DriversAndPremiumToIncreasedPremiumBasedOnOccupationTransform(jobsWherePremiumIsIncreased, increaseAmount); var driver = new DriverStub(driversName, driversOccupation, driversDateOfBirth, driversClaims); var driverAndPremium = new DriverAndPremium(driver, expected); var actual = driversAndPremiumToIncreasedPremiumBasedOnOccupationTransform.Transform(driverAndPremium); Assert.AreEqual(expected, actual); }
public void Should_return_result_of_premium_after_adult_calculation() { const string name = "name"; const string occupation = "occupation"; const double expected = 660.00; const double premium = 500.00; var claims = new IClaim[0]; var dateOfBirth = DateTime.Now; var driversAndPremiumToUpdatedPremiumForAdultDrivers = new GenericStubTransform <DriverAndPremium, double>(expected); var driversAndPremiumToUpdatedPremiumForYoungDrivers = new GenericStubTransform <DriverAndPremium, double>(expected); var driversAndPremiumToUpdatedPremiumBasedOnAgeTransform = new DriversAndPremiumToUpdatedPremiumBasedOnAgeTransform(driversAndPremiumToUpdatedPremiumForYoungDrivers, driversAndPremiumToUpdatedPremiumForAdultDrivers); var driver = new DriverStub(name, occupation, dateOfBirth, claims); var actual = driversAndPremiumToUpdatedPremiumBasedOnAgeTransform.Transform(new DriverAndPremium(driver, premium)); Assert.AreEqual(expected, actual); }
public void Should_return_the_result_of_driversAndPremiumToDecreasedPremiumBasedOnOccupationTransform() { const double premium = 500.00; const string driverName = "name"; const string driverOccupation = "occupation"; var driversDateOfBirth = DateTime.Now; var claims = new IClaim[0]; var drivers = new DriverStub(driverName, driverOccupation, driversDateOfBirth, claims); const double expected = 660.00; var driversAndPremium = new DriverAndPremium(drivers, premium); var driversAndPremiumToIncreasedPremiumBasedOnOccupationTransform = new GenericStubTransform <DriverAndPremium, double>(premium); var driversAndPremiumToDecreasedPremiumBasedOnOccupationTransform = new GenericStubTransform <DriverAndPremium, double>(expected); var driversAndPremiumToUpdatedPremiumBasedOnOccupationTransform = new DriversAndPremiumToUpdatedPremiumBasedOnOccupationTransform(driversAndPremiumToIncreasedPremiumBasedOnOccupationTransform, driversAndPremiumToDecreasedPremiumBasedOnOccupationTransform); var actual = driversAndPremiumToUpdatedPremiumBasedOnOccupationTransform.Transform(driversAndPremium); Assert.AreEqual(expected, actual); }
public void Should_return_original_premium_when_driver_is_younger_than_26() { const double increaseAmount = 0.1; const int startingAdultAge = 26; const int endingAdultAge = 75; const string driverName = "name"; const string occupation = "occupation"; const double expected = 500.00; var todayProvider = new GenericStubProvider <DateTime>(new[] { DateTime.Today, DateTime.Today }); var driverDateOfBirth = DateTime.Now.AddYears(-25); var driverClaims = new IClaim[0]; var driversAndPremiumToUpdatedPremiumForYoungDrivers = new DriversAndPremiumToUpdatedPremiumForAdultDrivers(startingAdultAge, endingAdultAge, todayProvider, increaseAmount); var driver = new DriverStub(driverName, occupation, driverDateOfBirth, driverClaims); var driversAndPremium = new DriverAndPremium(driver, expected); var actual = driversAndPremiumToUpdatedPremiumForYoungDrivers.Transform(driversAndPremium); Assert.AreEqual(expected, actual); }
#pragma warning restore CS0067 /// <summary> /// Adds a claim to the current identity /// </summary> /// <param name="userName">The user identity to add the claim to</param> /// <param name="claim">The claim</param> /// <param name="principal">The princiapl asserting the claim</param> /// <remarks>Not implemented</remarks> public void AddClaim(string userName, IClaim claim, IPrincipal principal, TimeSpan?expiry = null) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <see cref="TokenClaimsPrincipal"/> class. /// </summary> /// <param name="idToken">Token.</param> /// <param name="tokenType">Token type.</param> public TokenClaimsPrincipal(String accessToken, String idToken, String tokenType, String refreshToken) : base() { if (String.IsNullOrEmpty(idToken)) { throw new ArgumentNullException(nameof(idToken)); } else if (String.IsNullOrEmpty(tokenType)) { throw new ArgumentNullException(nameof(tokenType)); } else if (tokenType != "urn:ietf:params:oauth:token-type:jwt" && tokenType != "bearer") { throw new ArgumentOutOfRangeException(nameof(tokenType), "expected urn:ietf:params:oauth:token-type:jwt"); } // Token this.m_idToken = idToken; this.m_accessToken = accessToken; String[] tokenObjects = idToken.Split('.'); // Correct each token to be proper B64 encoding for (int i = 0; i < tokenObjects.Length; i++) { tokenObjects[i] = tokenObjects[i].PadRight(tokenObjects[i].Length + (tokenObjects[i].Length % 4), '=').Replace("===", "="); } JObject headers = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenObjects[0]))), body = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenObjects[1]))); // Attempt to get the certificate if (((String)headers["alg"]).StartsWith("RS")) { var cert = SecurityUtils.FindCertificate(X509FindType.FindByThumbprint, StoreLocation.CurrentUser, StoreName.My, headers["x5t"].ToString()); //if (cert == null) // throw new SecurityTokenException(SecurityTokenExceptionType.KeyNotFound, String.Format ("Cannot find certificate {0}", headers ["x5t"])); // TODO: Verify signature } else if (((String)headers["alg"]).StartsWith("HS")) { // TODO: Verify key } // Parse the jwt List <IClaim> claims = new List <IClaim>(); foreach (var kf in body) { String claimName = kf.Key; if (!claimMap.TryGetValue(kf.Key, out claimName)) { claims.AddRange(this.ProcessClaim(kf, kf.Key)); } else { claims.AddRange(this.ProcessClaim(kf, claimName)); } } IClaim expiryClaim = claims.Find(o => o.Type == SanteDBClaimTypes.Expiration), notBeforeClaim = claims.Find(o => o.Type == SanteDBClaimTypes.AuthenticationInstant); if (expiryClaim == null || notBeforeClaim == null) { throw new SecurityTokenException("Missing NBF or EXP claim"); } else { DateTime expiry = expiryClaim.AsDateTime().ToLocalTime(), notBefore = notBeforeClaim.AsDateTime().ToLocalTime(); if (expiry == null || expiry < DateTime.Now) { throw new SecurityTokenException("Token expired"); } else if (notBefore == null || Math.Abs(notBefore.Subtract(DateTime.Now).TotalMinutes) > 3) { throw new SecurityTokenException("Token cannot yet be used (issued in the future)"); } } this.RefreshToken = refreshToken; this.AddIdentity(new SanteDBClaimsIdentity(body["unique_name"]?.Value <String>().ToLower() ?? body["sub"]?.Value <String>().ToLower(), true, "OAUTH", claims)); }
public ClaimController(IClaim claimService) { this.claimService = claimService; }
public void MakeClaim(IClaim claim) => claims.Add(claim);
/// <summary> /// Initializes a new instance of the <see cref="SanteDB.DisconnectedClient.Security.TokenClaimsPrincipal"/> class. /// </summary> /// <param name="idToken">Token.</param> /// <param name="tokenType">Token type.</param> public TokenClaimsPrincipal(String accessToken, String idToken, String tokenType, String refreshToken, OpenIdConfigurationInfo configuration) : base() { if (String.IsNullOrEmpty(idToken)) { throw new ArgumentNullException(nameof(idToken)); } else if (String.IsNullOrEmpty(tokenType)) { throw new ArgumentNullException(nameof(tokenType)); } else if ( tokenType != "urn:santedb:session-info" && tokenType != "urn:ietf:params:oauth:token-type:jwt" && tokenType != "bearer") { throw new ArgumentOutOfRangeException(nameof(tokenType), "expected urn:ietf:params:oauth:token-type:jwt"); } // Token this.m_idToken = idToken; this.m_accessToken = accessToken; JObject tokenBody = null; if (tokenType == "urn:santedb:session-info") { tokenBody = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(idToken))); } else { String[] tokenObjects = idToken.Split('.'); // Correct each token to be proper B64 encoding for (int i = 0; i < tokenObjects.Length; i++) { tokenObjects[i] = tokenObjects[i].PadRight(tokenObjects[i].Length + (tokenObjects[i].Length % 4), '=').Replace("===", "="); } JObject headers = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenObjects[0]))); tokenBody = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(tokenObjects[1]))); // Attempt to get the certificate if (((String)headers["alg"]).StartsWith("RS")) { var cert = X509CertificateUtils.FindCertificate(X509FindType.FindByThumbprint, StoreLocation.CurrentUser, StoreName.My, headers["x5t"].ToString()); //if (cert == null) // throw new SecurityTokenException(SecurityTokenExceptionType.KeyNotFound, String.Format ("Cannot find certificate {0}", headers ["x5t"])); // TODO: Verify signature } else if (((String)headers["alg"]).StartsWith("HS")) { // TODO: Verfiy signature using our client secret } } // Parse the jwt List <IClaim> claims = new List <IClaim>(); foreach (var kf in tokenBody) { String claimName = kf.Key; if (!claimMap.TryGetValue(kf.Key, out claimName)) { claims.AddRange(this.ProcessClaim(kf, kf.Key)); } else { claims.AddRange(this.ProcessClaim(kf, claimName)); } } // Validate issuer if (configuration != null && !claims.Any(c => c.Type == "iss" && c.Value == configuration?.Issuer)) { throw new SecurityTokenException(SecurityTokenExceptionType.InvalidIssuer, "Issuer mismatch"); } // Validate validity IClaim expiryClaim = claims.Find(o => o.Type == SanteDBClaimTypes.Expiration), notBeforeClaim = claims.Find(o => o.Type == SanteDBClaimTypes.AuthenticationInstant); if (expiryClaim == null || notBeforeClaim == null) { throw new SecurityTokenException(SecurityTokenExceptionType.InvalidClaim, "Missing NBF or EXP claim"); } else { DateTime expiry = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), notBefore = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); expiry = expiryClaim.AsDateTime(); notBefore = notBeforeClaim.AsDateTime(); if (expiry == null || expiry < DateTime.Now) { throw new SecurityTokenException(SecurityTokenExceptionType.TokenExpired, "Token expired"); } else if (notBefore == null || Math.Abs(notBefore.Subtract(DateTime.Now).TotalMinutes) > 3) { throw new SecurityTokenException(SecurityTokenExceptionType.NotYetValid, $"Token cannot yet be used (issued {notBefore} but current time is {DateTime.Now})"); } } this.RefreshToken = refreshToken; this.m_identities.Clear(); this.m_identities.Add(new SanteDBClaimsIdentity(tokenBody["unique_name"]?.Value <String>() ?? tokenBody["sub"]?.Value <String>(), true, "OAUTH2", claims)); }
/// <summary> /// Remove the specified claim /// </summary> public void RemoveClaim(IClaim claim) { this.m_claims.Remove(claim); }
/// <summary> /// Add a claim to the specified user /// </summary> public void AddClaim(string userName, IClaim claim, IPrincipal principal, TimeSpan?expire = null) { if (userName == null) { throw new ArgumentNullException(nameof(userName)); } else if (claim == null) { throw new ArgumentNullException(nameof(claim)); } this.VerifyPrincipal(principal, PermissionPolicyIdentifiers.AlterIdentity); try { using (var dataContext = this.m_configuration.Provider.GetWriteConnection()) { dataContext.Open(); var user = dataContext.FirstOrDefault <DbSecurityUser>(o => o.UserName.ToLower() == userName.ToLower()); if (user == null) { throw new KeyNotFoundException(userName); } lock (this.m_syncLock) { var existingClaim = dataContext.FirstOrDefault <DbUserClaim>(o => o.ClaimType == claim.Type && o.SourceKey == user.Key); // Set the secret if (existingClaim == null) { existingClaim = new DbUserClaim() { ClaimType = claim.Type, ClaimValue = claim.Value, SourceKey = user.Key }; if (expire.HasValue) { existingClaim.ClaimExpiry = DateTime.Now.Add(expire.Value); } dataContext.Insert(existingClaim); } else { existingClaim.ClaimValue = claim.Value; if (expire.HasValue) { existingClaim.ClaimExpiry = DateTime.Now.Add(expire.Value); } dataContext.Update(existingClaim); } } } } catch (Exception e) { this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString()); throw; } }
/// <summary> /// Determines whether the specified access token is authorized to access /// the specified claim. /// </summary> /// <param name="accessToken">The access token.</param> /// <param name="claim">The claim.</param> /// <returns><c>true</c> if the access token is authorized; otherwise <c>false</c>.</returns> public static bool HasClaim(string accessToken, IClaim claim) { var credentials = Cache.Get <Credentials>(accessToken); return(credentials.Claims.Any(c => c.Type == claim.Type && c.Value == claim.Value)); }
/// <summary> /// Determines whether the specified header contains an authenticated Accesss Token, /// and whether the user has the necessary <see cref="Claim"/> (if defined). /// </summary> /// <param name="authorization">The authentication header.</param> /// <param name="claim">The required claim.</param> /// <param name="getUser">The delegate that will be called if the user associated with the access token is not cached.</param> /// <returns><c>200</c> when authenticated and authorized; <c>401</c> when unauthenticated; 403 when unauthorized.</returns> public static async Task <HttpStatusCode> IsAuthorized(AuthenticationHeaderValue authorization, IClaim claim, Func <string, Task <IClaimUser> > getUser) { var accessToken = GetAccessToken(authorization); if (!await ValidAccessToken(accessToken, getUser)) { return(HttpStatusCode.Unauthorized); } return(claim == null || HasClaim(accessToken, claim) ? HttpStatusCode.OK : HttpStatusCode.Forbidden); }
public void Setup() { now = DateTime.Now; claim = GetTestClaim(); testClaimTag = GetTestTag(); }
/// <summary> /// Indique si l'utilisateur a un droit particulier. /// </summary> /// <param name="claim">Droit.</param> /// <returns>Indique si l'utilisateur a le droit particulier ou non.</returns> public bool Claim(IClaim claim) { return(claims.ContainsKey(claim.Id)); }
/// <summary> /// Creates an instance of the claim based filter. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The value of the claim <paramref name="type"/>.</param> public ClaimAttribute(string type, string value) { Claim = new Claim { Type = type, Value = value }; }
public ClaimController(IClaim claim, UserManager <NewUser> userManager, RoleManager <IdentityRole> roleManager) { _claim = claim; _userManager = userManager; _roleManager = roleManager; }