public async Task ValidateToken_ProcessAsync(int seqid, TProtocol iprot, TProtocol oprot, CancellationToken cancellationToken) { var args = new ValidateTokenArgs(); await args.ReadAsync(iprot, cancellationToken); await iprot.ReadMessageEndAsync(cancellationToken); var result = new ValidateTokenResult(); try { result.Success = await _iAsync.ValidateTokenAsync(args.AuthToken, cancellationToken); await oprot.WriteMessageBeginAsync(new TMessage("ValidateToken", TMessageType.Reply, seqid), cancellationToken); await result.WriteAsync(oprot, cancellationToken); } catch (TTransportException) { throw; } catch (Exception ex) { Console.Error.WriteLine("Error occurred in processor:"); Console.Error.WriteLine(ex.ToString()); var x = new TApplicationException(TApplicationException.ExceptionType.InternalError, " Internal error."); await oprot.WriteMessageBeginAsync(new TMessage("ValidateToken", TMessageType.Exception, seqid), cancellationToken); await x.WriteAsync(oprot, cancellationToken); } await oprot.WriteMessageEndAsync(cancellationToken); await oprot.Transport.FlushAsync(cancellationToken); }
/// <summary> /// Logs in to account if <paramref name="code"/> is valid. /// </summary> /// <param name="code"></param> /// <param name="isPersistent"></param> /// <returns> /// <see cref="TwoFactorLogInActionResult.InvalidCredentials"/> if two factor credentials are invalid. /// <see cref="TwoFactorLogInActionResult.InvalidCode"/> if code is invalid. /// <see cref="TwoFactorLogInActionResult.Success"/> if log in is successful. /// </returns> public virtual async Task <TwoFactorLogInActionResult> TwoFactorLogInActionAsync(string code, bool isPersistent) { if (string.IsNullOrEmpty(code)) { throw new ArgumentException(nameof(code)); } TAccount account = await GetTwoFactorAccountAsync(); if (account == null) { return(TwoFactorLogInActionResult.InvalidCredentials); } ValidateTokenResult validateTokenResult = ValidateToken(TokenServiceOptions.TotpTokenService, _options.TwoFactorTokenPurpose, account, code); if (validateTokenResult == ValidateTokenResult.Valid) { await TwoFactorLogOffAsync(); await ApplicationLogInAsync(account, new AuthenticationProperties() { IsPersistent = isPersistent }); return(TwoFactorLogInActionResult.Success); } return(TwoFactorLogInActionResult.InvalidCode); }
public void ValidateToken_ReturnsValidateTokenResultExpiredIfTokenIsExpiredTest() { // Arrange Mock <IOptions <TokenServiceOptions> > mockOptions = new Mock <IOptions <TokenServiceOptions> >(); TokenServiceOptions dataProtectionServiceOptions = new TokenServiceOptions(); mockOptions.Setup(o => o.Value).Returns(dataProtectionServiceOptions); Mock <ITimeService> mockTimeService = new Mock <ITimeService>(); mockTimeService.SetupSequence(t => t.UtcNow). Returns(DateTimeOffset.MinValue). Returns(DateTimeOffset.UtcNow); DataProtectionTokenService <StubAccount> dataProtectionTokenService = new DataProtectionTokenService <StubAccount>(_dataProtectionProvider, mockOptions.Object, mockTimeService.Object); string token = dataProtectionTokenService.GenerateToken(_testInvalidPurpose, _testAccount); // Act ValidateTokenResult result = dataProtectionTokenService.ValidateToken(_testValidPurpose, token, _testAccount); // Assert Assert.Equal(ValidateTokenResult.Expired, result); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { string token; token = httpContext.Request.Headers["Access"]; token = token ?? httpContext.Request["Access"]; token = token ?? httpContext.Request.Cookies["Access"]?.Value; if (token == null) { return(false); } else { //解析token ValidateTokenResult obj = JwtUtils.DecodingToken(token); if (obj.ResultCode == ResultCode.Ok) //验证通过 { //延长token时间 Cache.SetCache(token, obj.Payload, obj.Payload.Exp); return(true); } else //拦截请求 { return(false); } } }
public void ValidateToken_ReturnsFalseIfTokenIsInvalidTest() { // Arrange TotpTokenService <StubAccount> totpTokenService = new TotpTokenService <StubAccount>(); string token = totpTokenService.GenerateToken(_invalidPurpose, _testAccount); // Act ValidateTokenResult result = totpTokenService.ValidateToken(_validPurpose, token, _testAccount); // Assert Assert.Equal(ValidateTokenResult.Invalid, result); }
/// <summary> /// Resets password for account with email <paramref name="email"/>. /// </summary> /// <param name="email"></param> /// <param name="token"></param> /// <param name="newPassword"></param> /// <returns> /// <see cref="ResetPasswordActionResult.InvalidEmail"/> if email is invalid. /// <see cref="ResetPasswordActionResult.InvalidNewPassword"/> if new password is same as old password. /// <see cref="ResetPasswordActionResult.InvalidToken"/> if token is invalid. /// <see cref="ResetPasswordActionResult.Success"/> if password reset is successful. /// </returns> /// <exception cref="Exception">Thrown if a database error occurs.</exception> public virtual async Task <ResetPasswordActionResult> ResetPasswordActionAsync(string email, string token, string newPassword) { if (string.IsNullOrEmpty(email)) { throw new ArgumentException(nameof(email)); } if (string.IsNullOrEmpty(token)) { throw new ArgumentException(nameof(token)); } if (string.IsNullOrEmpty(newPassword)) { throw new ArgumentException(nameof(newPassword)); } TAccount account = await _accountRepository.GetAsync(email, _cancellationToken); if (account == null) { return(ResetPasswordActionResult.InvalidEmail); } if (_passwordService.ValidatePassword(account.PasswordHash, newPassword)) { return(ResetPasswordActionResult.InvalidNewPassword); } ValidateTokenResult validateTokenResult = ValidateToken(TokenServiceOptions.DataProtectionTokenService, _options.ResetPasswordTokenPurpose, account, token); if (validateTokenResult != ValidateTokenResult.Valid) { return(ResetPasswordActionResult.InvalidToken); } SaveChangesResult result = await _accountRepository.UpdatePasswordHashAsync(account, _passwordService.HashPassword(newPassword), _cancellationToken); if (result == SaveChangesResult.ConcurrencyError) { // Unrecoverable by calling function. throw new Exception(); } return(ResetPasswordActionResult.Success); }
public void ValidateToken_ReturnsValidateTokenResultInvalidIfTokenIsInvalidTest() { // Arrange DataProtectionTokenService <StubAccount> dataProtectionTokenService = new DataProtectionTokenService <StubAccount>(_dataProtectionProvider, CreateTokenServiceOptions().Object, _testTimeService); string token = dataProtectionTokenService.GenerateToken(_testInvalidPurpose, _testAccount); // Act ValidateTokenResult result = dataProtectionTokenService.ValidateToken(_testValidPurpose, token, _testAccount); // Assert Assert.Equal(ValidateTokenResult.Invalid, result); }
public static ValidateTokenResult DecodingToken(string token) { ValidateTokenResult validateTokenResult = new ValidateTokenResult(); try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); var json = decoder.Decode(token, secret, verify: true); Payload payload = serializer.Deserialize <Payload>(json); var currentTime = DateTime.Now; if (currentTime > payload.Exp) { throw new TokenExpiredException("Token已过期"); } else //未过期,延长时间 { payload.Exp = DateTime.Now.AddDays(7); } validateTokenResult.Status = true; validateTokenResult.Payload = payload; validateTokenResult.ResultCode = ResultCode.Ok; return(validateTokenResult); } catch (TokenExpiredException ex) { validateTokenResult.Status = false; validateTokenResult.ErrorData = ex.Message; validateTokenResult.ResultCode = ResultCode.Error; return(validateTokenResult); } catch (SignatureVerificationException exception) { validateTokenResult.Status = false; validateTokenResult.ErrorData = exception; validateTokenResult.ResultCode = ResultCode.Error; return(validateTokenResult); } }
/// <summary> /// Sets email verified and two factor enabled of logged in account to true if <paramref name="code"/> is valid. /// </summary> /// <param name="code"></param> /// <returns> /// <see cref="TwoFactorVerifyEmailActionResult.Success"/> if email verified change succeeds. /// <see cref="TwoFactorVerifyEmailActionResult.AlreadySet"/> if account email verified is already true. /// <see cref="TwoFactorVerifyEmailActionResult.NoLoggedInAccount"/> if unable to retrieve logged in account. /// <see cref="TwoFactorVerifyEmailActionResult.InvalidCode"/> if code is invalid. /// </returns> /// <exception cref="Exception">Thrown if a database update fails unexpectedly.</exception> public virtual async Task <TwoFactorVerifyEmailActionResult> TwoFactorVerifyEmailActionAsync(string code) { if (string.IsNullOrEmpty(code)) { throw new ArgumentException(nameof(code)); } TAccount account = await GetApplicationAccountAsync(); if (account == null) { return(TwoFactorVerifyEmailActionResult.NoLoggedInAccount); } if (account.EmailVerified == true) { return(TwoFactorVerifyEmailActionResult.AlreadySet); } ValidateTokenResult validateTokenResult = ValidateToken(TokenServiceOptions.TotpTokenService, _options.TwoFactorTokenPurpose, account, code); if (validateTokenResult == ValidateTokenResult.Invalid) { return(TwoFactorVerifyEmailActionResult.InvalidCode); } SaveChangesResult result = await _accountRepository.UpdateAsync(account, _cancellationToken, emailVerified : true, twoFactorEnabled : true); if (result == SaveChangesResult.ConcurrencyError) { // Unrecoverable throw new Exception(); } return(TwoFactorVerifyEmailActionResult.Success); }
/// <summary> /// Sets alt email verified of logged in account to true if <paramref name="token"/> is valid. /// </summary> /// <param name="token"></param> /// <returns> /// <see cref="SetAltEmailVerifiedActionResult.Success"/> if alt email verified change succeeds. /// <see cref="SetAltEmailVerifiedActionResult.AlreadySet"/> if account alt email verified is already true. /// <see cref="SetAltEmailVerifiedActionResult.NoLoggedInAccount"/> if unable to retrieve logged in account. /// <see cref="SetAltEmailVerifiedActionResult.InvalidToken"/> if token is invalid. /// </returns> /// <exception cref="Exception">Thrown if database update fails unexpectedly.</exception> public virtual async Task <SetAltEmailVerifiedActionResult> SetAltEmailVerifiedActionAsync(string token) { if (string.IsNullOrEmpty(token)) { throw new ArgumentException(nameof(token)); } TAccount account = await GetApplicationAccountAsync(); if (account == null) { return(SetAltEmailVerifiedActionResult.NoLoggedInAccount); } if (account.AltEmailVerified == true) { return(SetAltEmailVerifiedActionResult.AlreadySet); } ValidateTokenResult validateTokenResult = ValidateToken(TokenServiceOptions.DataProtectionTokenService, _options.ConfirmAltEmailTokenPurpose, account, token); if (validateTokenResult != ValidateTokenResult.Valid) { return(SetAltEmailVerifiedActionResult.InvalidToken); } SaveChangesResult result = await _accountRepository.UpdateAltEmailVerifiedAsync(account, true, _cancellationToken); if (result == SaveChangesResult.ConcurrencyError) { // Unrecoverable throw new Exception(); } return(SetAltEmailVerifiedActionResult.Success); }
public async Task <string> ValidateTokenAsync(string AuthToken, CancellationToken cancellationToken) { await OutputProtocol.WriteMessageBeginAsync(new TMessage("ValidateToken", TMessageType.Call, SeqId), cancellationToken); var args = new ValidateTokenArgs(); args.AuthToken = AuthToken; await args.WriteAsync(OutputProtocol, cancellationToken); await OutputProtocol.WriteMessageEndAsync(cancellationToken); await OutputProtocol.Transport.FlushAsync(cancellationToken); var msg = await InputProtocol.ReadMessageBeginAsync(cancellationToken); if (msg.Type == TMessageType.Exception) { var x = await TApplicationException.ReadAsync(InputProtocol, cancellationToken); await InputProtocol.ReadMessageEndAsync(cancellationToken); throw x; } var result = new ValidateTokenResult(); await result.ReadAsync(InputProtocol, cancellationToken); await InputProtocol.ReadMessageEndAsync(cancellationToken); if (result.__isset.success) { return(result.Success); } throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, "ValidateToken failed: unknown result"); }