Generates new api access token.
508186
public function generateAccessToken()
    {

        // $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();
        $signer = new Sha256();
        $token = Yii::$app->jwt->getBuilder()->setIssuer(Yii::getAlias("@restIssuer"))// Configures the issuer (iss claim)
        ->setAudience(Yii::getAlias("@restAudience"))// Configures the audience (aud claim)
        ->setId(Yii::getAlias("@restId")+ strtotime(date('Y-m-d',time())), true)
            ->setExpiration(time() + Yii::$app->params['accessTokenExpire'])// Configures exp time
            ->setIssuedAt(time())// Configures the time that the token was issue (iat claim)

            ->sign($signer, Yii::$app->jwt->key)
            ->getToken(); // Retrieves the generated token
        //$this->auth_key=$this->id;
        $this->access_token = (string)$token;
    }
721471
def token_new():
    """"""
    form = TokenForm(request.form)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        t = Token.create_personal(
            form.data['name'], current_user.get_id(), scopes=form.scopes.data
        )
        db.session.commit()
        session['show_personal_access_token'] = True
        return redirect(url_for(".token_view", token_id=t.id))

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_new.html",
        form=form,
    )
51938
def token(ctx, opts, login, password):
    """"""
    click.echo(
        "Retrieving API token for %(login)s ... "
        % {"login": click.style(login, bold=True)},
        nl=False,
    )

    context_msg = "Failed to retrieve the API token!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            api_key = get_user_token(login=login, password=password)

    click.secho("OK", fg="green")

    click.echo(
        "Your API key/token is: %(token)s"
        % {"token": click.style(api_key, fg="magenta")}
    )

    create, has_errors = create_config_files(ctx, opts, api_key=api_key)

    if has_errors:
        click.echo()
        click.secho("Oops, please fix the errors and try again!", fg="red")
        return

    if opts.api_key != api_key:
        click.echo()
        if opts.api_key:
            click.secho(
                "Note: The above API key doesn't match what you have in "
                "your default credentials config file.",
                fg="yellow",
            )
        elif not create:
            click.secho(
                "Note: Don't forget to put your API key in a config file, "
                "export it on the environment, or set it via -k.",
                fg="yellow",
            )
            click.secho(
                "If you need more help please see the documentation: "
                "%(website)s" % {"website": click.style(get_help_website(), bold=True)}
            )
        click.echo()

    click.secho("You're ready to rock, let's start automating!", fg="green")
360765
protected Pair<AccessToken, RefreshToken> generateAccessTokenOAuthGrantTypes(final AccessTokenRequestDataHolder holder) {
        LOGGER.debug("Creating access token for [{}]", holder.getService());
        val clientId = holder.getRegisteredService().getClientId();
        val authn = DefaultAuthenticationBuilder
            .newInstance(holder.getAuthentication())
            .addAttribute(OAuth20Constants.GRANT_TYPE, holder.getGrantType().toString())
            .addAttribute(OAuth20Constants.SCOPE, holder.getScopes())
            .addAttribute(OAuth20Constants.CLIENT_ID, clientId)
            .build();

        LOGGER.debug("Creating access token for [{}]", holder);
        val ticketGrantingTicket = holder.getTicketGrantingTicket();
        val accessToken = this.accessTokenFactory.create(holder.getService(),
            authn, ticketGrantingTicket, holder.getScopes(), clientId);

        LOGGER.debug("Created access token [{}]", accessToken);
        addTicketToRegistry(accessToken, ticketGrantingTicket);
        LOGGER.debug("Added access token [{}] to registry", accessToken);

        updateOAuthCode(holder);

        val refreshToken = FunctionUtils.doIf(holder.isGenerateRefreshToken(),
            () -> generateRefreshToken(holder),
            () -> {
                LOGGER.debug("Service [{}] is not able/allowed to receive refresh tokens", holder.getService());
                return null;
            }).get();

        return Pair.of(accessToken, refreshToken);
    }
1343826
def refresh(self, refresh_token):
        
        r = requests.post(self.apiurl + "/token", params={"grant_type": "refresh_token", "client_id": self.cid,
                                                          "client_secret": self.csecret,
                                                          "refresh_token": refresh_token})

        if r.status_code != 200:
            raise ServerError

        jsd = r.json()

        return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at'])
1060888
def create_token(user, client, scope, id_token_dic=None):
    
    token = Token()
    token.user = user
    token.client = client
    token.access_token = uuid.uuid4().hex

    if id_token_dic is not None:
        token.id_token = id_token_dic

    token.refresh_token = uuid.uuid4().hex
    token.expires_at = timezone.now() + timedelta(
        seconds=settings.get('OIDC_TOKEN_EXPIRE'))
    token.scope = scope

    return token
147825
function (done) {
      // the token is random
      if (token.indexOf('.') === -1) {
        AccessToken.get(token, function (err, instance) {
          if (err) {
            return done(err)
          }

          if (!instance) {
            return done(new UnauthorizedError({
              realm: 'user',
              error: 'invalid_request',
              error_description: 'Unknown access token',
              statusCode: 401
            }))
          }

          done(null, {
            jti: instance.at,
            iss: instance.iss,
            sub: instance.uid,
            aud: instance.cid,
            iat: instance.created,
            exp: instance.created + instance.ei,
            scope: instance.scope
          })
        })

      // the token is not random
      } else {
        done()
      }
    }
