//
// TokenContainer
//
// Validates that the AccessToken within TokenContainer is not expired and not empty.
962665
func (t *TokenContainer) Valid() bool {
	if t.Token == nil {
		return false
	}
	return t.Token.Valid()
}
245500
func (a *authenticator) validateToken(token *jwt.Token, url, method string) error {
	var userName string
	// Read audience from the token
	switch v := token.Claims.(type) {
	case jwt.MapClaims:
		var ok bool
		if userName, ok = v["aud"].(string); !ok {
			return fmt.Errorf("failed to validate token claims audience")
		}
	case jwt.StandardClaims:
		userName = v.Audience
	default:
		return fmt.Errorf("failed to validate token claims")
	}
	loggedOut, err := a.userDb.IsLoggedOut(userName)
	if err != nil {
		return fmt.Errorf("failed to validate token: %v", err)
	}
	if loggedOut {
		// User logged out
		token.Valid = false
		return fmt.Errorf("invalid token")
	}
	user, err := a.userDb.GetUser(userName)
	if err != nil {
		return fmt.Errorf("failed to validate token: %v", err)
	}
	// Do not check for permissions if user is admin
	if userIsAdmin(user) {
		return nil
	}
	perms := a.getPermissionsForURL(url, method)
	for _, userPerm := range user.Permissions {
		for _, perm := range perms {
			if userPerm == perm {
				return nil
			}
		}
	}

	return fmt.Errorf("not permitted")
}
603895
func (s *tokenServiceImpl) RegisterToken(ctx context.Context, identityID uuid.UUID, tokenString string, tokenType string,
	privileges []tokenrepo.TokenPrivilege) (*tokenrepo.Token, error) {

	// Parse the claims from the provided token string
	tokenClaims, err := s.tokenManager.ParseToken(ctx, tokenString)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "invalid token string could not be parsed")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"invalid token string could not be parsed")
	}

	// Extract the id from the refresh token
	tokenID, err := uuid.FromString(tokenClaims.Id)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "could not extract token ID from token string")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"could not extract token ID from token string")
	}

	expiryTime := time.Unix(tokenClaims.ExpiresAt, 0)

	tkn := &tokenrepo.Token{
		TokenID:    tokenID,
		IdentityID: identityID,
		Status:     0,
		TokenType:  tokenType,
		ExpiryTime: expiryTime,
	}

	// Persist the token record to the database
	err = s.ExecuteInTransaction(func() error {
		err = s.Repositories().TokenRepository().Create(ctx, tkn)
		if err != nil {
			return err
		}

		// If the access token is an RPT, register its permissions also
		if privileges != nil && len(privileges) > 0 {
			// Assign privileges to the token record, and persist them to the database
			for _, tokenPriv := range privileges {
				tokenPriv.TokenID = tokenID
				err = s.Repositories().TokenRepository().CreatePrivilege(ctx, &tokenPriv)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})

	if err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}

	return tkn, nil
}
189701
public boolean validateToken(final String token) {
        try {
            final JwtParser jwtParser = Jwts.parser().setSigningKey(key);
            jwtParser.parse(token);
            this.subject = jwtParser.parseClaimsJws(token).getBody().getSubject();
            this.expiration = jwtParser.parseClaimsJws(token).getBody().getExpiration();
            return true;
        } catch (SignatureException e) {
            LOGGER.info(SecurityMarkers.SECURITY_FAILURE, "Received token that did not pass signature verification");
        } catch (ExpiredJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received expired token");
        } catch (MalformedJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received malformed token");
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        } catch (UnsupportedJwtException | IllegalArgumentException e) {
            LOGGER.error(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        }
        return false;
    }
10294
func (a *ACLToken) Validate() error {
	var mErr multierror.Error
	if len(a.Name) > maxTokenNameLength {
		mErr.Errors = append(mErr.Errors, fmt.Errorf("token name too long"))
	}
	switch a.Type {
	case ACLClientToken:
		if len(a.Policies) == 0 {
			mErr.Errors = append(mErr.Errors, fmt.Errorf("client token missing policies"))
		}
	case ACLManagementToken:
		if len(a.Policies) != 0 {
			mErr.Errors = append(mErr.Errors, fmt.Errorf("management token cannot be associated with policies"))
		}
	default:
		mErr.Errors = append(mErr.Errors, fmt.Errorf("token type must be client or management"))
	}
	return mErr.ErrorOrNil()
}
1192232
func checkSubtokenExpiration(t *messages.Subtoken, now int64) error {
	if t.CreationTime <= 0 {
		return fmt.Errorf("invalid 'creation_time' field: %d", t.CreationTime)
	}
	dur := int64(t.ValidityDuration)
	if dur <= 0 {
		return fmt.Errorf("invalid validity_duration: %d", dur)
	}
	if t.CreationTime >= now+allowedClockDriftSec {
		return fmt.Errorf("token is not active yet (created at %d)", t.CreationTime)
	}
	if t.CreationTime+dur < now {
		return fmt.Errorf("token has expired %d sec ago", now-(t.CreationTime+dur))
	}
	return nil
}
389041
func (s *FileSystemAPIServer) validateToken(t string) (string, error) {
	var tData TokenRef
	var aData AcctPayLoad
	var tDataByte []byte
	var aDataByte []byte
	var err error

	// Read Token
	pKeyA, pKeyB := murmur3.Sum128([]byte("/token"))
	cKeyA, cKeyB := murmur3.Sum128([]byte(t))
	_, tDataByte, err = s.gstore.Read(context.Background(), pKeyA, pKeyB, cKeyA, cKeyB, nil)
	if store.IsNotFound(err) {
		return "", errors.New("Not Found")
	}
	err = json.Unmarshal(tDataByte, &tData)
	if err != nil {
		log.Printf("TOKEN FAILED %v\n", err)
		return "", err
	}

	// Read Account
	pKeyA, pKeyB = murmur3.Sum128([]byte("/acct"))
	cKeyA, cKeyB = murmur3.Sum128([]byte(tData.AcctID))
	_, aDataByte, err = s.gstore.Read(context.Background(), pKeyA, pKeyB, cKeyA, cKeyB, nil)
	if store.IsNotFound(err) {
		return "", errors.New("Not Found")
	}
	err = json.Unmarshal(aDataByte, &aData)
	if err != nil {
		log.Printf("TOKEN FAILED %v\n", err)
		return "", err
	}

	if tData.TokenID != aData.Token {
		// Log Failed Operation
		log.Printf("TOKEN FAIL %s\n", t)
		return "", errors.New("Invalid Token")
	}

	// Return Account UUID
	// Log Operation
	log.Printf("TOKEN SUCCESS %s\n", tData.AcctID)
	return tData.AcctID, nil
}
168874
public final boolean isValid(HttpServletRequest req, String token) {
		String storedToken = getStoredToken(req);
		
		if (storedToken == null)
			return false;
		
		return storedToken.equals(token);
	}
157414
func (constraints *tokenConstraints) validate() (err error) {
	keys := 0
	if constraints.key != nil {
		keys++
	}
	if constraints.secret != "" {
		keys++
	}
	if keys > 1 {
		err = fmt.Errorf("duplicate key constraints")
		return
	}
	if keys < 1 {
		err = fmt.Errorf("no key constraint")
		return
	}
	return
}
270985
public final void validateExpiration() throws TokenExpiredException {
        Date d = new Date();
        Date expD = new Date(getExpiration());
        boolean expired = d.after(expD);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "Current time = " + d + ", expiration time = " + expD);
        }
        if (expired) {
            String msg = "The token has expired: current time = \"" + d + "\", expire time = \"" + expD + "\"";
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, msg);
            }
            throw new TokenExpiredException(expirationInMilliseconds, msg);
        }
    }
