org.scribe.model.Token Java Examples

The following examples show how to use org.scribe.model.Token. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResourceClient.java    From jerseyoauth2 with MIT License 7 votes vote down vote up
public SampleEntity retrieveEntitySample1(Token accessToken) throws ClientException
{
	OAuthService service = getOAuthService(scopes, null);
	
	OAuthRequest request = new OAuthRequest(Verb.GET,
			"http://localhost:9998/testsuite/rest/sample/1");
	service.signRequest(accessToken, request);
	Response response = request.send();
	if (response.getCode()!=200)
		throwClientException(response);
	
	ObjectMapper mapper = new ObjectMapper();
	try {
		SampleEntity entity = mapper.readValue(response.getBody(), SampleEntity.class);
		return entity;
	} catch (IOException e) {
		throw new ClientException(response.getBody());
	}
}
 
Example #2
Source File: ResourceTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testValidResourceAccess() throws ClientException
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity);
	Token tok = client.getAccessToken(code);
	assertNotNull(tok);
	assertNotNull(tok.getToken());
	
	client.sendTestRequestSample1(tok);
	
	SampleEntity entity = client.retrieveEntitySample1(tok);
	assertNotNull(entity);
	assertEquals("manager", entity.getUsername());
	assertEquals(clientEntity.getClientId(), entity.getClientApp());
}
 
Example #3
Source File: LoginActivity.java    From open with GNU General Public License v3.0 6 votes vote down vote up
public void loginRoutine() {
    (new AsyncTask<Void, Void, Token>() {
        @Override
        protected Token doInBackground(Void... params) {
            try {
                setRequestToken(app.getOsmOauthService().getRequestToken());
                return requestToken;
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(Token url) {
            if (url != null) {
                openLoginPage(url);
            } else {
                unableToLogInAction();
            }
        }
    }).execute();
}
 
Example #4
Source File: FacebookAuthController.java    From mamute with Apache License 2.0 6 votes vote down vote up
@Get("/sign-up/facebook/")
public void signupViaFacebook(String code, String state) {
	if (code == null) {
		includeAsList("mamuteMessages", i18n("error", "error.signup.facebook.unknown"));
		redirectTo(SignupController.class).signupForm();
		return;
	}
	
	Token token = service.getAccessToken(null, new Verifier(code));
	
	SocialAPI facebookAPI = new FacebookAPI(service, token);
	
	boolean success = loginManager.merge(MethodType.FACEBOOK, facebookAPI);
	if(!success) {
		includeAsList("mamuteMessages", i18n("error", "signup.errors.facebook.invalid_email", state));
		result.redirectTo(AuthController.class).loginForm(state);
		return;
	}
	redirectToRightUrl(state);
}
 
Example #5
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 6 votes vote down vote up
private Token parseXAuthResponse(final Response response) {
    String responseStr = response.getBody();
    if (responseStr != null) {
        // Response is received in the format "oauth_token=value&oauth_token_secret=value".
        String extractedToken = null, extractedSecret = null;
        final String[] values = responseStr.split("&");
        for (String value : values) {
            final String[] kvp = value.split("=");
            if (kvp != null && kvp.length == 2) {
                if (kvp[0].equals("oauth_token")) {
                    extractedToken = kvp[1];
                } else if (kvp[0].equals("oauth_token_secret")) {
                    extractedSecret = kvp[1];
                }
            }
        }
        if (extractedToken != null && extractedSecret != null) {
            return new Token(extractedToken, extractedSecret);
        }
    }
    // No good
    throw new JumblrException(response);
}
 
Example #6
Source File: OAuth20TokenExtractorImpl.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Token extract(String response) {
	ObjectMapper mapper = new ObjectMapper();
	try {
		Map tokenMap = mapper.readValue(response, Map.class);
		if (!tokenMap.containsKey("access_token")) {
			throw new TokenExtractorException(response);
		}
		
		String accessToken = (String)tokenMap.get("access_token");
		String refreshToken = (String)tokenMap.get("refresh_token");
		String expiration = null;
		if (tokenMap.containsKey("expires_in"))
		{
			expiration = ((Integer)tokenMap.get("expires_in")).toString();
		}
		
		return new OAuth2Token(accessToken, refreshToken, expiration, response);
	} catch (IOException e) {
		throw new TokenExtractorException(response, e);
	}
}
 
Example #7
Source File: DataUploadServiceTest.java    From open with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldGenerateGPX_shouldSubmit() throws Exception {
    Token token = new Token("stuff", "fun");
    app.setAccessToken(token);

    String expectedGroupId = "test_route";
    String expectedRouteDescription = "does not matter";
    fillLocationsTable(expectedGroupId, 10, true);
    DataUploadService spy = spy(service);
    spy.onStartCommand(null, 0, 0);
    verify(spy).generateGpxXmlFor(expectedGroupId, expectedRouteDescription);
    verify(spy).getDocument(expectedGroupId);
    verify(spy).submitCompressedFile(any(ByteArrayOutputStream.class),
            eq(expectedGroupId),
            eq(expectedRouteDescription));
}
 
Example #8
Source File: ProtocolTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testRefreshTokenFlowExpires() throws ClientException, InterruptedException
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity);
	Token oldToken = client.getAccessToken(code);
	assertNotNull(oldToken);
	assertNotNull(oldToken.getToken());
	
	client.sendTestRequestSample1(oldToken);
	
	Thread.sleep(7000);
	
	try {
		client.refreshToken((OAuth2Token)oldToken);
		fail();
	} catch (TokenExtractorException e1) {
	}
}
 
