-
-
Notifications
You must be signed in to change notification settings - Fork 1.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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xiangyao1989
wants to merge
1
commit into
scribejava:master
Choose a base branch
from
xiangyao1989:twitter-oauth2
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
scribejava-apis/src/main/java/com/github/scribejava/apis/TwitterApi20.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } |
133 changes: 133 additions & 0 deletions
133
...java-apis/src/test/java/com/github/scribejava/apis/examples/Twitter20WithPKCEExample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| 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(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I detect that this code is problematic. According to the Bad practice (BAD_PRACTICE), DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE).
This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required invoke a method on the existing Random object to obtain it.
If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead (and avoid allocating a new SecureRandom for each random number needed).