Create the OAuth 2.0 assertion.

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

        Returns:
            bytes: The authorization grant assertion.
431256
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,
            'scope': _helpers.scopes_to_string(self._scopes or ())
        }

        payload.update(self._additional_claims)

        # The subject can be a user email for domain-wide delegation.
        if self._subject:
            payload.setdefault('sub', self._subject)

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

        return token
710333
function generateAccessToken(req, res, next) {
        /**
         * TODO:
         * https://github.com/jaredhanson/oauth2orize/issues/182
         * oauth2orize only offers the option to forward request information via authInfo object
         *
         * Important: only used for resetting the brute count (access to req.ip)
         */
        req.authInfo = {
            ip: req.ip,
            accessToken: authUtils.getBearerAutorizationToken(req)
        };

        return oauthServer.token()(req, res, function (err) {
            if (err && err.status === 400) {
                err = new common.errors.BadRequestError({err: err, message: err.message});
            }

            next(err);
        });
    }
1275888
def auth_create(name, token, force, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('auth:group:create', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
        'token': token,
        'force': force,
    })
814857
def access_token(self):

        '''  '''

        title = '%s.access_token' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # construct request kwargs
        request_kwargs = {
            'url': self.token_endpoint,
            'data': {
                'client_id': self.client_id,
                'client_secret': self.client_secret,
                'grant_type': 'client_credentials'
            }
        }

    # send request
        try:
            current_time = time()
            response = requests.post(**request_kwargs)
        except Exception:
            if self.requests_handler:
                request_kwargs['method'] = 'POST'
                request_object = requests.Request(**request_kwargs)
                return self.requests_handler(request_object)
            else:
                raise

        response_details = self.response_handler.handle(response)

        if response_details['json']:
            self._access_token = response_details['json']['access_token']
            expires_in = response_details['json']['expires_in']
            self.expires_at = current_time + expires_in
            
        return self._access_token
664404
def get_basic_auth_token(self):
        
        return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\
                           .get('authorization')
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);
}
684757
def get_access_token(self, verifier=None):
        
        
        if self._access_token is None:
            self._access_token, self._access_token_dict = self._get_access_token(verifier)
        return self._access_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)
681716
def auth(self, request):
        
        client = self.get_evernote_client()
        request_token = client.get_request_token(self.callback_url(request))
        # Save the request token information for later
        request.session['oauth_token'] = request_token['oauth_token']
        request.session['oauth_token_secret'] = request_token['oauth_token_secret']
        # Redirect the user to the Evernote authorization URL
        # return the URL string which will be used by redirect()
        # from the calling func
        return client.get_authorize_url(request_token)
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
291764
def access_token(self):
        
        access = AccessToken()

        # Use instantiation time of refresh token as relative timestamp for
        # access token "exp" claim.  This ensures that both a refresh and
        # access token expire relative to the same time if they are created as
        # a pair.
        access.set_exp(from_time=self.current_time)

        no_copy = self.no_copy_claims
        for claim, value in self.payload.items():
            if claim in no_copy:
                continue
            access[claim] = value

        return access
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)
1124519
def request_access_token(self, params):
        
        return self.request(self.access_token_url, method="GET", params=params)
32505
def construct_oauth_url(self):
        
        response = self._requester(requests.head, 
                                   "{0}://{1}/".format(self.protocol, self.client.server),
                                   allow_redirects=False
                                  )
        if response.is_redirect:
            server = response.headers['location']
        else:
            server = response.url

        path = "oauth/authorize?oauth_token={token}".format(
            token=self.store["oauth-request-token"]
        )
        return "{server}{path}".format(
            server=server,
            path=path
        )
249010
def create_token(self, request, **kwargs):
        

        data = {
            "content": self.get_object().id,
            "create_date": get_request_data(request)["create_date"],
            "expire_date": get_request_data(request)["expire_date"]
        }
        serializer = ObfuscatedUrlInfoSerializer(data=data)
        if not serializer.is_valid():
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST,
                content_type="application/json",
            )
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json")
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)
794676
def get_assertion(self, ticket, attributes):
        
        assertion = etree.Element('Assertion')
        assertion.set('xmlns', 'urn:oasis:names:tc:SAML:1.0:assertion')
        assertion.set('AssertionID', self.generate_id())
        assertion.set('IssueInstant', self.instant())
        assertion.set('Issuer', 'localhost')
        assertion.set('MajorVersion', '1')
        assertion.set('MinorVersion', '1')
        assertion.append(self.get_conditions(ticket.service))
        subject = self.get_subject(ticket.user.get_username())
        if attributes:
            assertion.append(self.get_attribute_statement(subject, attributes))
        assertion.append(self.get_authentication_statement(subject, ticket))

        return assertion