Skip to content

Instantly share code, notes, and snippets.

@fbis251
Created March 27, 2015 03:53
Show Gist options
  • Save fbis251/5d54e95d96fbfda22a3f to your computer and use it in GitHub Desktop.
Save fbis251/5d54e95d96fbfda22a3f to your computer and use it in GitHub Desktop.
An OAuth test for the JRAW library on Android
import net.dean.jraw.RedditClient;
import net.dean.jraw.http.LoggingMode;
import net.dean.jraw.http.NetworkException;
import net.dean.jraw.http.UserAgent;
import net.dean.jraw.http.oauth.Credentials;
import net.dean.jraw.http.oauth.OAuthData;
import net.dean.jraw.http.oauth.OAuthException;
import net.dean.jraw.http.oauth.OAuthHelper;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String CLIENT_ID = "THE_APP_PUBLIC_ID";
private static final String REDIRECT_URL = "https://example.com/auth/";
private static RedditClient mRedditClient;
private TextView mTextView;
private String mRefreshToken = "PUT_TOKEN_HERE";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(LOG_TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this;
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
WebView webView = (WebView) findViewById(R.id.web_view);
mTextView = (TextView) findViewById(R.id.text_view);
mRedditClient = new RedditClient(UserAgent.of("JrawTest 0.1"));
mRedditClient.setLoggingMode(LoggingMode.ALWAYS);
final OAuthHelper oAuthHelper = mRedditClient.getOAuthHelper();
// This is Android, so our OAuth app should be an installed app.
final Credentials credentials = Credentials.installedApp(CLIENT_ID, REDIRECT_URL);
// Try to refresh the token
if(!mRefreshToken.isEmpty()) {
new TokenRefreshTask().execute();
return;
}
// If this is true, then you will be able to refresh to access token
boolean permanent = true;
// OAuth2 scopes to request. See https://www.reddit.com/dev/api/oauth for a full list
String[] scopes = {"identity", "read", "vote", "save", "mysubreddits"};
String authorizationUrl = oAuthHelper.getAuthorizationUrl(credentials, permanent, scopes)
.toExternalForm();
authorizationUrl = authorizationUrl.replace("www.", "i.");
Log.v(LOG_TAG, "Auth URL: " + authorizationUrl);
// Load the authorization URL into the browser
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
webView.loadUrl(authorizationUrl);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
// activity.setProgress(newProgress * 1000);
progressBar.setProgress(newProgress);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.contains("code=")) {
Log.v(LOG_TAG, "WebView URL: " + url);
// We've detected the redirect URL
new UserChallengeTask(oAuthHelper, credentials).execute(url);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.v(LOG_TAG, "onCreateOptionsMenu()");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.v(LOG_TAG, "onOptionsItemSelected()");
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void performRedditLogin() {
}
private final class TokenRefreshTask extends AsyncTask<String, Void, OAuthData> {
@Override
protected OAuthData doInBackground(String... params) {
if (!mRefreshToken.isEmpty()) {
final Credentials credentials = Credentials.installedApp(CLIENT_ID, REDIRECT_URL);
OAuthHelper oAuthHelper = mRedditClient.getOAuthHelper();
oAuthHelper.setRefreshToken(mRefreshToken);
try {
OAuthData finalData = oAuthHelper.refreshToken(credentials);
mRedditClient.authenticate(finalData);
if (mRedditClient.isAuthenticated()) {
Log.v(LOG_TAG, "Authenticated");
}
} catch (OAuthException e) {
e.printStackTrace();
}
}
return null;
}
}
private final class UserChallengeTask extends AsyncTask<String, Void, OAuthData> {
private OAuthHelper mOAuthHelper;
private Credentials mCredentials;
public UserChallengeTask(OAuthHelper oAuthHelper, Credentials credentials) {
Log.v(LOG_TAG, "UserChallengeTask()");
mOAuthHelper = oAuthHelper;
mCredentials = credentials;
}
@Override
protected OAuthData doInBackground(String... params) {
Log.v(LOG_TAG, "doInBackground()");
Log.v(LOG_TAG, "params[0]: " + params[0]);
try {
return mOAuthHelper.onUserChallenge(params[0], mCredentials);
} catch (IllegalStateException | NetworkException | OAuthException e) {
// Handle me gracefully
Log.e(LOG_TAG, "OAuth failed");
Log.e(LOG_TAG, e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(OAuthData oAuthData) {
Log.v(LOG_TAG, "onPostExecute()");
if (oAuthData != null) {
mRedditClient.authenticate(oAuthData);
Log.v(LOG_TAG, "Reddit client authentication: " + mRedditClient.isAuthenticated());
mTextView.setText("Logged in");
//TODO: Save refresh token:
String refreshToken = mRedditClient.getOAuthData().getRefreshToken();
Log.v(LOG_TAG, "Refresh Token: " + refreshToken);
} else {
Log.e(LOG_TAG, "Passed in OAuthData was null");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment