Returns value for expires_in by given scope and token type.

@param scope          scope/s for which expires in will be returned
@param tokenGrantType client_credentials or password type
@return minimum value of given scope/s expires_in
774346
public int getExpiresIn(String tokenGrantType, String scope) {
        int expiresIn = Integer.MAX_VALUE;
        List<Scope> scopes = loadScopes(scope);
        boolean ccGrantType = TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType);
        if (TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getCcExpiresIn() < expiresIn) {
                    expiresIn = s.getCcExpiresIn();
                }
            }
        } else if (TokenRequest.PASSWORD.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getPassExpiresIn() < expiresIn) {
                    expiresIn = s.getPassExpiresIn();
                }
            }
        } else {
            // refresh_token
            for (Scope s : scopes) {
                if (s.getRefreshExpiresIn() < expiresIn) {
                    expiresIn = s.getRefreshExpiresIn();
                }
            }
        }
        if (scopes.size() == 0 || expiresIn == Integer.MAX_VALUE) {
            expiresIn = (ccGrantType) ? OAuthConfig.DEFAULT_CC_EXPIRES_IN : OAuthConfig.DEFAULT_PASSWORD_EXPIRES_IN;
        }
        return expiresIn;
    }
60597
def get_token(self, client_id, target, api_type, grant_type,
                  id_token=None, refresh_token=None, scope='openid'):

        

        if id_token and refresh_token:
            raise ValueError('Only one of id_token or refresh_token '
                             'can be None')

        data = {
            'client_id': client_id,
            'grant_type': grant_type,
            'target': target,
            'scope': scope,
            'api_type': api_type,
        }

        if id_token:
            data.update({'id_token': id_token})
        elif refresh_token:
            data.update({'refresh_token': refresh_token})
        else:
            raise ValueError('Either id_token or refresh_token must '
                             'have a value')

        return self.post(
            'https://{}/delegation'.format(self.domain),
            headers={'Content-Type': 'application/json'},
            data=data
        )
713547
@Transactional(readOnly = true)
    public void validateToken(E token) throws Exception {

        if (token == null) {
            throw new Exception("The provided token is null.");
        }

        DateTime expirationDate = (DateTime) token.getExpirationDate();

        String tokenValue = token.getToken();

        // check if the token expire date is valid
        if (expirationDate.isBeforeNow()) {
            throw new Exception("The token '" + tokenValue + "' expired on '"
                + expirationDate + "'");
        }

    }
294947
def _generateForTokenSecurity(self,
                                  username, password,
                                  tokenUrl,
                                  expiration=None,
                                  client='requestip'):
        

        query_dict = {'username': username,
                      'password': password,
                      'expiration':str(_defaultTokenExpiration),
                      'client': client,
                      'f': 'json'}
        if client == "referer":
            query_dict['referer'] = self._referer_url
        if expiration is not None:
            query_dict['expiration'] = expiration

        secHandler = None
        if self.cookiejar is not None:
            secHandler = self
            if secHandler is not None:
                secHandler._method = "HANDLER"
        token = self._post(url=tokenUrl,
                           param_dict=query_dict,
                           securityHandler=secHandler,
                           proxy_port=self._proxy_port,
                           proxy_url=self._proxy_url)
        if self.cookiejar is not None:
            if secHandler is not None:
                secHandler._method = "TOKEN"
        if 'error' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None

            return token
        elif 'status' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None
            #print token['message']
            return token

        else:
            self._token = token['token']
            self._token_created_on = datetime.datetime.now()
            self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \
                datetime.timedelta(seconds=1)
            self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds()
            return token['token']
85703
public function setRefreshToken($token, $clientId, $userId, $expiryTimestamp, $scope = null)
    {
        $refreshTokenDataMapper = $this->getTokenDataMapper(Entity\RefreshToken::class);

        $client = $this->getClientDataMapper()->findByUuid($clientId);

        if (! $refreshToken = $refreshTokenDataMapper->findByToken($token)) {
            $refreshToken = new Entity\RefreshToken(null, $token, $client);
        } else {
            $refreshToken->setClient($client);
        }

        if ($userId) {
            $user = $this->getUserDataMapper()->findByUuid($userId);
            if ($user instanceof $this->userClass) {
                $refreshToken->setUser($user);
            }
        }

        $expiryDate = is_int($expiryTimestamp) ? new DateTime('@' . $expiryTimestamp) : null;
        $refreshToken->setExpiryDate($expiryDate);

        if ($scope) {
            $scopes = $this->getScopeDataMapper()->findScopes(explode(' ', $scope));
            $refreshToken->setScopes($scopes);
        }

        $refreshTokenDataMapper->save($refreshToken);
    }
