Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork1.7k
Added OAuth2 support and examples for Twitter API#1001
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
base:master
Are you sure you want to change the base?
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package com.github.scribejava.apis; | ||
import com.github.scribejava.apis.openid.OpenIdJsonTokenExtractor; | ||
import com.github.scribejava.core.builder.api.DefaultApi20; | ||
import com.github.scribejava.core.extractors.TokenExtractor; | ||
import com.github.scribejava.core.model.OAuth2AccessToken; | ||
import com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication; | ||
import com.github.scribejava.core.oauth2.clientauthentication.RequestBodyAuthenticationScheme; | ||
public class TwitterApi20 extends DefaultApi20 { | ||
protected TwitterApi20() { | ||
} | ||
private static class InstanceHolder { | ||
private static final TwitterApi20 INSTANCE = new TwitterApi20(); | ||
} | ||
public static TwitterApi20 instance() { | ||
return InstanceHolder.INSTANCE; | ||
} | ||
@Override | ||
public String getAccessTokenEndpoint() { | ||
return "https://api.twitter.com/2/oauth2/token"; | ||
} | ||
@Override | ||
protected String getAuthorizationBaseUrl() { | ||
return "https://developer.twitter.com/2/oauth2/consent"; | ||
} | ||
@Override | ||
public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() { | ||
return OpenIdJsonTokenExtractor.instance(); | ||
} | ||
@Override | ||
public String getRevokeTokenEndpoint() { | ||
return "https://api.twitter.com/2/oauth2/revoke"; | ||
} | ||
@Override | ||
public ClientAuthentication getClientAuthentication() { | ||
return RequestBodyAuthenticationScheme.instance(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
package com.github.scribejava.apis.examples; | ||
import java.util.Random; | ||
import java.util.Scanner; | ||
import com.github.scribejava.apis.TwitterApi20; | ||
import com.github.scribejava.core.builder.ServiceBuilder; | ||
import com.github.scribejava.core.oauth.AuthorizationUrlBuilder; | ||
import com.github.scribejava.core.model.OAuth2AccessToken; | ||
import com.github.scribejava.core.model.OAuthRequest; | ||
import com.github.scribejava.core.model.Response; | ||
import com.github.scribejava.core.model.Verb; | ||
import com.github.scribejava.core.oauth.AccessTokenRequestParams; | ||
import com.github.scribejava.core.oauth.OAuth20Service; | ||
import com.github.scribejava.core.revoke.TokenTypeHint; | ||
import java.io.IOException; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.concurrent.ExecutionException; | ||
public class Twitter20WithPKCEExample { | ||
private static final String NETWORK_NAME = "Twitter"; | ||
private static final String PROTECTED_RESOURCE_URL = "https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330"; | ||
private Twitter20WithPKCEExample() { | ||
} | ||
@SuppressWarnings("PMD.SystemPrintln") | ||
public static void main(String... args) throws IOException, InterruptedException, ExecutionException { | ||
final String clientId = "CLIENT_ID"; // replace these with your client id | ||
final String state = "secret" + new Random().nextInt(999_999); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. I detect that this code is problematic. According to theBad practice (BAD_PRACTICE),DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE). | ||
final OAuth20Service service = new ServiceBuilder(clientId) | ||
.defaultScope("tweet.read users.read account.follows.read account.follows.write") // replace with desired scope | ||
.callback("https://twitter.com/") | ||
.build(TwitterApi20.instance()); | ||
final Scanner in = new Scanner(System.in, "UTF-8"); | ||
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); | ||
System.out.println(); | ||
// Obtain the Authorization URL | ||
System.out.println("Fetching the Authorization URL..."); | ||
final Map<String, String> additionalParams = new HashMap<>(); | ||
final AuthorizationUrlBuilder authorizationUrlBuilder = service.createAuthorizationUrlBuilder() | ||
.state(state) | ||
.additionalParams(additionalParams) | ||
.initPKCE(); | ||
System.out.println("Got the Authorization URL!"); | ||
System.out.println("Now go and authorize ScribeJava here:"); | ||
System.out.println(authorizationUrlBuilder.build()); | ||
System.out.println("And paste the authorization code here"); | ||
System.out.print(">>"); | ||
final String code = in.nextLine(); | ||
System.out.println(); | ||
System.out.println("And paste the state from server here. We have set 'state'='" + state + "'."); | ||
System.out.print(">>"); | ||
final String value = in.nextLine(); | ||
if (state.equals(value)) { | ||
System.out.println("State value does match!"); | ||
} else { | ||
System.out.println("Ooops, state value does not match!"); | ||
System.out.println("Expected = " + state); | ||
System.out.println("Got = " + value); | ||
System.out.println(); | ||
} | ||
System.out.println("Trading the Authorization Code for an Access Token..."); | ||
OAuth2AccessToken accessToken = service.getAccessToken(AccessTokenRequestParams.create(code).clientId(clientId) | ||
.pkceCodeVerifier(authorizationUrlBuilder.getPkce().getCodeVerifier())); | ||
System.out.println("Got the Access Token!"); | ||
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')"); | ||
fetchResource(service, accessToken, PROTECTED_RESOURCE_URL); | ||
System.out.println("Refreshing the Access Token..."); | ||
accessToken = service.refreshAccessToken(accessToken.getRefreshToken(), null, clientId); | ||
System.out.println("Refreshed the Access Token!"); | ||
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')"); | ||
System.out.println(); | ||
fetchResource(service, accessToken, PROTECTED_RESOURCE_URL); | ||
System.out.println("Revoking the Refresh Token..."); | ||
service.revokeToken(accessToken.getRefreshToken(), TokenTypeHint.REFRESH_TOKEN); | ||
System.out.println("Revoked the Refresh Token!"); | ||
// Access Token is still valid | ||
fetchResource(service, accessToken, PROTECTED_RESOURCE_URL); | ||
System.out.println("Revoking the Access Token..."); | ||
service.revokeToken(accessToken.getAccessToken(), TokenTypeHint.ACCESS_TOKEN); | ||
System.out.println("Revoked the Access Token!"); | ||
// Both Access Token and Refresh Token are revoked at this moment | ||
fetchResource(service, accessToken, PROTECTED_RESOURCE_URL); | ||
// Now let's go and ask for a protected resource! | ||
while (true) { | ||
System.out.println("Paste fieldnames to fetch (leave empty to get profile, 'exit' to stop example)"); | ||
System.out.print(">>"); | ||
final String query = in.nextLine(); | ||
System.out.println(); | ||
final String requestUrl; | ||
if ("exit".equals(query)) { | ||
break; | ||
} else if (query == null || query.isEmpty()) { | ||
requestUrl = PROTECTED_RESOURCE_URL; | ||
} else { | ||
requestUrl = PROTECTED_RESOURCE_URL + "?fields=" + query; | ||
} | ||
fetchResource(service, accessToken, requestUrl); | ||
} | ||
} | ||
private static void fetchResource(OAuth20Service service, OAuth2AccessToken accessToken, String requestUrl) | ||
throws IOException, InterruptedException, ExecutionException { | ||
// Now let's go and ask for a protected resource! | ||
System.out.println(); | ||
System.out.println("Now we're going to access a protected resource..."); | ||
final OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl); | ||
service.signRequest(accessToken, request); | ||
try (Response response = service.execute(request)) { | ||
System.out.println(response.getCode()); | ||
System.out.println(response.getBody()); | ||
} | ||
System.out.println(); | ||
} | ||
} |