public IssuedToken IssueOneUseToken(string consumerKey) { IssuedToken tokenData = IssueToken(consumerKey); tokenData.AllowableUses = AllowableTokenUses.Unlimited; return(tokenData); }
public IActionResult Add([FromBody] CreditCardInfo cardInfo) { try { if (cardInfo.CardNumber > 9999999999999999) { return(BadRequest("Card number should have maximum of 16 characters")); } if (cardInfo.CVV > 99999) { return(BadRequest("CVV should have maximum of 5 characters")); } IssuedToken issuedToken = new IssuedToken() { RegistrationDate = DateTime.UtcNow }; issuedToken.Token = string.Format("{0}{1:yyyy}{1:MM}{1:dd}{1:HH}{1:mm}", cardInfo.CardNumber, issuedToken.RegistrationDate); issuedToken.Token = Transformations.Rotate(Transformations.AbsoluteDifference(issuedToken.Token, 5), cardInfo.CVV); _dbContext.IssuedTokens.Add(issuedToken); _dbContext.SaveChanges(); return(new JsonResult(new { registration_date = issuedToken.RegistrationDate, token = issuedToken.Token })); } catch (Exception ex) { /* log ex message */ return(BadRequest("Error processing credit card.")); } }
/// <summary> /// Creates a custom SOAP request filter /// </summary> /// <param name="parentAssertion">Custom security assertion</param> public CustomSecurityClientOutputFilterHok(CustomSecurityAssertionHok parentAssertion) : base(parentAssertion.ServiceActor, true) { issuedToken = new IssuedToken(parentAssertion.BinaryToken, parentAssertion.TokenType); samlAssertionId = parentAssertion.BinaryToken.Attributes.GetNamedItem("ID").Value; messageSignature = new MessageSignature(parentAssertion.SecurityToken); }
public async Task Get_Token_By_Refresh_Token_Mongo_Test() { // Arrange DatabaseOptions databaseOptions = _context.MongoDatabaseOptions; IOptionsMonitor <DatabaseOptions> databaseOptionsMock = Mock.Of <IOptionsMonitor <DatabaseOptions> >(_ => _.CurrentValue == databaseOptions); #pragma warning disable CA2000 // Dispose objects before losing scope IssuedTokenMongoRepository issuedTokenRepository = new IssuedTokenMongoRepository(new MongoConnection(databaseOptionsMock.CurrentValue)); #pragma warning restore CA2000 // Dispose objects before losing scope // Act IssuedToken issuedToken = new IssuedToken { Id = DataUtil.GenerateUniqueId(), ExpiredJwtToken = DateTime.UtcNow.AddDays(30), ExpiredRefreshToken = DateTime.UtcNow.AddDays(30), JwtToken = "abcy2", RefreshToken = "xyzy1", UserId = "5c06a15e4cc9a850bca44488", UserSessionId = DataUtil.GenerateUniqueId() }; await issuedTokenRepository.AddAsync(issuedToken); string token = await issuedTokenRepository.GetTokenByRefreshToken("xyzy1"); issuedTokenRepository.Dispose(); // Assert Assert.True(token == "abcy2"); }
public void IssuedTokenWaitStop( VssTraceActivity activity, IssuedTokenProvider provider, IssuedToken token) { if (IsEnabled(EventLevel.Verbose, Keywords.Authentication)) { SetActivityId(activity); IssuedTokenWaitStop(provider.CredentialType, provider.GetHashCode(), token != null ? token.GetHashCode() : 0); } }
public void IssuedTokenValidated( VssTraceActivity activity, IssuedTokenProvider provider, IssuedToken token) { if (IsEnabled()) { SetActivityId(activity); IssuedTokenValidated(provider.CredentialType, provider.GetHashCode(), token.GetHashCode()); } }
public void IssuedTokenRetrievedFromCache( VssTraceActivity activity, IssuedTokenProvider provider, IssuedToken token) { if (IsEnabled()) { SetActivityId(activity); IssuedTokenRetrievedFromCache(provider.CredentialType, provider.GetHashCode(), token.GetHashCode()); } }
private void RefreshLeaseAndStoreToken(Uri serverUrl, IssuedToken token) { if (token.Properties == null) { token.Properties = new Dictionary <string, string>(); } token.Properties[__tokenExpirationKey] = JsonConvert.SerializeObject(this.GetNewExpirationDateTime()); base.StoreToken(serverUrl, token); }
/// <summary> /// Removes the token. /// </summary> /// <param name="serverUrl">The server URL.</param> /// <param name="token">The token.</param> /// <param name="force">if set to <c>true</c> force the removal of the token.</param> public void RemoveToken(Uri serverUrl, IssuedToken token, bool force) { ////////////////////////////////////////////////////////// // Bypassing this allows the token to be stored in local // cache. Token is removed if lease is expired. if (force || token != null && this.IsTokenExpired(token)) { base.RemoveToken(serverUrl, token); } ////////////////////////////////////////////////////////// }
internal static IssuedTokenWrapper GetInstance() { IssuedToken real = default(IssuedToken); RealInstanceFactory(ref real); var instance = (IssuedTokenWrapper)IssuedTokenWrapper.GetWrapper(real); InstanceFactory(ref instance); if (instance == null) { Assert.Inconclusive("Could not Create Test Instance"); } return(instance); }
public virtual IssuedToken IssueToken(string consumerKey) { string token = Guid.NewGuid().ToString(); var tokenData = new IssuedToken { Token = token, TokenSecret = Guid.NewGuid().ToString(), ConsumerKey = consumerKey }; _tokens[token] = tokenData; return(tokenData); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { String username = parentAssertion.username; String password = parentAssertion.password; XmlElement binaryToken = parentAssertion.binaryToken; if (binaryToken == null) { userToken = new UsernameToken(username.Trim(), password.Trim(), PasswordOption.SendPlainText); } else { issuedToken = new IssuedToken(binaryToken); } }
public virtual IssuedToken GetToken(string token) { IssuedToken tokenData = _tokens[token]; if (!IsUsable(tokenData)) { throw Error.TokenCanNoLongerBeUsed(token); } if (tokenData.AllowableUses != AllowableTokenUses.Unlimited) { _tokens.Remove(token); } return(tokenData); }
public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { if (parentAssertion.BinaryToken == null) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); parentAssertion.SecurityToken = signatureToken; } else { issuedToken = new IssuedToken(parentAssertion.BinaryToken); signatureToken = parentAssertion.SecurityToken; samlAssertionId = parentAssertion.BinaryToken.Attributes.GetNamedItem("ID").Value; } sig = new MessageSignature(signatureToken); }
private bool IsTokenExpired(IssuedToken token) { bool expireToken = true; if (token != null && token.Properties.ContainsKey(__tokenExpirationKey)) { string expirationDateTimeJson = token.Properties[__tokenExpirationKey]; try { DateTime expiration = JsonConvert.DeserializeObject <DateTime>(expirationDateTimeJson); expireToken = DateTime.Compare(DateTime.Now, expiration) >= 0; } catch { } } return(expireToken); }
public async Task <TokenModel> RefreshTokenAsync(string refreshToken) { var issuedToken = await _issuedTokenRepository.GetByRefreshToken(refreshToken); var canDeactive = await _issuedTokenRepository.DeactiveRefreshToken(refreshToken); if (canDeactive) { var claimPrincipal = GetPrincipalFromExpiredToken(issuedToken.JwtToken); var newToken = SignedToken(claimPrincipal.Claims); // Create refresh token var expToken = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.TokenExpiration); var expRefreshToken = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.RefreshTokenExpiration); var newIssuedToken = new IssuedToken { Id = DataUtil.GenerateUniqueId(), UserId = issuedToken.Id, JwtToken = newToken, ExpiredJwtToken = expToken, ExpiredRefreshToken = expRefreshToken, RefreshToken = CryptoUtil.ToSHA256(Guid.NewGuid().ToString()), UserSessionId = issuedToken.UserSessionId, Deactive = false }; await _issuedTokenRepository.AddAsync(newIssuedToken); return(new TokenModel { Token = newToken, Exp = ((DateTimeOffset)expToken).ToUnixTimeSeconds(), ExpRefresh = ((DateTimeOffset)expRefreshToken).ToUnixTimeSeconds(), RefreshToken = newIssuedToken.RefreshToken, UserSessionId = newIssuedToken.UserSessionId }); } throw new IdentityException(ErrorCodes.CannotDeactiveRefreshToken); }
private bool IsTokenExpired(IssuedToken token) { bool tokenIsExpired = true; if (token != null && token.Properties.ContainsKey(__tokenExpirationKey)) { string expirationDateTimeJson = token.Properties[__tokenExpirationKey]; try { DateTime expiration = JsonConvert.DeserializeObject <DateTime>(expirationDateTimeJson); tokenIsExpired = DateTime.Compare(DateTime.Now, expiration) >= 0; } catch (JsonException) { // token is malfromed, ignore the exception and simply return that it is expired } } return(tokenIsExpired); }
public IActionResult ValidateToken([FromBody] TokenValidationInfo tokenInfo) { bool validated = true; try { if (string.IsNullOrWhiteSpace(tokenInfo.Token)) { return(BadRequest("Token is empty.")); } if (tokenInfo.CVV > 99999) { return(BadRequest("CVV should have maximum of 5 characters")); } if (DateTime.UtcNow.Subtract(tokenInfo.RegistrationDate).TotalMinutes > 15) { return(new JsonResult(new { validated = false })); } IssuedToken issuedToken = _dbContext.IssuedTokens.Where(w => w.RegistrationDate == tokenInfo.RegistrationDate && w.Token == tokenInfo.Token).FirstOrDefault(); if (issuedToken == null) { return(new JsonResult(new { validated = false })); } long cardNumber = issuedToken.CardNumber; return(new JsonResult(new { validated = true })); } catch (Exception ex) { /* log ex message */ return(BadRequest("Error validating token.")); } }
static partial void RealInstanceFactory(ref IssuedToken real, [CallerMemberName] string callerName = "");
/// <summary> /// Stores the token. /// </summary> /// <param name="serverUrl">The server URL.</param> /// <param name="token">The token.</param> public override void StoreToken(Uri serverUrl, IssuedToken token) { this.RefreshLeaseAndStoreToken(serverUrl, token); }
public void AddToIssuedTokens(IssuedToken issuedToken) { base.AddObject("IssuedTokens", issuedToken); }
/// <summary> /// Creates CustomSecurityClientOutputFilterBearer object /// </summary> /// <param name="parentAssertion">Parent assertion</param> public CustomSecurityClientOutputFilterBearer(CustomSecurityAssertionBearer parentAssertion) : base(parentAssertion.ServiceActor, true) { issuedToken = new IssuedToken(parentAssertion.BinaryToken); }
public async Task <TokenModel> SignInAsync(LoginModel loginModel) { _serviceLogger.Info("User Login {$loginModel}", loginModel.ToJson()); var user = await _userManager.FindByNameAsync(loginModel.Username); if (user != null) { var validationResult = await _signInManager.PasswordSignInAsync(user, loginModel.Password, false, true); if (validationResult.Succeeded) { var userClaims = await _userManager.GetClaimsAsync(user); var token = SignedToken(userClaims); // Create UserSession var userSession = new UserSession { Id = DataUtil.GenerateUniqueId(), RequestIpAddress = loginModel.ClientIp, SoftwareAgent = loginModel.SoftwareAgent, InstalledVersion = loginModel.VersionInstalled, SignInDate = DateTime.UtcNow, UserId = user.Id, Username = user.Username, UserActivities = new List <UserActivity> { new UserActivity { Id = DataUtil.GenerateUniqueId(), ActivityName = "USER_SIGNIN", Content = "Signin successfully", ActivityDate = DateTime.UtcNow, ActivityType = ActivityType.Info } } }; await _userSessionRepository.AddAsync(userSession); // Create refresh token var expToken = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.TokenExpiration); var expRefreshToken = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.RefreshTokenExpiration); var issuedToken = new IssuedToken { Id = DataUtil.GenerateUniqueId(), UserId = user.Id, JwtToken = token, ExpiredJwtToken = expToken, ExpiredRefreshToken = expRefreshToken, RefreshToken = CryptoUtil.ToSHA256(Guid.NewGuid().ToString()), UserSessionId = userSession.Id, Deactive = false }; await _issuedTokenRepository.AddAsync(issuedToken); _serviceLogger.Info("User Login Successfully {$issuedToken}", issuedToken.ToJson()); return(new TokenModel { Token = token, Exp = ((DateTimeOffset)expToken).ToUnixTimeSeconds(), ExpRefresh = ((DateTimeOffset)expRefreshToken).ToUnixTimeSeconds(), RefreshToken = issuedToken.RefreshToken, UserSessionId = userSession.Id }); } } throw new IdentityException(ErrorCodes.CannotSignIn); }
/// <summary> /// Issues a token request to the configured secure token service. On success, the access token issued by the /// token service is returned to the caller /// </summary> /// <param name="failedToken">If applicable, the previous token which is now considered invalid</param> /// <param name="cancellationToken">A token used for signalling cancellation</param> /// <returns>A <c>Task&lgt;IssuedToken></c> for tracking the progress of the token request</returns> protected override async Task <IssuedToken> OnGetTokenAsync( IssuedToken failedToken, CancellationToken cancellationToken) { if (this.SignInUrl == null || this.Grant == null || this.ClientCredential == null) { return(null); } IssuedToken issuedToken = null; var traceActivity = VssTraceActivity.Current; try { var tokenHttpClient = new VssOAuthTokenHttpClient(this.SignInUrl); var tokenResponse = await tokenHttpClient.GetTokenAsync(this.Grant, this.ClientCredential, this.TokenParameters, cancellationToken).ConfigureAwait(false); if (!String.IsNullOrEmpty(tokenResponse.AccessToken)) { // Construct a new access token based on the response, including the expiration time so we know // when to refresh the token. issuedToken = CreateIssuedToken(tokenResponse); if (!String.IsNullOrEmpty(tokenResponse.RefreshToken)) { // TODO: How should this flow be handled? Refresh Token is a credential change which is not // the same thing as access token storage } } else if (!String.IsNullOrEmpty(tokenResponse.Error)) { // Raise a new exception describing the underlying authentication error throw new VssOAuthTokenRequestException(tokenResponse.ErrorDescription) { Error = tokenResponse.Error, }; } else { // If the error property isn't set, but we didn't get an access token, then it's not // clear what the issue is. In this case just trace the response and fall through with // a null access token return value. var sb = new StringBuilder(); var serializer = JsonSerializer.Create(s_traceSettings.Value); using (var sr = new StringWriter(sb)) { serializer.Serialize(sr, tokenResponse); } VssHttpEventSource.Log.AuthenticationError(traceActivity, this, sb.ToString()); } } catch (VssServiceResponseException ex) { VssHttpEventSource.Log.AuthenticationError(traceActivity, this, ex); } return(issuedToken); }
protected override IAsyncResult OnBeginGetToken(IssuedToken failedToken, TimeSpan timeout, AsyncCallback callback, object state) { return(default(IAsyncResult)); }
protected override IssuedToken OnGetToken(IssuedToken failedToken, TimeSpan timeout) { return(default(IssuedToken)); }
/// <summary> /// Removes the token. /// </summary> /// <param name="serverUrl">The server URL.</param> /// <param name="token">The token.</param> public override void RemoveToken(Uri serverUrl, IssuedToken token) { this.RemoveToken(serverUrl, token, false); }
static partial void RealInstanceFactory(ref IssuedToken real, string callerName) { real = new BasicAuthToken(null); }
public virtual bool IsUsable(IssuedToken token) { return((!token.Expires.HasValue || (token.Expires.Value >= DateTime.Now)) && (token.AllowableUses != AllowableTokenUses.None)); }