Step 1. Exchange authorization code for access token.
356512
function(req, res, next) {
    var accessTokenUrl = 'https://github.com/login/oauth/access_token';
    var params = {
      code: req.body.code,
      client_id: req.body.clientId,
      client_secret: config.GITHUB_SECRET,
      redirect_uri: req.body.redirectUri
    };

    request.get({ url: accessTokenUrl, qs: params }, function(err, response, accessToken) {
      if (err) {
        res.status(500).send(err);
        return;
      }
      req.accessToken = qs.parse(accessToken);
      next();
    });
  }
331570
public AccessToken getAccessToken(String code) {
        String url = WxEndpoint.get("url.oauth.accesstoken.get");
        String formatUrl = String.format(url, wxClient.getClientId(), wxClient.getClientSecret(), code);
        logger.debug("get access token: {}", formatUrl);
        String response = wxClient.get(formatUrl, false);
        return JsonMapper.defaultMapper().fromJson(response, AccessToken.class);
    }
636656
public AccessToken obtainAccessTokenByCode(String authorizationCode) throws InvalidCodeException, TokenExpiredException {
        AccessToken token = tp().obtainAccessTokenByAuthzCode(authorizationCode);
        return token;
    }
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)
539199
@Override
    public AzureAdAccessToken acquireAccessToken() throws Exception {
        AuthenticationResult authResult = getToken().get();
        return new AzureAdAccessToken(authResult.getAccessToken(), authResult.getExpiresOnDate());
    }
1249520
def exchange_code_for_token(self, authorization_code):
        # type: (str) -> se_leg_op.access_token.AccessToken
        
        if authorization_code not in self.authorization_codes:
            raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))

        authz_info = self.authorization_codes[authorization_code]
        if authz_info['used']:
            logger.debug('detected already used authz_code=%s', authorization_code)
            raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code))
        elif authz_info['exp'] < int(time.time()):
            logger.debug('detected expired authz_code=%s, now=%s > exp=%s ',
                         authorization_code, int(time.time()), authz_info['exp'])
            raise InvalidAuthorizationCode('{} has expired'.format(authorization_code))

        authz_info['used'] = True

        access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
                                                 authz_info['granted_scope'])

        logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value)
        return access_token
1174308
def fetch_access_token(auth_code, options)
      raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
      # Exchange the auth code for an access token
      @access_token = @oauth_client.auth_code.get_token(auth_code, options)

      # Use the scope to figure out which merchant we're managing
      scope = @access_token.params[:scope] || @access_token.params['scope']
      set_merchant_id_from_scope(scope)

      self.scoped_access_token
    end
416596
def exchange_code(code)
      return nil unless token_account
      return nil unless token_account['token_endpoint']

      response = request(
        http_method: token_account['token_method'].downcase.to_sym,
        path: token_account['token_endpoint'],
        headers: { CONTENT_TYPE => token_account['token_post_content_type'] },
        body: {
          'grant_type' => 'authorization_code',
          'code' => code,
          'client_id' => Kontena::Client::CLIENT_ID,
          'client_secret' => Kontena::Client::CLIENT_SECRET
        },
        expects: [200,201],
        auth: false
      )
      response['expires_at'] ||= in_to_at(response['expires_in'])
      response
    end
595799
function authorised(request) {
	// JWT is usually passed via an HTTP header
    let token = request.headers.authorization;
    
    // For EventSource and WebSocket, JWT is passed as a URL parameter
    if (token === undefined) {
    	let url = URL.parse(request.url, true);
    	
    	if (url.query)
    		token = url.query.jwt;
    }
    
    // ask app to validate JWT authorisation token
    return (!token || config.validateJWT(token, request.url));
}
444142
public function authenticate($authorizationCode)
    {
        $tokens = $this->client->requestTokens(
            $authorizationCode,
            $this->clientId,
            $this->clientSecret,
            $this->redirectUrl
        );

        $this->accessToken = $tokens->access_token;
        $this->refreshToken = $tokens->refresh_token;
        $this->expires = $tokens->expires_at;

        $this->client->authenticate($this->accessToken);
    }
1228684
function exchangeToken()
    {
        $this->isTokenExchanged = true;
        $token = $this->client->attainAccessToken( $this->grant );
        return $this->token = $token;
    }
1317483
public void authenticate(String authCode) {
        URL url = null;
        try {
            url = new URL(this.tokenURL);
        } catch (MalformedURLException e) {
            assert false : "An invalid token URL indicates a bug in the SDK.";
            throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e);
        }

        String urlParameters = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s",
            authCode, this.clientID, this.clientSecret);

        BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
        request.shouldAuthenticate(false);
        request.setBody(urlParameters);

        BoxJSONResponse response = (BoxJSONResponse) request.send();
        String json = response.getJSON();

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.accessToken = jsonObject.get("access_token").asString();
        this.refreshToken = jsonObject.get("refresh_token").asString();
        this.lastRefresh = System.currentTimeMillis();
        this.expires = jsonObject.get("expires_in").asLong() * 1000;
    }
544057
def request_access(self, verifier):
        
        client = OAuth1(
            client_key=self._server_cache[self.client.server].key,
            client_secret=self._server_cache[self.client.server].secret,
            resource_owner_key=self.store["oauth-request-token"],
            resource_owner_secret=self.store["oauth-request-secret"],
            verifier=verifier,
        )

        request = {"auth": client}
        response = self._requester(
            requests.post,
            "oauth/access_token",
            **request
        )

        data = parse.parse_qs(response.text)

        self.store["oauth-access-token"] = data[self.PARAM_TOKEN][0]
        self.store["oauth-access-secret"] = data[self.PARAM_TOKEN_SECRET][0]
        self._server_tokens = {}
422202
def get_access_token_from_code(
        self, code, redirect_uri, app_id, app_secret
    ):
        
        args = {
            "code": code,
            "redirect_uri": redirect_uri,
            "client_id": app_id,
            "client_secret": app_secret,
        }

        return self.request(
            "{0}/oauth/access_token".format(self.version), args
        )
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
1005862
def access_token(self):
        """"""
        access_token = self.get_auth_bearer()
        if not access_token:
            access_token = self.query_kwargs.get('access_token', '')
            if not access_token:
                access_token = self.body_kwargs.get('access_token', '')

        return access_token
590391
def request_user_auth(code, redirect_uri)
      response = http_client(MXIT_AUTH_TOKEN_URI) do |http, path|

        request = new_post_request(path, {
          "grant_type" => "authorization_code",
          "code" => code,
          "redirect_uri" => redirect_uri
        })

        http.request(request)
      end

      @auth_token = AuthToken.new(handle_response(response))
    end