Example #9
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public Response connect(final String authorizationCode) throws OAuthException, MalformedURLException,
        URISyntaxException {
    OAuthService service = new ServiceBuilder().provider(SliApi.class).apiKey(config.getApiKey())
            .apiSecret(config.getApiSecret()).callback(config.getCallback()).build();
    Verifier verifier = new Verifier(authorizationCode);
    SliApi.TokenResponse r = ((SliApi.SLIOauth20ServiceImpl) service).getAccessToken(
            new Token(config.getApiSecret(), authorizationCode), verifier, null);

    if (r != null && r.getToken() != null) {
        accessToken = r.getToken();
        sessionToken = accessToken.getToken();
    }

    ResponseBuilder builder = Response.status(r.getOauthResponse().getCode());
    for (Map.Entry<String, String> entry : r.getOauthResponse().getHeaders().entrySet()) {
        if (entry.getKey() == null) {
            builder.header("Status", entry.getValue());
        } else {
            builder.header(entry.getKey(), entry.getValue());
        }
    }
    builder.entity(r.getOauthResponse().getBody());

    return builder.build();
}
 
Example #10
Source File: SliApi.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public TokenResponse getAccessToken(Token requestToken, Verifier verifier, Token t) {
    TokenResponse tokenResponse = new TokenResponse();

    OAuthRequest request = new OAuthRequest(myApi.getAccessTokenVerb(), myApi.getAccessTokenEndpoint());
    request.addQuerystringParameter(OAuthConstants.CLIENT_ID, myConfig.getApiKey());
    request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, myConfig.getApiSecret());
    request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
    request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, myConfig.getCallback());
    if (myConfig.hasScope()) {
        request.addQuerystringParameter(OAuthConstants.SCOPE, myConfig.getScope());
    }

    Response response = request.send();

    tokenResponse.oauthResponse = response;
    tokenResponse.token = myApi.getAccessTokenExtractor().extract(response.getBody());
    return tokenResponse;
}
 