24300
func (token *Token) Validate(securityCode string) (valid bool) {

	totp := otp.TOTP{
		Secret:         token.Secret,
		IsBase32Secret: true,
	}
	valid = totp.Now().Verify(securityCode)
	return

}
1134871
func (t *Token) expired() bool {
	if t.Expiry.IsZero() {
		return false
	}
	return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow())
}
157341
func (t *TokenRefresher) RefreshAuthToken() (string, error) {
	tokens, err := t.uaaClient.RefreshAccessToken(t.cache.RefreshToken())
	if err != nil {
		return "", err
	}

	t.cache.SetAccessToken(tokens.AuthorizationToken())
	t.cache.SetRefreshToken(tokens.RefreshToken)
	return tokens.AuthorizationToken(), nil
}
795284
func validateToken(p Provider, access_token string, header http.Header) bool {
	if access_token == "" || p.Data().ValidateURL == nil {
		return false
	}
	endpoint := p.Data().ValidateURL.String()
	if len(header) == 0 {
		params := url.Values{"access_token": {access_token}}
		endpoint = endpoint + "?" + params.Encode()
	}
	resp, err := api.RequestUnparsedResponse(endpoint, header)
	if err != nil {
		log.Printf("GET %s", stripToken(endpoint))
		log.Printf("token validation request failed: %s", err)
		return false
	}

	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	log.Printf("%d GET %s %s", resp.StatusCode, stripToken(endpoint), body)

	if resp.StatusCode == 200 {
		return true
	}
	log.Printf("token validation request failed: status %d - %s", resp.StatusCode, body)
	return false
}
948115
func checkExpiration(body *tokenserver.MachineTokenBody, now time.Time) error {
	notBefore := time.Unix(int64(body.IssuedAt), 0)
	notAfter := notBefore.Add(time.Duration(body.Lifetime) * time.Second)
	if now.Before(notBefore.Add(-allowedClockDrift)) {
		diff := notBefore.Sub(now)
		return fmt.Errorf("token is not valid yet, will be valid in %s", diff)
	}
	if now.After(notAfter.Add(allowedClockDrift)) {
		diff := now.Sub(notAfter)
		return fmt.Errorf("token expired %s ago", diff)
	}
	return nil
}
93192
public Authentication verifyAccessToken(String accessToken) throws InvalidTokenException, TokenExpiredException{
        CacheProvider cp = cp();

        Authentication authc = cp.get(accessToken);
        if(null != authc) {
            if(!authc.isExpired()) {
                return authc;
            }else{
                cp.remove(accessToken);
            }
        }

        boolean jwt = checkJwtToken(accessToken);
        if(jwt) {
            authc = tp().verifyJwtAccessToken(accessToken);
        }else{
            authc = tp().verifyBearerAccessToken(accessToken);
        }

        cp.put(accessToken, authc, authc.getExpires());

        return authc;
    }
1158494
func (client *Client) verifyAccessToken() error {
	if len(client.AccessToken) > 0 {
		return nil
	} else {
		return fmt.Errorf("missing access token")
	}
}