Create the OAuth 2.0 assertion.

        This assertion is used during the OAuth 2.0 grant to acquire an
        ID token.

        Returns:
            bytes: The authorization grant assertion.
492093
def _make_authorization_grant_assertion(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
        expiry = now + lifetime

        payload = {
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            # The issuer must be the service account email.
            'iss': self.service_account_email,
            # The audience must be the auth token endpoint's URI
            'aud': self._token_uri,
            # The target audience specifies which service the ID token is
            # intended for.
            'target_audience': self._target_audience
        }

        payload.update(self._additional_claims)

        token = jwt.encode(self._signer, payload)

        return token
350383
def get_token(self):
        
        
        payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret}
        r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'})
		
        response = r.json()
        
        if r.status_code != 200 and not ERROR_KEY in response:
            raise GfycatClientError('Error fetching the OAUTH URL', r.status_code)
        elif ERROR_KEY in response:
            raise GfycatClientError(response[ERROR_KEY], r.status_code)
        
        self.token_type = response['token_type']
        self.access_token = response['access_token']
        self.expires_in = response['expires_in']
        self.expires_at = time.time() + self.expires_in - 5
        self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}
247297
def request_token(self):
        
        client_key = request.oauth.client_key
        realm = request.oauth.realm
        # TODO: fallback on default realm?
        callback = request.oauth.callback_uri
        request_token = generate_token(length=self.request_token_length[1])
        token_secret = generate_token(length=self.secret_length)
        self.save_request_token(client_key, request_token, callback,
            realm=realm, secret=token_secret)
        return urlencode([(u'oauth_token', request_token),
                          (u'oauth_token_secret', token_secret),
                          (u'oauth_callback_confirmed', u'true')])
262604
public Assertion newAssertion(final AuthenticationStatement authnStatement, final String issuer,
                                  final ZonedDateTime issuedAt, final String id) {
        val assertion = newSamlObject(Assertion.class);

        assertion.setID(id);
        assertion.setIssueInstant(DateTimeUtils.dateTimeOf(issuedAt));
        assertion.setIssuer(issuer);
        assertion.getAuthenticationStatements().add(authnStatement);
        return assertion;
    }
251416
def _token_request(self, grant_type, **kwargs):
        
        payload = {
            'grant_type': grant_type,
            'client_id': self._client_id,
            'client_secret': self._client_secret
        }

        payload.update(**kwargs)

        return self._realm.client.post(self.get_url('token_endpoint'),
                                       data=payload)
1106935
def create_token():
    '''
        
    '''
    username = id_generator()
    password = id_generator()
    create_couchdb_admin(username, password)
    create_token_file(username, password)

    return 'Token {} created'.format(username)