Example #11
Source File: HubicSwift.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
public static SwiftAccess getSwiftAccess ()
{
   	final HasAuthenticationSettings authSettings = Configuration.INSTANCE.getAuthenticationSettings() ;
	String apiKey = authSettings.getClientId() ;
	String apiSecret = authSettings.getClientSecret() ;

	HubicOAuth20ServiceImpl service = (HubicOAuth20ServiceImpl) new ServiceBuilder()
			.provider(HubicApi.class).apiKey(apiKey).apiSecret(apiSecret)
			//.scope("account.r,links.rw,usage.r,credentials.r").callback(HubicApi.CALLBACK_URL)
			.scope(scope).callback(HubicApi.CALLBACK_URL)
			.build();
	
	Verifier verif = service.obtainVerifier();
	
	if (verif == null)
		return null ;
	
	Token accessToken = service.getAccessToken(null, verif);
	return getSwiftAccess (service, accessToken) ;
}
 
Example #12
Source File: Google2Api.java    From jpa-invoicer with The Unlicense 6 votes vote down vote up
@Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
    switch (api.getAccessTokenVerb()) {
    case POST:
        request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
        request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
        request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
        request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
        request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
        break;
    case GET:
    default:
        request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
        request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
        request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
        request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
        if(config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
    }
    Response response = request.send();
    return api.getAccessTokenExtractor().extract(response.getBody());
}
 
Example #13
Source File: HubicOAuth20ServiceImpl.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
public Token refreshAccessToken (Token expiredToken)
{
	if (expiredToken == null)
		return null ;
	
	OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
	
	String authenticationCode = config.getApiKey() + ":" + config.getApiSecret() ;
	byte[] bytesEncodedAuthenticationCode = Base64.encodeBase64(authenticationCode.getBytes()); 
	request.addHeader ("Authorization", "Basic " + bytesEncodedAuthenticationCode) ;
	
	String charset = "UTF-8";
	
	request.setCharset(charset);
	request.setFollowRedirects(false);
	
	AccessToken at = new HubicTokenExtractorImpl ().getAccessToken(expiredToken.getRawResponse()) ;
	
	try
	{
		request.addBodyParameter("refresh_token", at.getRefreshToken());
		//request.addBodyParameter("refresh_token", URLEncoder.encode(at.getRefreshToken(), charset));
		request.addBodyParameter("grant_type", "refresh_token");
		request.addBodyParameter(OAuthConstants.CLIENT_ID, URLEncoder.encode(config.getApiKey(), charset));
		request.addBodyParameter(OAuthConstants.CLIENT_SECRET, URLEncoder.encode(config.getApiSecret(), charset));
	} 
	catch (UnsupportedEncodingException e) 
	{			
		logger.error("Error occurred while refreshing the access token", e);
	}
	
	Response response = request.send();
	Token newToken = api.getAccessTokenExtractor().extract(response.getBody());		
	// We need to keep the initial RowResponse because it contains the refresh token
	return new Token (newToken.getToken(), newToken.getSecret(), expiredToken.getRawResponse()) ;
}
 
Example #14
Source File: ResourceTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testTokenExpiration() throws ClientException, InterruptedException
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity);
	Token tok = client.getAccessToken(code);
	assertNotNull(tok);
	assertNotNull(tok.getToken());
	
	client.sendTestRequestSample1(tok);
	
	Thread.sleep(7000);
	
	try {
		client.sendTestRequestSample1(tok);
		fail();
	} catch (ClientException e) {
	}
}
 
Example #15
Source File: HubicSwift.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
private static SwiftAccess getSwiftAccess (HubicOAuth20ServiceImpl service, Token accessToken)
{
	String urlCredential = HubicApi.CREDENTIALS_URL;
	
    OAuthRequest request = new OAuthRequest(Verb.GET, urlCredential);
    request.setConnectionKeepAlive(false);
    service.signRequest(accessToken, request);
    Response responseReq = request.send();
    
    SwiftAccess ret = gson.fromJson(responseReq.getBody(), SwiftAccess.class) ;
    ret.setAccessToken(accessToken);
    
    logger.info("Swift access token expiry date: " + ret.getExpires());
    
	return ret ;
}
 
