Tests given token against stored one.
@param req request used to retrieve stored cookie
@param token token to be tested
@return a boolean indicating if given token is valid.
168874
public final boolean isValid(HttpServletRequest req, String token) {
		String storedToken = getStoredToken(req);
		
		if (storedToken == null)
			return false;
		
		return storedToken.equals(token);
	}
125662
public static Map<String, Object> verify(String token, final RSAPublicKey pk) throws InvalidTokenException {
        // RS256签名验证器
        Verifier verifier = new Verifier() {
            @Override
            public boolean verifySignature(String content, String payload, String signature) {
                return JWT.verifySignature(content,signature,pk);
            }
        };
        return verify(token, verifier);
    }
692784
public OAuthAccessToken refreshToken(RequestContext requestContext, OAuthAccessToken token) {
    OAuthAccessToken result = token;
    
    String[] scopes = token.getScopes();
    String tokenUrl = String.format("%s/realms/%s/protocol/openid-connect/token", getServerUrl(), getRealm());
    
    HttpPost httpPost = new HttpPost(tokenUrl);
    
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("client_id", getApiKey()));
      params.add(new BasicNameValuePair("client_secret", getApiSecret()));
      params.add(new BasicNameValuePair("grant_type", "refresh_token"));
      params.add(new BasicNameValuePair("refresh_token", token.getRefreshToken()));

      httpPost.setEntity(new UrlEncodedFormEntity(params));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        
        if (statusLine.getStatusCode() == 200) {
          HttpEntity entity = response.getEntity();
          
          ObjectMapper objectMapper = new ObjectMapper();
          try (InputStream stream = entity.getContent()) {
            RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(stream, RefreshTokenResponse.class);
            Date expiresAt = getExpiresAt(refreshTokenResponse.getExpiresIn());
            result = new OAuthAccessToken(token.getExternalId(), refreshTokenResponse.getAccessToken(), refreshTokenResponse.getRefreshToken(), expiresAt, scopes);
            AuthUtils.purgeOAuthAccessTokens(requestContext, getName());
            AuthUtils.storeOAuthAccessToken(requestContext, getName(), result);            
          }
          
          EntityUtils.consume(entity);
        } else {
          logger.log(Level.WARNING, String.format("Failed to refresh access token with message [%d]: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
      }
    } catch (IOException e) {
      logger.log(Level.WARNING, "Failed to refresh access token", e);
    }
    
    return result;
  }
103107
function _getCookieToken (cookies, req, cookieName, cookieDomain, publicUrl) {
  let token = cookies.get(cookieName)
  if (!token) return null
  const reqOrigin = req.headers['origin']
  const originDomain = reqOrigin && new URL(reqOrigin).host

  // check that the origin of the request is part of the accepted domain
  if (reqOrigin && cookieDomain && originDomain !== cookieDomain && !originDomain.endsWith('.' + cookieDomain)) {
    debug(`A cookie was sent from origin ${reqOrigin} while cookie domain is ${cookieDomain}, ignore it`)
    return null
  }
  // or simply that it is strictly equal to current target if domain is unspecified
  // in this case we are also protected by sameSite
  if (reqOrigin && !cookieDomain && reqOrigin !== new URL(publicUrl).origin) {
    debug(`A cookie was sent from origin ${reqOrigin} while public url is ${publicUrl}, ignore it`)
    return null
  }

  // Putting the signature in a second token is recommended but optional
  // and we accept full JWT in id_token cooke
  const signature = cookies.get(cookieName + '_sign')
  if (signature && (token.match(/\./g) || []).length === 1) {
    token += '.' + signature
  }
  return token
}
873440
@SuppressWarnings("unused")
    public static boolean isTokenValid(byte[] secret, String oid, String token) {
        if (S.anyBlank(oid, token)) {
            return false;
        }
        String s = Crypto.decryptAES(token, secret);
        String[] sa = s.split("\\|");
        if (sa.length < 2) return false;
        if (!S.isEqual(oid, sa[0])) return false;
        try {
            long due = Long.parseLong(sa[1]);
            return (due < 1 || due > System.currentTimeMillis());
        } catch (Exception e) {
            return false;
        }
    }