705943
function createOAuthWrapper(oauthkey,
	oauthsecret, headers) {

	return new OAuthClient(
				'https://api.7digital.com/1.2/oauth/requesttoken',
				accessTokenUrl,
				oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers);
}
439171
def get_access_token(self, request, callback=None):
        ""
        raw_token = request.session.get(self.session_key, None)
        verifier = request.GET.get('oauth_verifier', None)
        if raw_token is not None and verifier is not None:
            data = {'oauth_verifier': verifier}
            callback = request.build_absolute_uri(callback or request.path)
            callback = force_text(callback)
            try:
                response = self.request('post', self.provider.access_token_url,
                                        token=raw_token, data=data, oauth_callback=callback)
                response.raise_for_status()
            except RequestException as e:
                logger.error('Unable to fetch access token: {0}'.format(e))
                return None
            else:
                return response.text
        return None
849980
def make_auth_headers():
    """"""
    if not os.path.exists(".appveyor.token"):
        raise RuntimeError(
            "Please create a file named `.appveyor.token` in the current directory. "
            "You can get the token from https://ci.appveyor.com/api-token"
        )
    with open(".appveyor.token") as f:
        token = f.read().strip()

    headers = {
        'Authorization': 'Bearer {}'.format(token),
    }
    return headers
65076
def get_token(params, access_token_opts={})
      params = params.merge(:parse => :json)
      access_token_opts = access_token_opts.merge({:header_format => "OAuth2 %s", :param_name => "access_token"})
      
      @token = super(params, access_token_opts)
    end
635659
public function generateToken()
	{
		$controller = new AjaxController();
		$controller->restrictAccess(Auth::isAdmin());
		
		$token = Functions::generateRandomToken();		
		$this->module->setSetting('MAJ_AT_FORCE_EXEC_TOKEN', $token);
		Log::addConfigurationLog($this->module->getTitle().' : New token generated.');
		
		$controller->pageHeader();
		echo $token;
	}
513011
def renew_access_token(self):
        
        auth_params = {'REFRESH_TOKEN': self.refresh_token}
        self._add_secret_hash(auth_params, 'SECRET_HASH')
        refresh_response = self.client.initiate_auth(
            ClientId=self.client_id,
            AuthFlow='REFRESH_TOKEN',
            AuthParameters=auth_params,
        )

        self._set_attributes(
            refresh_response,
            {
                'access_token': refresh_response['AuthenticationResult']['AccessToken'],
                'id_token': refresh_response['AuthenticationResult']['IdToken'],
                'token_type': refresh_response['AuthenticationResult']['TokenType']
            }
        )
1350996
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
        # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken
        
        access_token = AccessToken(rand_str(), self.access_token_lifetime)

        scope = current_scope or granted_scope
        logger.debug('creating access token for scope=%s', scope)

        authz_info = {
            'iat': int(time.time()),
            'exp': int(time.time()) + self.access_token_lifetime,
            'sub': subject_identifier,
            'client_id': auth_req['client_id'],
            'aud': [auth_req['client_id']],
            'scope': scope,
            'granted_scope': granted_scope,
            'token_type': access_token.BEARER_TOKEN_TYPE,
            self.KEY_AUTHORIZATION_REQUEST: auth_req
        }
        self.access_tokens[access_token.value] = authz_info

        logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',
                     access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])
        return access_token
674696
def get_access_token(self, code, state=None):
        '''
        
        '''
        kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
        if self._redirect_uri:
            kw['redirect_uri'] = self._redirect_uri
        if state:
            kw['state'] = state
        opener = build_opener(HTTPSHandler)
        request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))
        request.get_method = _METHOD_MAP['POST']
        request.add_header('Accept', 'application/json')
        try:
            response = opener.open(request, timeout=TIMEOUT)
            r = _parse_json(response.read())
            if 'error' in r:
                raise ApiAuthError(str(r.error))
            return str(r.access_token)
        except HTTPError as e:
            raise ApiAuthError('HTTPError when get access token')
686469
def get_access_token(client_id, client_secret):
	'''
	
	'''

	headers = {'Content-Type': 'application/x-www-form-urlencoded'}
	payload = {
		'client_id': client_id,
		'client_secret': client_secret
	}

	request = requests.post(token_url, data=payload, headers=headers)
	if request.status_code == 200:
		token = request.json()
		return token

	return {'status': request.status_code, "message": request.text}
516920
def create_refresh_token(self, access_token_value):
        # type: (str) -> str
        
        if access_token_value not in self.access_tokens:
            raise InvalidAccessToken('{} unknown'.format(access_token_value))

        if not self.refresh_token_lifetime:
            logger.debug('no refresh token issued for for access_token=%s', access_token_value)
            return None

        refresh_token = rand_str()
        authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}
        self.refresh_tokens[refresh_token] = authz_info

        logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],
                     access_token_value)
        return refresh_token