Example #16
Source File: EvernoteOAuthActivity.java    From EverMemo with MIT License 5 votes vote down vote up
@Override
protected String doInBackground(Void... params) {
	String url = null;
	try {

		EvernoteSession session = EvernoteSession.getOpenSession();
		if (session != null) {
			// Network request
			BootstrapManager.BootstrapInfoWrapper infoWrapper = session
					.getBootstrapSession().getBootstrapInfo();

			if (infoWrapper != null) {
				BootstrapInfo info = infoWrapper.getBootstrapInfo();
				if (info != null) {
					mBootstrapProfiles = (ArrayList<BootstrapProfile>) info
							.getProfiles();
					if (mBootstrapProfiles != null
							&& mBootstrapProfiles.size() > 0
							&& mSelectedBootstrapProfilePos < mBootstrapProfiles
									.size()) {

						mSelectedBootstrapProfile = mBootstrapProfiles
								.get(mSelectedBootstrapProfilePos);
					}
				}
			}
		}

		if (mSelectedBootstrapProfile == null
				|| TextUtils.isEmpty(mSelectedBootstrapProfile
						.getSettings().getServiceHost())) {
			Log.d(LOGTAG, "Bootstrap did not return a valid host");
			return null;
		}

		OAuthService service = createService();

		Log.i(LOGTAG, "Retrieving OAuth request token...");
		Token reqToken = service.getRequestToken();
		mRequestToken = reqToken.getToken();
		mRequestTokenSecret = reqToken.getSecret();

		Log.i(LOGTAG, "Redirecting user for authorization...");
		url = service.getAuthorizationUrl(reqToken);
	} catch (BootstrapManager.ClientUnsupportedException cue) {

		return null;
	} catch (Exception ex) {
		Log.e(LOGTAG, "Failed to obtain OAuth request token", ex);
	}
	return url;
}
 
Example #17
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthSuccess() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(200);
    when(r.getBody()).thenReturn("oauth_token=valueForToken&oauth_token_secret=valueForSecret");

    Token token = rb.clearXAuth(r);
    assertEquals(token.getToken(), "valueForToken");
    assertEquals(token.getSecret(), "valueForSecret");
}
 
Example #18
Source File: InitialActivityTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void onCreate_shouldTrackAsLoggedIn() throws Exception {
    ((MapzenApplication) application).setAccessToken(new Token("hokus", "bogus"));
    initInitialActivity();
    JSONObject expectedPayload = new JSONObject();
    expectedPayload.put(LOGGED_IN_KEY, String.valueOf(true));
    Mockito.verify(mixpanelAPI).track(eq(INITIAL_LAUNCH), refEq(expectedPayload));
}
 
Example #19
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 5 votes vote down vote up
Token clearXAuth(Response response) {
    if (response.getCode() == 200 || response.getCode() == 201) {
        return parseXAuthResponse(response);
    } else {
        throw new JumblrException(response);
    }
}
 
Example #20
Source File: EvernoteAuthToken.java    From EverMemo with MIT License 5 votes vote down vote up
public EvernoteAuthToken(Token token) {
  super(token.getToken(), token.getSecret(), token.getRawResponse());
  this.mNoteStoreUrl = extract(getRawResponse(), NOTESTORE_REGEX);
  this.mWebApiUrlPrefix = extract(getRawResponse(), WEBAPI_REGEX);
  this.mUserId = Integer.parseInt(extract(getRawResponse(), USERID_REGEX));
}
 
Example #21
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthSuccessWithExtra() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(201);
    when(r.getBody()).thenReturn("oauth_token=valueForToken&oauth_token_secret=valueForSecret&other=paramisokay");

    Token token = rb.clearXAuth(r);
    assertEquals(token.getToken(), "valueForToken");
    assertEquals(token.getSecret(), "valueForSecret");
}
 
