Open a browser to the authorization url and spool up a CherryPy
        server to accept the response
506251
def browser_authorize(self):
        
        url = self.authorize_url()
        # Open the web browser in a new thread for command-line browser support
        threading.Timer(1, webbrowser.open, args=(url,)).start()

        server_config = {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': 443,

            'server.ssl_module': 'pyopenssl',
            'server.ssl_certificate': 'tests/files/certificate.cert',
            'server.ssl_private_key': 'tests/files/key.key',
        }

        cherrypy.config.update(server_config)
        cherrypy.quickstart(self)
18709
def _request(self, *args, **kwargs):
        """"""
        if not self.token:
            self._obtain_token()

        headers = {
            "Authorization": "Bearer {}".format(self.token)
        }

        # add authorization headers
        if "headers" in kwargs:
            kwargs["headers"].update(headers)
        else:
            kwargs["headers"] = headers

        # add api site to url
        args = list(args)
        if not args[1].startswith("http"):
            args[1] = "{}{}".format(API_URL, args[1])

        has_no_token = kwargs.get("no_token")
        if has_no_token:
            del kwargs["no_token"]
        resp = requests.request(*args, **kwargs)
        if resp.status_code == 401 and not has_no_token:
            self._obtain_token()
            kwargs["no_token"] = True
            self._request(*args, **kwargs)
        return resp
198626
def main():
    """"""
    if len(sys.argv) < 2:
        print("Usage: {} SCOPE...".format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_refresh_token_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
        os.environ["PRAWCORE_REDIRECT_URI"],
    )

    state = str(random.randint(0, 65000))
    url = authenticator.authorize_url("permanent", sys.argv[1:], state)
    print(url)

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value
        for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            "State mismatch. Expected: {} Received: {}".format(
                state, params["state"]
            ),
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    authorizer = prawcore.Authorizer(authenticator)
    authorizer.authorize(params["code"])

    send_message(client, "Refresh token: {}".format(authorizer.refresh_token))
    return 0
643200
def lambda_handler(event, context):
    # incoming token value
    token = event['authorizationToken']
    print("Method ARN: " + event['methodArn'])

    '''
    
    '''
    principalId = 'user|a1b2c3d4'

    '''
    You can send a 401 Unauthorized response to the client by failing like so:

      raise Exception('Unauthorized')

    If the token is valid, a policy must be generated which will allow or deny
    access to the client. If access is denied, the client will receive a 403
    Access Denied response. If access is allowed, API Gateway will proceed with
    the backend integration configured on the method that was called.

    This function must generate a policy that is associated with the recognized
    principal user identifier. Depending on your use case, you might store
    policies in a DB, or generate them on the fly.

    Keep in mind, the policy is cached for 5 minutes by default (TTL is
    configurable in the authorizer) and will apply to subsequent calls to any
    method/resource in the RestApi made with the same token.

    The example policy below denies access to all resources in the RestApi.
    '''
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]

    policy = AuthPolicy(principalId, awsAccountId)
    policy.restApiId = apiGatewayArnTmp[0]
    policy.region = tmp[3]
    policy.stage = apiGatewayArnTmp[1]
    policy.denyAllMethods()
    #policy.allowMethod(HttpVerb.GET, '/pets/*')

    # Finally, build the policy
    authResponse = policy.build()

    # new! -- add additional key-value pairs associated with the authenticated principal
    # these are made available by APIGW like so: $context.authorizer.<key>
    # additional context is cached
    context = {
        'key': 'value',  # $context.authorizer.key -> value
        'number': 1,
        'bool': True
    }
    # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it
    # context['obj'] = {'foo':'bar'} <- also invalid

    authResponse['context'] = context

    return authResponse
990838
def authorize(client_key, client_secret, credfile=CONFIG_FILE, app='trlo.py',
              expiration='never', scope='read,write'):
    
    # 1. Obtain the request token.
    oauth = OAuth1Session(client_key, client_secret=client_secret)
    request_token = oauth.fetch_request_token(OAUTH_REQUEST_TOKEN_URL)

    # 2. Authorize the user (in the browser).
    authorization_url = oauth.authorization_url(OAUTH_BASE_AUTHORIZE_URL,
        name=app, expiration=expiration, scope=scope)
    print("Please visit the following URL to authorize this app:")
    print(authorization_url)
    print('')
    print("Once you've authorized, copy and paste the token Trello gives you below.")
    # Py3K backwards-compatibility shim
    global input
    try:
        input = raw_input
    except NameError:
        pass
    verifier = input("Trello's token: ").strip()

    # 3. Obtain the access token
    oauth = OAuth1Session(client_key, client_secret=client_secret,
        resource_owner_key=request_token['oauth_token'],
        resource_owner_secret=request_token['oauth_token_secret'],
        verifier=verifier)
    access_token = oauth.fetch_access_token(OAUTH_ACCESS_TOKEN_URL)

    # Save all our creds to ~/.trlo so we can get at 'em later.
    # The names are specially chosen so we can do OAuth1Session(**creds)
    creds = {
        'client_key': client_key,
        'client_secret': client_secret,
        'resource_owner_key': access_token['oauth_token'],
        'resource_owner_secret': access_token['oauth_token_secret'],
    }
    with open(credfile, 'w') as fp:
        json.dump(creds, fp)
398708
def u2open(self, u2request):
        
        tm = self.options.timeout
        url = build_opener(HTTPSClientAuthHandler(self.context))
        if self.u2ver() < 2.6:
            socket.setdefaulttimeout(tm)
            return url.open(u2request)
        else:
            return url.open(u2request, timeout=tm)
870335
def authorize_url(self, scope='', **kwargs):
        
        self._check_configuration("site", "authorization_url", "redirect_uri",
                                  "client_id")
        if isinstance(scope, (list, tuple, set, frozenset)):
            self._check_configuration("scope_sep")
            scope = self.scope_sep.join(scope)
        oauth_params = {
            'redirect_uri': self.redirect_uri,
            'client_id': self.client_id,
            'scope': scope,
        }
        oauth_params.update(kwargs)
        return "%s%s?%s" % (self.site, quote(self.authorization_url),
                            urlencode(oauth_params))
840675
def authorize():
    
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    url = auth.get_authorization_url()
    print('Open this url on your webbrowser: {0}'.format(url))
    webbrowser.open(url)
    pin = input('Input verification number here: ').strip()

    token_key, token_secret = auth.get_access_token(verifier=pin)

    return OAuthToken(token_key, token_secret)
368958
def process(self, request, response, environ):
        
        try:
            data = self.site_adapter.authenticate(request, environ,
                                                  self.scope_handler.scopes,
                                                  self.client)
            data = AuthorizeMixin.sanitize_return_value(data)
        except UserNotAuthenticated:
            raise OAuthInvalidError(error="invalid_client",
                                    explanation=self.OWNER_NOT_AUTHENTICATED)

        if isinstance(data, Response):
            return data

        token_data = self.create_token(
            client_id=self.client.identifier,
            data=data[0],
            grant_type=ResourceOwnerGrant.grant_type,
            scopes=self.scope_handler.scopes,
            user_id=data[1])

        if self.scope_handler.send_back:
            token_data["scope"] = encode_scopes(self.scope_handler.scopes)

        json_success_response(data=token_data, response=response)

        return response
962034
def authorize_url(self, state=None):
        '''
        
        '''
        if not self._client_id:
            raise ApiAuthError('No client id.')
        kw = dict(client_id=self._client_id)
        if self._redirect_uri:
            kw['redirect_uri'] = self._redirect_uri
        if self._scope:
            kw['scope'] = self._scope
        if state:
            kw['state'] = state
        return 'https://github.com/login/oauth/authorize?%s' % _encode_params(kw)
157406
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}
281207
def resp2flask(resp):
    """"""
    if isinstance(resp, Redirect) or isinstance(resp, SeeOther):
        code = int(resp.status.split()[0])
        raise cherrypy.HTTPRedirect(resp.message, code)
    return resp.message, resp.status, resp.headers
659125
def get_req(url):
    """"""
    request = urllib.request.Request(url)
    request.add_header('Authorization', 'token %s' % API_TOKEN)
    try:
        response = urllib.request.urlopen(request).read().decode('utf-8')
        return response
    except urllib.error.HTTPError:
        exception()
        sys.exit(0)
718406
def get_token(self, url):
        
        # A hack to avoid url-encoding the url, since the authorization service
        # doesn't work with correctly encoded urls

        parsed_url = urlparse.urlsplit(url)
        parsed_url = parsed_url._replace(path='/authorization/api')
        self.url = urlparse.urlunsplit(parsed_url)

        response = self.request(method='GET', url='/v1/token?url=' + url)
        return response.result.text
1203033
def auth(
        cls, consumer_key, redirect_uri='http://example.com/', state=None,
    ):
        '''
        

        '''
        code = cls.get_request_token(consumer_key, redirect_uri, state)

        auth_url = 'https://getpocket.com/auth/authorize?request_token='\
            '%s&redirect_uri=%s' % (code, redirect_uri)
        raw_input(
            'Please open %s in your browser to authorize the app and '
            'press enter:' % auth_url
        )

        return cls.get_access_token(consumer_key, code)
1021366
def validate_authorization_request(self, uri, http_method='GET', body=None,
                                       headers=None):
        """"""
        request = Request(
            uri, http_method=http_method, body=body, headers=headers)

        request.scopes = utils.scope_to_list(request.scope)

        response_type_handler = self.response_types.get(
            request.response_type, self.default_response_type_handler)
        return response_type_handler.validate_authorization_request(request)
1350943
def start_response_callback(start_response, origin):
        """"""
        def callback(status, headers, exc_info=None):
            """Add our headers to response using a closure."""
            headers.append(('Access-Control-Allow-Origin', origin))
            # Call upstream start_response
            start_response(status, headers, exc_info)
        return callback