Attemps to obtain an access token from the oauth/access_token Twitter API.

@param request
@param response
495867
@Sensitive
    public Map<String, Object> getAccessToken(HttpServletRequest request, HttpServletResponse response, SocialLoginConfig config) {
        TwitterEndpointServices twitter = getTwitterEndpointServices();
        twitter.setConsumerKey(config.getClientId());
        twitter.setConsumerSecret(config.getClientSecret());

        Map<String, String[]> params = request.getParameterMap();

        if (isMissingParameter(params, TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN)) {
            return null;
        }

        // oauth_token provided in request MUST match the request token obtained earlier
        String token = request.getParameter(TwitterConstants.PARAM_OAUTH_TOKEN);
        String cachedRequestToken = webUtils.getAndClearCookie(request, response, TwitterConstants.COOKIE_NAME_REQUEST_TOKEN);
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "Obtained token from request: [" + token + "], matching against: [" + cachedRequestToken + "]");
        }

        if (!token.equals(cachedRequestToken)) {
            Tr.error(tc, "TWITTER_TOKEN_DOES_NOT_MATCH");
            return null;
        }

        String oauthVerifier = request.getParameter(TwitterConstants.PARAM_OAUTH_VERIFIER);

        Map<String, Object> result = twitter.obtainAccessToken(config, cachedRequestToken, oauthVerifier);
        if (result == null || result.isEmpty()) {
            Tr.error(tc, "TWITTER_ERROR_OBTAINING_ENDPOINT_RESULT", new Object[] { TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN });
            return null;
        }

        if (!isSuccessfulResult(result, TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN)) {
            return null;
        }

        // If result was successful, the result has already been verified to contain a non-empty access_token and access_token_secret
        return result;
    }
1250986
protected Token responseToToken(Map<String, String> response) {
		return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET));
	}
1235911
def _get_tokens(self, authn_response, context):
        
        if "code" in authn_response:
            # make token request
            args = {
                "code": authn_response["code"],
                "redirect_uri": self.client.registration_response['redirect_uris'][0],
            }

            token_resp = self.client.do_access_token_request(scope="openid", state=authn_response["state"],
                                                             request_args=args,
                                                             authn_method=self.client.registration_response[
                                                                 "token_endpoint_auth_method"])

            self._check_error_response(token_resp, context)
            return token_resp["access_token"], token_resp["id_token"]

        return authn_response.get("access_token"), authn_response.get("id_token")
1196938
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(TWITTER_ACTION)) {
			String verifier = request.getParameter("oauth_verifier");
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String denied = request.getParameter("denied");
			String redirectURI = SecurityUtils.getRedirectUrl(request) + (appid == null ? "" : "?appid=" + appid);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.TWITTER_PREFIX);
			if (denied != null) {
				throw new BadCredentialsException("Cancelled.");
			}

			if (verifier == null && stepOne(response, redirectURI, keys)) {
				return null;
			} else {
				userAuth = stepTwo(request, verifier, keys, app);
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
1355851
protected boolean isAuthorizationRequest(final HttpServletRequest request, final HttpServletResponse response) {
        val requestPath = request.getRequestURI();
        return doesUriMatchPattern(requestPath, OAuth20Constants.AUTHORIZE_URL);
    }
232783
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) {
		String ident = getIdentifierFromCookie(request);
		if (ident != null) {
			String key = ident.concat(parameterName);
			CsrfToken token = loadToken(request);
			if (token == null) {
				token = generateToken(null);
				if (Config.isCacheEnabled()) {
					cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC);
				} else {
					localCache.put(key, new Object[]{token, System.currentTimeMillis()});
				}
			}
			storeTokenAsCookie(token, request, response);
		}
	}
1841
public Request processAuthChallenge(Response response, Request req_msg) {
    return processAuthChallenge(response, req_msg, null, null);
  }
943014
protected static void fetchAnonymousAccessTokenAndRunRequest(final Request request) {
        fetchAnonymousAccessToken(request.getUserId(), new ResponseHandler() {
            @Override
            public void onSuccess(Response response) {
                requestAuthenticated(request);
            }

            @Override
            public void onFailure(Throwable e, Response errorResponse) {
            }
        });
    }
886380
private function get_token($request, $consumer, $token_type = 'access')
    {
        $token_field = $request instanceof Twitter_OAuthRequest
            ? $request->get_parameter('oauth_token')
            : null;

        $token = $this->data_store->lookup_token(
            $consumer, $token_type, $token_field
        );
        if (!$token) {
            throw new Twitter_OAuthException("Invalid $token_type token: $token_field");
        }
        return $token;
    }
1055000
def do_authenticated_request(method, url, options = {})
      begin
        response = case client
                   when BasicAuthClient
                     self.class.send(method, api_url(url), options.merge(:basic_auth => client.credentials))
                   when OauthClient
                     # We have to wrap the result of the access_token request into an HTTParty::Response object
                     # to keep duck typing with HTTParty
                     result = client.send(method, api_url(url), options)
                     content_type = Parser.format_from_mimetype(result.content_type)
                     parsed_response = Parser.call(result.body, content_type)

                     HTTParty::Response.new(nil, result, lambda { parsed_response })
                   else
                     raise CredentialsMissing
                   end
        check_response_codes(response)
        response.parsed_response
      rescue Timeout::Error
        raise Unavailable.new('Service Unavailable')
      end
    end