502686
def create_token(self, data, token_valid_for=180) -> str:
        
        jwt_token = jwt.encode({
            'data': data,
            'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
            self.app_secret)
        return Security.encrypt(jwt_token)
156156
def create_token(self, request, refresh_token=False, **kwargs):
        
        if "save_token" in kwargs:
            warnings.warn("`save_token` has been deprecated, it was not called internally."
                          "If you do, call `request_validator.save_token()` instead.",
                          DeprecationWarning)

        if callable(self.expires_in):
            expires_in = self.expires_in(request)
        else:
            expires_in = self.expires_in

        request.expires_in = expires_in

        token = {
            'access_token': self.token_generator(request),
            'expires_in': expires_in,
            'token_type': 'Bearer',
        }

        # If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but
        # there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so
        # all tokens issued are for the entire set of requested scopes.
        if request.scopes is not None:
            token['scope'] = ' '.join(request.scopes)

        if refresh_token:
            if (request.refresh_token and
                    not self.request_validator.rotate_refresh_token(request)):
                token['refresh_token'] = request.refresh_token
            else:
                token['refresh_token'] = self.refresh_token_generator(request)

        token.update(request.extra_credentials or {})
        return OAuth2Token(token)
302969
def RequestPacket(self):
        
        attr = self._PktEncodeAttributes()

        if self.authenticator is None:
            self.authenticator = self.CreateAuthenticator()

        if self.id is None:
            self.id = self.CreateID()

        header = struct.pack('!BBH16s', self.code, self.id,
            (20 + len(attr)), self.authenticator)

        return header + attr
204079
def _authorize_new_tokens(self):
        '''
        
        '''
        logging.info('About to request new OAuth2 tokens from Coursera.')
        # Attempt to request new tokens from Coursera via the browser.
        state_token = uuid.uuid4().hex
        authorization_url = self._build_authorizaton_url(state_token)

        sys.stdout.write(
            'Please visit the following URL to authorize this app:\n')
        sys.stdout.write('\t%s\n\n' % authorization_url)
        if _platform == 'darwin':
            # OS X -- leverage the 'open' command present on all modern macs
            sys.stdout.write(
                'Mac OS X detected; attempting to auto-open the url '
                'in your default browser...\n')
            try:
                subprocess.check_call(['open', authorization_url])
            except:
                logging.exception('Could not call `open %(url)s`.',
                                  url=authorization_url)

        if self.local_webserver_port is not None:
            # Boot up a local webserver to retrieve the response.
            server_address = ('', self.local_webserver_port)
            code_holder = CodeHolder()

            local_server = BaseHTTPServer.HTTPServer(
                server_address,
                _make_handler(state_token, code_holder))

            while not code_holder.has_code():
                local_server.handle_request()
            coursera_code = code_holder.code
        else:
            coursera_code = raw_input('Please enter the code from Coursera: ')

        form_data = {
            'code': coursera_code,
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'redirect_uri': self._redirect_uri,
            'grant_type': 'authorization_code',
        }
        return self._request_tokens_from_token_endpoint(form_data)
204846
def _verify(
        self,
        request,
        return_payload=False,
        verify=True,
        raise_missing=False,
        request_args=None,
        request_kwargs=None,
        *args,
        **kwargs
    ):
        
        try:
            token = self._get_token(request)
            is_valid = True
            reason = None
        except (
            exceptions.MissingAuthorizationCookie,
            exceptions.MissingAuthorizationQueryArg,
            exceptions.MissingAuthorizationHeader,
        ) as e:
            token = None
            is_valid = False
            reason = list(e.args)
            status = e.status_code if self.config.debug() else 401

            if raise_missing:
                if not self.config.debug():
                    e.status_code = 401
                raise e

        if token:
            try:
                payload = self._decode(token, verify=verify)

                if verify:
                    if self._extra_verifications:
                        self._verify_extras(payload)
                    if self._custom_claims:
                        self._verify_custom_claims(payload)
            except (
                jwt.exceptions.ExpiredSignatureError,
                jwt.exceptions.InvalidIssuerError,
                jwt.exceptions.ImmatureSignatureError,
                jwt.exceptions.InvalidIssuedAtError,
                jwt.exceptions.InvalidAudienceError,
                InvalidVerificationError,
                InvalidCustomClaimError,
            ) as e:
                # Make sure that the reasons all end with '.' for consistency
                reason = [
                    x if x.endswith(".") else "{}.".format(x)
                    for x in list(e.args)
                ]
                payload = None
                status = 401
                is_valid = False
            except jwt.exceptions.DecodeError as e:
                self._reasons = e.args
                # Make sure that the reasons all end with '.' for consistency
                reason = (
                    [
                        x if x.endswith(".") else "{}.".format(x)
                        for x in list(e.args)
                    ]
                    if self.config.debug()
                    else "Auth required."
                )
                logger.debug(e.args)
                is_valid = False
                payload = None
                status = 400 if self.config.debug() else 401
        else:
            payload = None

        if return_payload:
            return payload

        status = 200 if is_valid else status

        return is_valid, status, reason
676518
def create_authorization_response(self, uri, http_method='GET', body=None,
                                      headers=None, scopes=None, credentials=None):
        """"""
        request = Request(
            uri, http_method=http_method, body=body, headers=headers)
        request.scopes = scopes
        # TODO: decide whether this should be a required argument
        request.user = None     # TODO: explain this in docs
        for k, v in (credentials or {}).items():
            setattr(request, k, v)
        response_type_handler = self.response_types.get(
            request.response_type, self.default_response_type_handler)
        log.debug('Dispatching response_type %s request to %r.',
                  request.response_type, response_type_handler)
        return response_type_handler.create_authorization_response(
            request, self.default_token_type)
883908
def get_token(self):
    
    if self.__token is not None:
      return self.__token

    url = "https://api.neur.io/v1/oauth2/token"

    creds = b64encode(":".join([self.__key,self.__secret]).encode()).decode()

    headers = {
      "Authorization": " ".join(["Basic", creds]),
    }
    payload = {
      "grant_type": "client_credentials"
    }

    r = requests.post(url, data=payload, headers=headers)

    self.__token = r.json()["access_token"]

    return self.__token
162547
def create(self, ttl=values.unset):
        
        data = values.of({'Ttl': ttl, })

        payload = self._version.create(
            'POST',
            self._uri,
            data=data,
        )

        return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], )
877068
def create_request_token(self, request, credentials):
        
        token = {
            'oauth_token': self.token_generator(),
            'oauth_token_secret': self.token_generator(),
            'oauth_callback_confirmed': 'true'
        }
        token.update(credentials)
        self.request_validator.save_request_token(token, request)
        return urlencode(token.items())
450349
def create_token(credential, opts = {})
      data, _status_code, _headers = create_token_with_http_info(credential, opts)
      return data
    end
538131
def create_auth_token(sender, instance, raw, created, **kwargs):
    
    if not raw:
        if created:
            sender.objects.create(user=instance)