1213157
public function createToken($redirectUri, $owner, $client, array $scopes = []): AuthorizationCode
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = AuthorizationCode::createNewAuthorizationCode(
                $this->serverOptions->getAuthorizationCodeTtl(),
                $redirectUri,
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
642740
private static Credential getCredentialFromAccessTokenProvider(
      AccessTokenProvider accessTokenProvider, Collection<String> scopes)
      throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(
        accessTokenProvider.getAccessToken() != null, "Access Token cannot be null!");
    GoogleCredential credential =
        GoogleCredentialWithAccessTokenProvider.fromAccessTokenProvider(
            Clock.SYSTEM, accessTokenProvider);
    // TODO: credential.createScoped does nothing at the moment, since
    //  GoogleCredentialWithAccessTokenProvider never sets the serviceAccountPrivateKey.
    //  The AccessTokenProvider interface does not provide a mechanism to return a private key,
    //  and scopes cannot be sent down to the AccessTokenProvider
    //  so they're essentially ignored at the moment.
    return credential.createScoped(scopes);
  }
382895
public static Token<EsTokenIdentifier> obtainToken(RestClient client, User user) {
        EsToken esToken = obtainEsToken(client, user);
        return EsTokenIdentifier.createTokenFrom(esToken);
    }
118853
protected function getTokenByClientCredentialsGrant()
    {
        $token = $this->getAuthorizationServer()->getAccessToken('client_credentials', [
            'scope' => $this->config['client_credentials']['scope'],
        ]);

        $this->getFrameworkBridge()->persistClientToken(
            $this->config['client_credentials']['client_id'],
            $token->getToken(),
            $token->getExpires(),
            $token->getValues()['role']
        );

        return $token;
    }
741778
function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) {
  if (!tokenSecret) {
    throw new Error('Token secret is undefined');
  }

  const data = {
    user: this._id.toString(),
  };

  if (scope.length) {
    data.scope = scope;
  }

  const token = jwt.sign(data, tokenSecret, {
    expiresInMinutes,
  });

  return {
    type: 'Bearer',
    value: token,
  };
}
790674
@Restricted(NoExternalUse.class)
    public boolean hasMoreRecentlyUsedToken(@Nonnull User user, @Nullable ApiTokenProperty.TokenInfoAndStats legacyStats) {
        if (legacyStats == null) {
            return false;
        }
        
        ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class);
        
        return apiTokenProperty.getTokenList().stream()
                .filter(token -> !token.isLegacy)
                .anyMatch(token -> {
                    Date currentLastUseDate = token.lastUseDate;
                    Date legacyLastUseDate = legacyStats.lastUseDate;
                    if (legacyLastUseDate == null) {
                        legacyLastUseDate = legacyStats.creationDate;
                    }
                    return currentLastUseDate != null && legacyLastUseDate != null && currentLastUseDate.after(legacyLastUseDate);
                });
    }
503988
private DateTime credentialExpirationTime(JsonNode credentialsJson) {
        String expiration = getText(credentialsJson, "Expiration");

        if (expiration != null) {
            DateTime credentialExpiration = new DateTime(DateUtils.parseISO8601Date(expiration));
            credentialExpiration = credentialExpiration.minus(expirationBufferUnit.toMillis(expirationBufferValue));
            return credentialExpiration;
        } else {
            return DateTime.now().plusYears(9999);
        }
    }
894586
public static String getPasswordResetToken(final RequestContext requestContext) {
        val flowScope = requestContext.getFlowScope();
        return flowScope.getString(FLOWSCOPE_PARAMETER_NAME_TOKEN);
    }
979492
public String getDelegationToken(String owner, String renewer) throws HiveSQLException {
    if (saslServer == null) {
      throw new HiveSQLException(
          "Delegation token only supported over kerberos authentication", "08S01");
    }

    try {
      String tokenStr = saslServer.getDelegationTokenWithService(owner, renewer, HS2_CLIENT_TOKEN);
      if (tokenStr == null || tokenStr.isEmpty()) {
        throw new HiveSQLException(
            "Received empty retrieving delegation token for user " + owner, "08S01");
      }
      return tokenStr;
    } catch (IOException e) {
      throw new HiveSQLException(
          "Error retrieving delegation token for user " + owner, "08S01", e);
    } catch (InterruptedException e) {
      throw new HiveSQLException("delegation token retrieval interrupted", "08S01", e);
    }
  }
625589
public static Map<String, Object> createFormParamClientCredentialsGrantType(String scope) {
        Map<String, Object> formParams = new HashMap<>();
        formParams.put("grant_type", "client_credentials");
        if (scope != null) {
            formParams.put("scope", scope);
        }
        return formParams;
    }
366965
public Token<DelegationTokenIdentifier> selectTokenFromFsOwner() throws IOException {
    return lookupToken(user.getCredentials(), service, tokenBinding.getKind());
  }
189740
@SuppressWarnings("OptionalGetWithoutIsPresent")
  public Token<DelegationTokenIdentifier> getBoundOrNewDT(String renewer) throws IOException {
    logger.atFine().log("Delegation token requested");
    if (isBoundToDT()) {
      // the FS was created on startup with a token, so return it.
      logger.atFine().log("Returning current token");
      return getBoundDT();
    }

    // not bound to a token, so create a new one.
    // issued DTs are not cached so that long-lived filesystems can
    // reliably issue session/role tokens.
    return tokenBinding.createDelegationToken(renewer);
  }