78931
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
    public Token getAuthorizationToken(final ContainerRequest request) {
        String authorizationString = request.getHeaderString("Authorization");
        if (authorizationString != null && !"".equals(authorizationString)) {
            authorizationString = authorizationString.trim();
            final String[] components = authorizationString.split("\\s");
            if (components.length != 2) {
                throw new NotAuthorizedException(authenticationType);
            }
            final String scheme = components[0];
            if (!authenticationType.equalsIgnoreCase(scheme)) {
                throw new NotAuthorizedException(authenticationType);
            }
            final String tokenString = components[1];
            return Token.fromString(tokenString);
        }
        return null;
    }
29890
private String signAndCreateAuthzHeader(String endpointUrl, Map<String, String> parameters) {

        String signature = computeSignature(requestMethod, endpointUrl, parameters);
        parameters.put(TwitterConstants.PARAM_OAUTH_SIGNATURE, signature);

        String authzHeaderString = createAuthorizationHeaderString(parameters);
        return authzHeaderString;
    }
306745
public void authenticate(HttpURLConnection httpConn, String url) {
        String authorization = null;
        if (hasAccessToken() && isOperationOauth(url)) {
            logger.debug("Using OAuth token to authenticate");
            authorization = getAccessTokenType() + " " + getAccessToken();
        } else if (hasApiKey()) {
            logger.debug("Using API Key to authenticate");
            String apiKey = getApiKey() + ":";
            authorization = "Basic " + DatatypeConverter.printBase64Binary(apiKey.getBytes()).trim();
        }
        if (authorization != null) {
            logger.debug("Authorization: " + authorization);
            httpConn.setRequestProperty("authorization", authorization);
        }
    }
1138330
protected OAuthToken getOAuthTokenFromRequest(final HttpServletRequest request) {
        val token = getOAuthConfigurationContext().getTicketRegistry().getTicket(getOAuthParameter(request), OAuthToken.class);
        if (token == null || token.isExpired()) {
            LOGGER.error("OAuth token indicated by parameter [{}] has expired or not found: [{}]", getOAuthParameter(request), token);
            if (token != null) {
                getOAuthConfigurationContext().getTicketRegistry().deleteTicket(token.getId());
            }
            return null;
        }
        return token;
    }
384021
def get_access_token(self):
        
        if self.access_token is None:
            request_token = self._get_rt_from_session()
            oauth = OAuth1(
                self.consumer_key,
                client_secret=self.consumer_secret,
                resource_owner_key=request_token['oauth_token'],
                resource_owner_secret=request_token['oauth_token_secret'])
            at_url = self.access_token_url
            # Passing along oauth_verifier is required according to:
            # http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9#
            # Though, the custom oauth_callback seems to work without it?
            oauth_verifier = get_request_param(self.request, 'oauth_verifier')
            if oauth_verifier:
                at_url = at_url + '?' + urlencode(
                    {'oauth_verifier': oauth_verifier})
            response = requests.post(url=at_url, auth=oauth)
            if response.status_code not in [200, 201]:
                raise OAuthError(
                    _('Invalid response while obtaining access token'
                      ' from "%s".') % get_token_prefix(
                          self.request_token_url))
            self.access_token = dict(parse_qsl(response.text))

            self.request.session['oauth_%s_access_token' % get_token_prefix(
                self.request_token_url)] = self.access_token
        return self.access_token
750201
def access_token(self, request_token, request_secret):
        """"""
        logging.debug("Getting access token from %s:%d",
                      self.server, self.port)
        self.access_token, self.access_secret = \
            self._token("/oauth/accessToken", request_token, request_secret)
        return self.access_token, self.access_secret
245182
protected Response doRequest(HttpRequestBase request, String authorizationToken, Class<?> successResponseClass) {

		assertValid(authorizationToken, "An authorizationToken is required for web resource call");

		CloseableHttpClient httpclient = HttpClients.createDefault();
		request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		request.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		request.setHeader("Authorization", "Token " + authorizationToken);
		
		try {
			CloseableHttpResponse clientResponse = httpclient.execute(request);
		
		    HttpEntity entity = clientResponse.getEntity();

		    InputStream inputStream = entity.getContent();

		    StringWriter writer = new StringWriter();
		    IOUtils.copy(inputStream, writer, "UTF-8");
		    String json = writer.toString();
		    
		    LOG.debug("json: " + json);
		    
			Response response = (Response) OBJECT_MAPPER.readValue(json, successResponseClass);

			LOG.debug("response.statuscode: " + response.status_code);
			
			if (!StatusCode.SUCCESS.equals(response.status_code)) {

				throw new RuntimeException(response.toString());
			}

			Header totalCount = clientResponse.getFirstHeader("X-Total-Count");
			if (totalCount != null) {
				response.totalCount = Integer.valueOf(totalCount.getValue());
			}
		    EntityUtils.consume(entity);
			clientResponse.close();
		    
			LOG.debug("Response: " + response);
		    
			return response;

		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}