Example #22
Source File: ResourceClient.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
public String sendTestRequestSample1(Token accessToken) throws ClientException
{
	OAuthService service = getOAuthService(scopes, null);
	
	OAuthRequest request = new OAuthRequest(Verb.GET,
			"http://localhost:9998/testsuite/rest/sample/1");
	service.signRequest(accessToken, request);
	Response response = request.send();
	if (response.getCode()!=200)
		throwClientException(response);
	return response.getBody();
}
 
Example #23
Source File: BaseActivityTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void onOptionsItemSelected_shouldLogout() throws Exception {
    Token token = new Token("stuff", "fun");
    Menu menu = new TestMenu();
    activity.onCreateOptionsMenu(menu);
    activity.setAccessToken(token);
    MenuItem menuItem = menu.findItem(R.id.logout);
    assertThat(app.getAccessToken()).isNotNull();
    activity.onOptionsItemSelected(menuItem);
    assertThat(app.getAccessToken()).isNull();
}
 
Example #24
Source File: BaseActivityTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldHaveOSMLogoutOption() throws Exception {
    Token token = new Token("stuff", "fun");
    Menu menu = new TestMenu();
    activity.onCreateOptionsMenu(menu);
    activity.setAccessToken(token);
    MenuItem menuItem = menu.findItem(R.id.logout);
    assertThat(menuItem).isVisible();
}
 
Example #25
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
public XeroClient(Reader pemReader, String consumerKey, String consumerSecret) {
  service = new ServiceBuilder()
      .provider(new XeroOAuthService(pemReader))
      .apiKey(consumerKey)
      .apiSecret(consumerSecret)
      .build();
  token = new Token(consumerKey, consumerSecret);
}
 
Example #26
Source File: LoginActivityTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldNotStoreLoginPageInHistory() {
    Token testToken = new Token("Bogus_key", "Bogus_verfier");
    activity.openLoginPage(testToken);
    assertThat(shadowOf(activity).getNextStartedActivity().getFlags()
            & Intent.FLAG_ACTIVITY_NO_HISTORY).isEqualTo(Intent.FLAG_ACTIVITY_NO_HISTORY);
}
 
Example #27
Source File: LoginActivityTest.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldOpenLoginPage() {
    Token testToken = new Token("Bogus_key", "Bogus_verfier");
    activity.openLoginPage(testToken);
    String urlOpened = shadowOf(activity).getNextStartedActivity().getDataString();
    assertThat(urlOpened)
            .contains("https://www.openstreetmap.org/oauth/authorize?oauth_token=");
}
 
Example #28
Source File: MapzenApplication.java    From open with GNU General Public License v3.0 5 votes vote down vote up
public void setAccessToken(Token accessToken) {
    SharedPreferences prefs = getSharedPreferences("OAUTH", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("token", simpleCrypt.encode(accessToken.getToken()));
    editor.putString("secret", simpleCrypt.encode(accessToken.getSecret()));
    editor.commit();
}
 
Example #29
Source File: OAuth2ServiceWrapper.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Override
public Token refreshToken(OAuth2Token token) {
    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
    request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
    request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
    request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
    request.addQuerystringParameter("refresh_token", token.getRefreshToken());
    if(config.hasScope()) 
    	request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
    Response response = request.send();
    return api.getAccessTokenExtractor().extract(response.getBody());
}
 
Example #30
Source File: SmugMugInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
SmugMugInterface(AppCredentials appCredentials, TokenSecretAuthData authData, ObjectMapper mapper)
    throws IOException {
  this.oAuthService =
      new ServiceBuilder()
          .apiKey(appCredentials.getKey())
          .apiSecret(appCredentials.getSecret())
          .provider(SmugMugOauthApi.class)
          .build();
  this.accessToken = new Token(authData.getToken(), authData.getSecret());
  this.mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  this.user = getUserInformation().getUser();
}