Skip to content

Instantly share code, notes, and snippets.

@niftynei
Created March 30, 2014 00:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save niftynei/9865193 to your computer and use it in GitHub Desktop.
Save niftynei/9865193 to your computer and use it in GitHub Desktop.
Java Example using Apache's OLTU OAuth2 library
/// GENERAL METHODS FOR OAUTH'ING
/// using the Apache Oltu library
/// https://cwiki.apache.org/confluence/display/OLTU/Index
public String getAuthUrl() {
OAuthClientRequest request = null;
try {
request = OAuthClientRequest
.authorizationLocation("https://www.hackerschool.com/oauth/authorize")
.setClientId(Constants.CLIENT_ID)
.setResponseType("code")
.setRedirectURI(Constants.REDIRECT_URI)
.buildQueryMessage();
}
catch (OAuthSystemException e) {
Log.e(TAG, "exception loading oauth ", e);
}
return request.getLocationUri();
}
// Note: should be run on background thread
public void getAccessToken(final String accessCode) {
try {
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://www.hackerschool.com/oauth/token")
.setClientId(Constants.CLIENT_ID)
.setClientSecret(Constants.CLIENT_SECRET)
.setRedirectURI(Constants.REDIRECT_URI)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setCode(accessCode)
.buildBodyMessage();
OAuthJSONAccessTokenResponse response = mClient.accessToken(mRequest);
mAccessToken = response.getAccessToken();
}
catch (OAuthSystemException e) {
Log.e(TAG, "exception loading oauth ", e);
}
}
// NOTE: Should be run on background thread
public void makeARequest() throws OAuthSystemException, OAuthProblemException {
OAuthClientRequest bearerRequest = new OAuthBearerClientRequest("https://www.hackerschool.com/api/v1/people/me")
.setAccessToken(mAccessToken)
.buildQueryMessage();
OAuthResourceResponse response = mClient.resource(bearerRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
response.getBody();
response.getResponseCode();
}
/// ANDROID IMPLEMENTATION (partially complete) FOR USING A WEBVIEW
private void setupWebView() {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
if (url.startsWith(Constants.REDIRECT_URI)) {
Uri uri = Uri.parse(url);
if (uri.getQueryParameter("code") != null) {
String code = uri.getQueryParameter("code");
getAccessToken(code);
return true;
}
else if (uri.getQueryParameter("error") != null) {
String message = uri.getQueryParameter("error_message");
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
}
}
return super.shouldOverrideUrlLoading(view, url);
}
});
mWebView.loadUrl(getAuthUrl());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment