Related documentation: https://dev.fitbit.com/build/reference/web-api/oauth2/
511419
@Override
    public void generateError(String response) {
        final String errorInString = extractParameter(response, ERROR_REGEX_PATTERN, true);
        final String errorDescription = extractParameter(response, ERROR_DESCRIPTION_REGEX_PATTERN, false);

        OAuth2Error errorCode;
        try {
            errorCode = OAuth2Error.parseFrom(errorInString);
        } catch (IllegalArgumentException iaE) {
            //non oauth standard error code
            errorCode = null;
        }

        throw new OAuth2AccessTokenErrorResponse(errorCode, errorDescription, null, response);
    }
1239485
def api_walk(uri, per_page=100, key="login"):
    
    page = 1
    result = []

    while True:
        response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page))
        if len(response) == 0:
            break
        else:
            page += 1
            for r in response:
                if key == USER_LOGIN:
                    result.append(user_login(r))
                else:
                    result.append(r[key])

    return list(set(result))
269345
function () {
      if (this.auth_url) {
        return this.auth_url;
      }
      var self = this,
        destination = {
          protocol: 'https',
          host: 'www.box.com',
          pathname: '/api/oauth2/authorize',
          search: querystring.stringify({
            response_type: 'code',
            client_id: self.client_id,
            state: self.csrf,
            redirect_uri: 'http://' + self.host + ':' + self.port + '/authorize?id=' + self.email
          })
        };

      self.auth_url = url.format(destination);
      return self.auth_url;
    }
962613
def require_api_auth(allow_anonymous=False):
    
    def wrapper(f):
        """Wrap function with oauth require decorator."""
        f_oauth_required = oauth2.require_oauth()(f)

        @wraps(f)
        def decorated(*args, **kwargs):
            """Require OAuth 2.0 Authentication."""
            if not hasattr(current_user, 'login_via_oauth2'):
                if not current_user.is_authenticated:
                    if allow_anonymous:
                        return f(*args, **kwargs)
                    abort(401)
                if current_app.config['ACCOUNTS_JWT_ENABLE']:
                    # Verify the token
                    current_oauth2server.jwt_veryfication_factory(
                        request.headers)
                # fully logged in with normal session
                return f(*args, **kwargs)
            else:
                # otherwise, try oauth2
                return f_oauth_required(*args, **kwargs)
        return decorated
    return wrapper
610807
def get_pr_checks(pr: PullRequestDetails) -> Dict[str, Any]:
    
    url = ("https://api.github.com/repos/{}/{}/commits/{}/check-runs"
           "?access_token={}".format(pr.repo.organization,
                                     pr.repo.name,
                                     pr.branch_sha,
                                     pr.repo.access_token))
    response = requests.get(
        url,
        headers={'Accept': 'application/vnd.github.antiope-preview+json'})

    if response.status_code != 200:
        raise RuntimeError(
            'Get check-runs failed. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())
1320326
def auth_by_user(operator_id, user_name, password, endpoint)
      endpoint = API_BASE_URL if endpoint.nil?
      res = RestClient.post endpoint + '/auth',
                            { operatorId: operator_id, userName: user_name, password: password },
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json'
      result = JSON.parse(res.body)
      fail result['message'] if res.code != '200'
      Hash[JSON.parse(res.body).map { |k, v| [k.to_sym, v] }]
    end
1293928
def __get_oauth_url(self, url, method, **kwargs):
        
        oauth = OAuth(
            url=url,
            consumer_key=self.consumer_key,
            consumer_secret=self.consumer_secret,
            version=self.version,
            method=method,
            oauth_timestamp=kwargs.get("oauth_timestamp", int(time()))
        )

        return oauth.get_oauth_url()
106816
function() {
            auth.type = 'basic';

            auth.username = process.env.GHusername || octofish.config.auth.username || null;
            auth.password = process.env.GHpassword || octofish.config.auth.password || null;

            if ( !auth.password || !auth.username ) {
                return false;
            } else {
                octofish.github.authenticate( auth );
                return true;
            }
        }
829460
def oauthgetm(method, param_dict, socket_timeout=None):
    try:
        import oauth2 # lazy import this so oauth2 is not a hard dep
    except ImportError:
        raise Exception("You must install the python-oauth2 library to use this method.")

    
    def build_request(url):
        params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_timestamp': int(time.time())
            }
        consumer = oauth2.Consumer(key=config.ECHO_NEST_CONSUMER_KEY, secret=config.ECHO_NEST_SHARED_SECRET)
        params['oauth_consumer_key'] = config.ECHO_NEST_CONSUMER_KEY
        
        req = oauth2.Request(method='GET', url=url, parameters=params)
        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, None)
        return req
    
    param_dict['api_key'] = config.ECHO_NEST_API_KEY
    param_list = []
    if not socket_timeout:
        socket_timeout = config.CALL_TIMEOUT
    
    for key,val in param_dict.iteritems():
        if isinstance(val, list):
            param_list.extend( [(key,subval) for subval in val] )
        elif val is not None:
            if isinstance(val, unicode):
                val = val.encode('utf-8')
            param_list.append( (key,val) )

    params = urllib.urlencode(param_list)
    
    orig_timeout = socket.getdefaulttimeout()
    socket.setdefaulttimeout(socket_timeout)
    """
    just a normal GET call
    """
    url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION, 
                                     method, params)
    req = build_request(url)
    f = opener.open(req.to_url())
            
    socket.setdefaulttimeout(orig_timeout)
    
    # try/except
    response_dict = get_successful_response(f)
    return response_dict
947954
def sig2(method, endpoint, params, provider, aws_api_version):
    '''
    
    '''
    timenow = datetime.utcnow()
    timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ')

    # Retrieve access credentials from meta-data, or use provided
    access_key_id, secret_access_key, token = creds(provider)

    params_with_headers = params.copy()
    params_with_headers['AWSAccessKeyId'] = access_key_id
    params_with_headers['SignatureVersion'] = '2'
    params_with_headers['SignatureMethod'] = 'HmacSHA256'
    params_with_headers['Timestamp'] = '{0}'.format(timestamp)
    params_with_headers['Version'] = aws_api_version
    keys = sorted(params_with_headers.keys())
    values = list(list(map(params_with_headers.get, keys)))
    querystring = urlencode(list(zip(keys, values)))

    canonical = '{0}\n{1}\n/\n{2}'.format(
        method.encode('utf-8'),
        endpoint.encode('utf-8'),
        querystring.encode('utf-8'),
    )

    hashed = hmac.new(secret_access_key, canonical, hashlib.sha256)
    sig = binascii.b2a_base64(hashed.digest())
    params_with_headers['Signature'] = sig.strip()

    # Add in security token if we have one
    if token != '':
        params_with_headers['SecurityToken'] = token

    return params_with_headers
882062
function requireAuthCycle(sources) {
  const cookieToken$ = sources.ACTION.filter(
    action => action.type === REQUIRE_AUTH,
  ).map(cookieHelper.getCookieToken);

  const request$ = cookieToken$.map(cookieToken => ({
    url: '/oauth/cookies',
    method: 'POST',
    send: { token: cookieToken },
    category: REQUIRE_AUTH,
  }));

  const successRes$ = sources.HTTP.select(REQUIRE_AUTH).switchMap(success);

  const action$ = Observable.from([
    successRes$.pluck('body', 'results').map(setUserInfo),
    successRes$.mapTo(serviceActions.fetchIpList()),
    successRes$.mapTo(systemActions.fetchSystemByType('db')),
  ]).mergeAll();

  return {
    ACTION: action$,
    HTTP: request$,
  };
}
1144421
def callback_oauth2(self, request):
        
        callback_url = self.callback_url(request)

        oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)
        request_token = oauth.fetch_token(self.REQ_TOKEN,
                                          code=request.GET.get('code', ''),
                                          authorization_response=callback_url,
                                          client_secret=self.consumer_secret,
                                          scope=self.scope,
                                          verify=False)
        return request_token.get('access_token')
10543
def oauth2(self):
        
        if self._url.endswith("/oauth2"):
            url = self._url
        else:
            url = self._url + "/oauth2"
        return _oauth2.oauth2(oauth_url=url,
                              securityHandler=self._securityHandler,
                              proxy_url=self._proxy_url,
                              proxy_port=self._proxy_port)
286258
function Login(callback)
	{
		Log("Making OAuth Request...");
		// start OAuth request (use our internal GET function as this is different!)
		_URLGET(
			// URL
			urls.login_base + "/2.0/oauth/authorize",
			// query string
			GetOAuthData({
				response_type: "code",
				service_entity: "urn:service-entity:psn",
				returnAuthCode: true,
				state: "1156936032"
			}),
			// headers
			{
				'User-Agent': ParseStaches(useragent)
			},
			function(err, body, response)
			{
				if (err)
				{
					// return login error
					if (callback) callback(err);
					return;
				}
				else
				{
					// get the login path
					var login_referrer = response.req.path;

					Log("Logging in...");

					// now actually login using the previous URL as the referrer
					request(
						{
							url: urls.login_base + "/login.do",
							method: "POST",
				            headers:
				            {
				            	'User-Agent': ParseStaches(useragent),
				            	'X-Requested-With': headers["X-Requested-With"],
				                'Origin': 'https://auth.api.sonyentertainmentnetwork.com',
				                'Referer': login_referrer,
				            },
				            form:
				            {
				                'params': new Buffer(login_params).toString('base64'),
				                'j_username': login_details.email,
				                'j_password': login_details.password
				            }
			        	},
				        function (err, response, body)
				        {
				        	if (err)
				        	{
				        		// login failed
				        		Log("Failed to make login request");
				        		if (callback) callback(err);
				        		return;
				        	}
				        	else
				        	{
					        	Log("Following login...");
					        	
					            request.get(response.headers.location, function (err, response, body)
					            {
					                if (!err)
					                {
					                	// parse URL
					                	var result = url.parse(response.req.path, true);
					                	if (result.query.authentication_error)
					                	{
					                		// try to extract login error from website
					                		var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body);
					                		if (error_message && error_message[1])
					                		{
					                			Log("Login failed! Error from Sony: " + error_message[1]);
					                			if (callback) callback(error_message[1]);
					                		}
					                		else
					                		{
												Log("Login failed!");
								        		if (callback) callback("Login failed!");
								        	}

							        		return;
					                	}
					                	else
					                	{
					                		// no auth error!
					                		var auth_result = url.parse(result.query.targetUrl, true);
					                		if (auth_result.query.authCode)
					                		{
					                			Log("Got auth code: " + auth_result.query.authCode);
					                			auth_obj.auth_code = auth_result.query.authCode;
					                			if (callback) callback(false);
					                			return;
					                		}
					                		else
					                		{
					                			Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
								        		if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
								        		return;
					                		}
					                	}
					                }
					                else
					                {
					                    Log("Auth code fetch error: " + err);
					                    if (callback) callback(err);
					                    return;
					                }
					            });
					        }
				        }
				    );
				}
			}
		);
	}
233731
public function oauth2callback() {
		if (array_key_exists('code', $_GET) && !empty($_GET['code'])) {
			$code = $_GET['code'];
			$url = 'https://github.com/login/oauth/access_token';
			
			$params = array(
				'code' => $code,
				'client_id' => $this->strategy['client_id'],
				'client_secret' => $this->strategy['client_secret'],
				'redirect_uri' => $this->strategy['redirect_uri'],
			);
			if (!empty($this->strategy['state'])) $params['state'] = $this->strategy['state'];
			
			$response = $this->serverPost($url, $params, null, $headers);
			parse_str($response, $results);
			
			if (!empty($results) && !empty($results['access_token'])) {
				$user = $this->user($results['access_token']);
				
				$this->auth = array(
					'uid' => $user['id'],
					'info' => array(),
					'credentials' => array(
						'token' => $results['access_token']
					),
					'raw' => $user
				);
				
				$this->mapProfile($user, 'name', 'info.name');
				$this->mapProfile($user, 'blog', 'info.urls.blog');
				$this->mapProfile($user, 'avatar_url', 'info.image');
				$this->mapProfile($user, 'bio', 'info.description');
				$this->mapProfile($user, 'login', 'info.nickname');
				$this->mapProfile($user, 'html_url', 'info.urls.github');
				$this->mapProfile($user, 'email', 'info.email');
				$this->mapProfile($user, 'location', 'info.location');
				$this->mapProfile($user, 'url', 'info.urls.github_api');
				
				$this->callback();
			}
			else {
				$error = array(
					'code' => 'access_token_error',
					'message' => 'Failed when attempting to obtain access token',
					'raw' => array(
						'response' => $response,
						'headers' => $headers
					)
				);

				$this->errorCallback($error);
			}
		}
		else {
			$error = array(
				'code' => 'oauth2callback_error',
				'raw' => $_GET
			);
			
			$this->errorCallback($error);
		}
	}
512599
function fetchRepoREADME (repo) {
  request({
    uri: 'https://api.github.com/repos/' + repo + '/readme',
    headers: _.extend(headers, {

      // Get raw README content
      'Accept': 'application/vnd.github.VERSION.raw'
    })
  },
  function (error, response, body) {
    if (!error && response.statusCode === 200) {
      lintMarkdown(body, repo);
    } else {
      if (response.headers['x-ratelimit-remaining'] === '0') {
        getAuthToken();
      } else {
        console.log('README for https://github.com/' + repo.blue + ' not found.'.red);
        return;
      }
    }
  });
}
625593
function oauth(httpRequest, httpResponse){
        var code = httpRequest.query.code,
            redirectUrl = _.has(grasshopper.config.identities, 'google') ? grasshopper.config.identities.google.redirectUrl : 'defaultRoute';


        grasshopper.auth('Google', { code: code })
            .then(function(token) {

                httpRequest.session.token = new Buffer(token).toString('base64');
                httpRequest.session.save(function() {
                    httpResponse.redirect(redirectUrl+'/'+ httpRequest.session.token);
                });


            })
            .fail(function(err){
                httpResponse.redirect(redirectUrl+'/error='+ err.message);
            });
    }