public bool ValidateToken(string token, TokenClaims claims, SymmetricSecurityKey secretKey, out SecurityToken validatedToken) { var tokenHandler = new JwtSecurityTokenHandler(); try { var result = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidIssuer = claims.Issuer, ValidAudience = claims.Audience, IssuerSigningKey = secretKey, RequireExpirationTime = true, RequireSignedTokens = true, }, out validatedToken); return(result != null); } catch { validatedToken = null; return(false); } }
public static TokenClaims ConvertStringToTokenClaims(string token) { try { token = EncryptHelper.AES_Decrypt(token); string[] tokenarr = token.Split('|'); TokenClaims tkClaims = new TokenClaims(); tkClaims.UserKey = tokenarr[0]; tkClaims.Role = int.Parse(tokenarr[2]); try { tkClaims.LastTime = DateTime.Parse(tokenarr[1]); } catch { tkClaims.LastTime = new DateTime(2500, 1, 1); } return(tkClaims); } catch (Exception ex) { throw new Exception("token格式不正确" + ex.ToString()); } }
public async Task <IActionResult> Authentication(UserLogin login) { //if it is a valid user var validation = await IsValidUser(login); if (validation.Item1) { var token = GenerateToken(validation.Item2); var userId = validation.Item2.Id; var role = validation.Item2.Role; var tokenClaims = new TokenClaims { Token = token, Role = role, UserId = userId }; var response = new ApiResponse <TokenClaims>(tokenClaims); return(Ok(response)); } return(NotFound()); }
public TokenClaims GetTokenClaims(HttpContext httpContext) { var currentUser = httpContext.User; var claims = new TokenClaims() { UserId = currentUser.HasClaim(c => c.Type == "userId") ? currentUser.Claims.FirstOrDefault(c => c.Type == "userId").Value : null, Email = currentUser.HasClaim(c => c.Type == "email") ? currentUser.Claims.FirstOrDefault(c => c.Type == "email").Value : null }; return(claims); }
public void UserRight_ParsedCorrectlly(IEnumerable <Claim> claims, UserRight?userRight) { // Arrange var tokenClaims = new TokenClaims(claims); // Act var parseUserRight = tokenClaims.UserRight; // Assert Assert.AreEqual(userRight, parseUserRight); }
public void LicenceStatus_ParsedCorrectlly(IEnumerable <Claim> claims, LicenceStatus?licenceStatus) { // Arrange var tokenClaims = new TokenClaims(claims); // Act var parseLicenceStatus = tokenClaims.LicenceStatus; // Assert Assert.AreEqual(licenceStatus, parseLicenceStatus); }
private BearerToken GenerateBearerToken(User user, Membership membership) { string tokenId = Guid.NewGuid().ToString(); var tokenClaims = new TokenClaims(tokenId, user, membership); var hashAlgorithm = membership.GetHashAlgorithm(); var encoding = membership.GetEncoding(); var accessToken = this.jwtService.GenerateToken(tokenClaims, hashAlgorithm, encoding); var refreshExpiresIn = TimeSpan.FromSeconds(membership.RefreshTokenExpiresIn); var refreshToken = this.jwtService.GenerateToken(tokenClaims.AddClaim(REFRESH_TOKEN_CLAIM, true), hashAlgorithm, encoding); return(new BearerToken(accessToken, tokenClaims.ExpiresIn, refreshToken, refreshExpiresIn)); }
public TokenClaimsAccessor MockTokenClaimsAccessor(TokenClaims tokenClaims) { var mockHttpAccessor = new Mock <IHttpContextAccessor>(); var httpContext = new DefaultHttpContext { User = tokenClaims.ToClaimsPrincipal() }; mockHttpAccessor.Setup(x => x.HttpContext).Returns(httpContext); return(new TokenClaimsAccessor(mockHttpAccessor.Object)); }
public AccountController(IOptions <TokenClaims> jwtClaims, ICustomerRepository repository) { _repository = repository; _tokenOptions = jwtClaims.Value; ThrowIfInvalidOptions(_tokenOptions); //Converte o nome dos objetos no padrão do JSON //Falha no NewtonSoft.Json, talvez já tenham corrigido. _serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; }
private async Task <BearerToken> GenerateBearerTokenAsync(User user, Membership membership, string ipAddress = null, string userAgent = null) { string tokenId = Guid.NewGuid().ToString(); var tokenClaims = new TokenClaims(tokenId, user, membership); var hashAlgorithm = membership.GetHashAlgorithm(); var encoding = membership.GetEncoding(); var accessToken = this.jwtService.GenerateToken(tokenClaims, hashAlgorithm, encoding); var refreshExpiresIn = TimeSpan.FromSeconds(membership.RefreshTokenExpiresIn); var refreshToken = this.jwtService.GenerateToken(tokenClaims.AddClaim(REFRESH_TOKEN_CLAIM, true), hashAlgorithm, encoding); var bearerToken = new BearerToken(accessToken, tokenClaims.ExpiresIn, refreshToken, refreshExpiresIn); // Save to active tokens collection await this.StoreActiveTokenAsync(bearerToken, user, membership.Id, ipAddress, userAgent); return(bearerToken); }
public async Task <ResetPasswordToken> ResetPasswordAsync(Utilizer utilizer, string membershipId, string usernameOrEmailAddress) { if (string.IsNullOrEmpty(usernameOrEmailAddress)) { throw ErtisAuthException.ValidationError(new [] { "Username or email required!" }); } var membership = await this.membershipService.GetAsync(membershipId); if (membership == null) { throw ErtisAuthException.MembershipNotFound(membershipId); } var user = await this.GetUserWithPasswordAsync(usernameOrEmailAddress, usernameOrEmailAddress, membershipId); if (user == null) { throw ErtisAuthException.UserNotFound(usernameOrEmailAddress, "username or email_address"); } if (utilizer.Role == Rbac.ReservedRoles.Administrator || utilizer.Id == user.Id) { var tokenClaims = new TokenClaims(Guid.NewGuid().ToString(), user, membership); tokenClaims.AddClaim("token_type", "reset_token"); var resetToken = this.jwtService.GenerateToken(tokenClaims, HashAlgorithms.SHA2_256, Encoding.UTF8); var resetPasswordToken = new ResetPasswordToken(resetToken, TimeSpan.FromHours(1)); await this.eventService.FireEventAsync(this, new ErtisAuthEvent { EventType = ErtisAuthEventType.UserPasswordReset, UtilizerId = user.Id, Document = resetPasswordToken, MembershipId = membershipId }); return(resetPasswordToken); } else { throw ErtisAuthException.AccessDenied("Unauthorized access"); } }
public static async Task <TokenClaimsAccessor> MockTokenClaimsAccessor(IdentityDbContext context, string username = "******", string password = "******", Predicate <Scope>?scopeChooser = null) { var(scope, userId) = await GetAuthenticationInfo(context, username, password, scopeChooser); var tokenClaims = new TokenClaims(scope.System, scope.Social, userId, scope.DomainId, scope.ProjectId, scope.UserProjectAssignmentId, (UserRole)scope.Role); var mockHttpAccessor = new Mock <IHttpContextAccessor>(); var httpContext = new DefaultHttpContext { User = tokenClaims.ToClaimsPrincipal() }; mockHttpAccessor.Setup(x => x.HttpContext).Returns(httpContext); return(new TokenClaimsAccessor(mockHttpAccessor.Object)); }
public string GenerateToken(TokenClaims tokenClaims, DateTime tokenGenerationTime, HashAlgorithms hashAlgorithm, Encoding encoding) { return(this.GenerateToken( hashAlgorithm, encoding, tokenGenerationTime, tokenClaims.SecretKey, tokenClaims.Issuer, tokenClaims.Audience, tokenClaims.ExpiresIn, tokenClaims.Subject, tokenClaims.TokenId, tokenClaims.Principal, tokenClaims.FirstName, tokenClaims.LastName, tokenClaims.EmailAddress, tokenClaims.AdditionalClaims)); }
public async Task Claims_ParsedSucessfullyAsync() { // Arrange var auth = new ClientCredentialsAuthentication(Configuration.ClientCredentials.ClientId, Configuration.ClientCredentials.ClientSecret); var config = new DokladConfiguration(Configuration.Urls.ApiUrl, Configuration.Urls.IdentityServerTokenUrl); auth.Configuration = config; // Act var token = await auth.GetTokenAsync(); // Assert Assert.IsNotNull(token); Assert.That(token.Claims, Is.Not.Null.And.Not.Empty); var tokenClaims = new TokenClaims(token.Claims); Assert.That(tokenClaims.LicenceStatus, Is.Not.Null); Assert.That(tokenClaims.UserRight, Is.Not.Null); }
private string StimulateRefreshToken(string accessToken, User user, Membership membership) { if (this.jwtService.TryDecodeToken(accessToken, out var securityToken)) { if (this.TryExtractClaimValue(securityToken, JwtRegisteredClaimNames.Jti, out var tokenId)) { var tokenClaims = new TokenClaims(tokenId, user, membership); var hashAlgorithm = membership.GetHashAlgorithm(); var encoding = membership.GetEncoding(); var refreshToken = this.jwtService.GenerateToken(tokenClaims.AddClaim(REFRESH_TOKEN_CLAIM, true), securityToken.IssuedAt, hashAlgorithm, encoding); if (!string.IsNullOrEmpty(refreshToken)) { return(refreshToken); } } } return(null); }
private string?Authenticate(User user, Scope scope) { if (scope.System) { if (!user.System) { return(null); } } // In gRPC there is no null value, the empty string means nothing else if (string.IsNullOrEmpty(scope.ProjectId)) { // disallow social domain login var domainIdGuid = Guid.Parse(scope.DomainId); if (domainIdGuid == Constants.SocialDomainId) { return(null); } // it's a domain scope, find whether the user has it var domain = user.Domains.FirstOrDefault(x => x.Domain.Id == domainIdGuid && (int)x.Role == (int)scope.Role); if (domain == null) { return(null); } } else { var project = user.Projects.FirstOrDefault(x => x.Project.Id == Guid.Parse(scope.ProjectId) && (int)x.Role == (int)scope.Role); if (project == null) { return(null); } } // auth successful. generate token according to token claims var claims = new TokenClaims(scope.System, scope.Social, user.Id.ToString(), scope.DomainId, scope.ProjectId, scope.UserProjectAssignmentId, (UserRole)scope.Role); return(jwtSettings.GenerateToken(claims)); }
public SessionUser GetUserDataByToken() { string token = Request.Headers["token"]; try { TokenClaims claim = TokenBuilder.DecodeToken(token); if (claim == null || TokenBuilder.IsOverTime(claim)) { return(null); } else { SessionUser data = _accSer.GetUserData(claim.TokenPayload.UsrId, claim.TokenPayload.SysId); return(data); } } catch (Exception ex) { return(null); } }
public async Task TestChangeProjectUserResourcesOnSocialProject() { var socialDomain = db.Domains.Find(Constants.SocialDomainId); var lqsocialproject = new Project(Guid.NewGuid(), lq, socialDomain, Domain.ValueObjects.Resources.QuotaForSocialProject); var lqlqsocialproject = new UserProjectAssignment(Guid.NewGuid(), lq, lqsocialproject, Domain.ValueObjects.Resources.QuotaForSocialProject); var lqlqsocialprojectTokenClaims = new TokenClaims(false, true, lq.Id, Constants.SocialDomainId, lqsocialproject.Id, lqlqsocialproject.Id, UserRole.Admin); // set this token as a social project token. var initial = new Domain.ValueObjects.Resources(3, 4, 5); lqlqsocialproject.Resources = initial.Clone(); db.UseCycleEntries.Add(new UseCycleEntry(lqlqsocialproject.UseCycleSubject)); db.UseCycleEntries.Add(new UseCycleEntry(lqsocialproject.UseCycleSubject)); db.BillingCycleEntries.Add(new BillingCycleEntry(lqlqsocialproject.BillingCycleSubject)); db.BillingCycleEntries.Add(new BillingCycleEntry(lqsocialproject.BillingCycleSubject)); await db.SaveChangesAsync(); var service = CreateService(lqlqsocialprojectTokenClaims); // change delta var delta = new Domain.ValueObjects.Resources(-3, -4, -5); await service.ChangeProjectUserResources(new Protos.Interop.ChangeProjectUserResourcesRequest { ResourcesDelta = delta.ToGrpc() }, TestContext); // 1 allocated billing with 0 amount to be allocated to user. var billing = Assert.Single(lqlqsocialproject.BillingCycleRecords); Assert.Equal(0, billing.Amount); // No resources is now being used Assert.Equal(Domain.ValueObjects.Resources.Zero, lqsocialproject.Resources); // lq should pay the resources price // the previous 0 allocated billing should also be included AssertIEnumerableIgnoreOrder(new[] { PricePlan.Instance.Calculate(initial), 0 }, lq.PayedUserTransactions.Select(x => x.Amount)); }
/// <summary> /// Access token. /// </summary> /// <returns>Tokenizer.</returns> public Tokenizer GetToken() { if (_authentication.UseRefreshToken) { _token = _authentication.RefreshAccessToken(); _authentication.UseRefreshToken = false; } if (_token is null) { _token = _authentication.GetToken(); } if (_token.ShouldBeRefreshedNow(RefreshTokenLimit)) { _token = _authentication.RefreshAccessToken(); } TokenClaims = new TokenClaims(_token.Claims); return(_token); }
private static void ThrowIfInvalidOptions(TokenClaims options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.ValidFor <= TimeSpan.Zero) { throw new ArgumentException("O período deve ser maior que zero", nameof(TokenClaims.ValidFor)); } if (options.SigningCredentials == null) { throw new ArgumentNullException(nameof(TokenClaims.SigningCredentials)); } if (options.JtiGenerator == null) { throw new ArgumentNullException(nameof(TokenClaims.JtiGenerator)); } }
public static TokenClaims SetTokenCache(string key, string tokenStr) { lock (lockobj) { TokenClaims claim = TokenBuilder.DecodeToken(tokenStr); if (DicCache.ContainsKey(key)) { DicCache.Remove(key); DicCache.Add(key, new TokenCacheModel() { TokenClaim = claim, TokenStr = tokenStr }); } else { DicCache.Add(key, new TokenCacheModel() { TokenClaim = claim, TokenStr = tokenStr }); } return(claim); } }
public void InitializeVariables(Domain.Entities.System system) { nju = new DomainEntity(Guid.NewGuid(), njuadmin, new Domain.ValueObjects.Resources(10, 20, 30), system); pku = new DomainEntity(Guid.NewGuid(), fc, new Domain.ValueObjects.Resources(20, 30, 40), system); cjd.JoinDomain(nju); cjd.JoinDomain(pku); lq.JoinDomain(nju); njuadmin.JoinDomain(nju); fc.JoinDomain(pku); lqproject = new Project(Guid.NewGuid(), lq, nju, new Domain.ValueObjects.Resources(5, 10, 20)); fcproject = new Project(Guid.NewGuid(), fc, pku, new Domain.ValueObjects.Resources(10, 30, 40)); lq67project = new UserProjectAssignment(Guid.NewGuid(), lq, lqproject, new Domain.ValueObjects.Resources(4, 8, 10)); cjd67project = new UserProjectAssignment(Guid.NewGuid(), cjd, lqproject, new Domain.ValueObjects.Resources(1, 2, 10)); fcfcproject = new UserProjectAssignment(Guid.NewGuid(), fc, fcproject, new Domain.ValueObjects.Resources(5, 15, 20)); cjdlqTokenClaims = new TokenClaims(false, false, cjd.Id, nju.Id, lqproject.Id, cjd67project.Id, UserRole.Member); lqlqTokenClaims = new TokenClaims(false, false, lq.Id, nju.Id, lqproject.Id, lq67project.Id, UserRole.Admin); njuadminnjuTokenClaims = new TokenClaims(false, false, njuadmin.Id, nju.Id, null, null, UserRole.Admin); fcfcTokenClaims = new TokenClaims(false, false, fc.Id, pku.Id, fcproject.Id, fcfcproject.Id, UserRole.Admin); systemTokenClaims = new TokenClaims(true, false, SystemUserId, nju.Id, null, null, UserRole.Admin); }
/// <summary> /// Returns existing Tokenizer and if necessary, refreshes it. /// </summary> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>up-to-date Tokenizer.</returns> public async Task <Tokenizer> GetTokenAsync(CancellationToken cancellationToken = default) { if (_authentication.UseRefreshToken) { _token = await _authentication.RefreshAccessTokenAsync(cancellationToken).ConfigureAwait(false); _authentication.UseRefreshToken = false; } if (_token is null) { _token = await _authentication.GetTokenAsync(cancellationToken).ConfigureAwait(false); } if (_token.ShouldBeRefreshedNow(RefreshTokenLimit)) { _token = await _authentication.RefreshAccessTokenAsync(cancellationToken).ConfigureAwait(false); } TokenClaims = new TokenClaims(_token.Claims); return(_token); }
public TokenService(IOptions <TokenClaims> tokenOptionsSnapshot, SigningConfigurations signingConfigurations, IPasswordHasher passwordHasher) { this.signingConfigurations = signingConfigurations; this.tokenClaims = tokenOptionsSnapshot.Value; this.passwordHasher = passwordHasher; }
public async Task <BearerTokenValidationResult> VerifyBearerTokenAsync(string token, bool fireEvent = true) { var revokedToken = await this.revokedTokensRepository.FindOneAsync(x => x.Token == token); if (revokedToken != null) { throw ErtisAuthException.TokenWasRevoked(); } if (this.jwtService.TryDecodeToken(token, out var securityToken)) { var expireTime = securityToken.ValidTo.ToLocalTime(); if (DateTime.Now <= expireTime) { var user = await this.GetTokenOwnerAsync(securityToken); if (user != null) { if (this.TryExtractClaimValue(securityToken, JwtRegisteredClaimNames.Prn, out var membershipId) && !string.IsNullOrEmpty(membershipId)) { var membership = await this.membershipService.GetAsync(membershipId); if (membership != null) { var encoding = membership.GetEncoding(); var secretSecurityKey = new SymmetricSecurityKey(encoding.GetBytes(membership.SecretKey)); var tokenClaims = new TokenClaims(null, user, membership); if (!this.jwtService.ValidateToken(token, tokenClaims, secretSecurityKey, out _)) { // Token signature not verified! throw ErtisAuthException.InvalidToken("Token signature could not verified!"); } } else { // Membership not found! throw ErtisAuthException.MembershipNotFound(membershipId); } } else { // MembershipId could not found in token claims! throw ErtisAuthException.InvalidToken(); } if (fireEvent) { await this.eventService.FireEventAsync(this, new ErtisAuthEvent(ErtisAuthEventType.TokenVerified, user, new { token })); } return(new BearerTokenValidationResult(true, token, user, expireTime - DateTime.Now, this.IsRefreshToken(securityToken))); } else { // User not found! var userId = securityToken.Subject; throw ErtisAuthException.UserNotFound(userId, "_id"); } } else { // Token was expired! throw ErtisAuthException.TokenWasExpired(); } } else { // Token could not decoded! throw ErtisAuthException.InvalidToken(); } }