433417
public JwtToken refreshToken(String token) {
        String refreshedToken;
        Date expireTime = generateExpirationDate();
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, expireTime.getTime());
            refreshedToken = build(claims, expireTime);
        } catch (Exception e) {
            log.error("refreshedToken jwt token error : {}", e.getMessage());
            refreshedToken = null;
        }
        return new JwtToken(refreshedToken, expireTime.getTime());
    }
724757
public final boolean isValidEmailConfirmationToken(String token) {
		Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
		return isValidToken(s, Config._EMAIL_TOKEN, token);
	}
915675
public function isTokenValid(CsrfToken $token) {

		$tokenId = $token->getId();

		if (!$this->storage->hasToken($tokenId)) {
			return FALSE;
		}
	
		return hash_equals($this->storage->getToken($tokenId)->getValue(), $token->getValue());

	}
1371748
def check_token(self, respond):
        
        if respond.status_code == 401:
            self.credential.obtain_token(config=self.config)
            return False
        return True
301843
public function addCheckToken(string $token, string $cookie_url): bool
    {
        if (\Yii::$app->getRequest()->getCookies()->getValue('auth_token')) {
            \Yii::$app->getResponse()->getCookies()->remove('auth_token');
        }
        setcookie('auth_token', $token, time() + DateHelper::TIME_DAY_THIRTY, '/', $cookie_url, false, false);
        return true;
    }
407299
public Optional<String> authenticate(String token) {
    String tokenHash = tokenGenerator.hash(token);
    try (DbSession dbSession = dbClient.openSession(false)) {
      UserTokenDto userToken = dbClient.userTokenDao().selectByTokenHash(dbSession, tokenHash);
      if (userToken == null) {
        return empty();
      }
      userLastConnectionDatesUpdater.updateLastConnectionDateIfNeeded(userToken);
      return of(userToken.getUserUuid());
    }
  }
575794
public CommonProfile validateToken(final String token) {
        final TokenCredentials credentials = new TokenCredentials(token);
        try {
            validate(credentials, null);
        } catch (final HttpAction e) {
            throw new TechnicalException(e);
        } catch (final CredentialsException e) {
            logger.info("Failed to retrieve or validate credentials: {}", e.getMessage());
            logger.debug("Failed to retrieve or validate credentials", e);
            return null;
        }
        return credentials.getUserProfile();
    }
939434
protected synchronized void cacheToken(final Token token) {

		log.debug("OAuthTokenManager.cacheToken");

		// Parse token expires in seconds.
		int tokenExpiresInSecs;
		try {
			tokenExpiresInSecs = Integer.parseInt(token.getExpires_in());
		} catch (NumberFormatException exception) {
			tokenExpiresInSecs = 0;
		}

		// Parse token expiration time
		long tokenExpirationTime;
		try {
			tokenExpirationTime = Long.parseLong(token.getExpiration());
		} catch (NumberFormatException exception) {
			tokenExpirationTime = 0;
		}

		// Calculate token refresh time based on lifespan percentage offset.
		long refreshBeforeExpirySecs = (long) (tokenExpiresInSecs * this.iamRefreshOffset);
		long tokenRefreshTime = tokenExpirationTime - refreshBeforeExpirySecs;

		token.setRefreshTime(tokenRefreshTime);
		token.setExpirationTime(tokenExpirationTime);

		setTokenCache(token);
	}
1082963
protected void store(HttpServletRequest req, HttpServletResponse resp, String token) {
		HttpSession session = req.getSession();
		session.setAttribute(ATR_SESSION_TOKEN, token);
	}
264153
public static String getToken(final HttpServletRequest request, final String key) {
		return (String) request.getSession(true).getAttribute(key);
	}
800339
function validateToken (token) {
  const header = jwt.decode(token)
  const now = Math.floor(Date.now() / 1000)
  return header && header.exp > now
}
46581
@RequestMapping(value = "/gettoken", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage getToken(HttpServletRequest request, HttpServletResponse response) {
        String username = StringUtil.EMPTY_STRING;
        String password = StringUtil.EMPTY_STRING;
        ResponseMessage result = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            if (json.has("username")) {
                username = json.getString("username");
            }
            if (json.has("password")) {
                password = json.getString("password");
            }

            mUserService.validLoginUser(username, password);
            String token = mUserService.createToken(username, request.getRemoteAddr());
            result.setStatus(true);
            result.setData(token);
        } catch (Exception e) {
            result.setStatus(false);
            result.setData(e.getMessage());
        }
        return result;
    }