Skip to content

OAuth 2.0 Implementation

ashokgelal edited this page Apr 1, 2013 · 7 revisions

Requirements:
-An API class with the correct OAuth Urls
-The API key and secret received when you registered the application

Getting an Access Token
The OAuth 2.0 process is very simple to implement.
The flow is essentially:
-Allow a user to authorize your application through a web view -Upgrade the token to an access token

Unlike OAuth 1.0, there is no user secret provided. Access tokens are typically short lived but most APIs will also provide a refresh token used for refreshing access tokens when they expire.

There are a few simple steps to implement this process:
-make a new OAuth20Service by passing in an instance of the API class, your API key, API secret, and an interface callback.
-set any additional parameters, likely the API callback, scope, and duration (these usually default to 'identity' and 'temporary' respectively if not set)
-launch a WebView with the authorization url -save the OAuth20Token

      OAuth20Service service = OAuthService.newInstance(new RedditApi(), APIKEY, APISECRET, new OAuth20ServiceCallback() {
		
		@Override
		public void onOAuthAccessTokenReceived(OAuth20Token token) {
			editor.putString("access_token", token.getAccessToken());
			editor.putString("refresh_token", token.getRefreshToken()); 
			editor.commit();
			getInfo(token); 
		}

		@Override
		public void onAccessTokenRequestFailed(HootResult result) {
			// TODO Auto-generated method stub
			
		}			
	});
	service.setApiCallback(CALLBACK);
	service.setScope("identity");
	service.setDuration("permanent");
	
            WebView webview = (WebView) findViewById(R.id.webview);
	webview.getSettings().setJavaScriptEnabled(true);
	webview.setWebViewClient(new WebViewClient() {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			// Checking for our successful callback
			if(url.startsWith(CALLBACK)) {
				webview.setVisibility(View.GONE);					
				service.getOAuthAccessToken(url);

			}
			return super.shouldOverrideUrlLoading(view, url);
		}

	});
	
	webview.loadUrl(service.getAuthorizeUrl());

**Making Signed Requests**
To make a signed request you only need a valid access token. However, if you have both an access token and a refresh token, the library will attempt to automatically refresh the access token whenever it becomes invalid without requiring user intervention. All you need to do is pass in the url, your token and an instance of the OAuth20Service
          String baseUrl = "https://oauth.reddit.com/api/v1/me";
          OAuth20Request request = OAuthRequest.newInstance(baseUrl, token, service, new OnRequestCompleteListener() {
		
		@Override
		public void onSuccess(HootResult result) {
			//process json response string
		}
		
		@Override
		public void onNewAccessTokenReceived(OAuth20Token token) {
		}
		
		@Override
		public void onFailure(HootResult result) {
		}
	}); 
	request.get();



You can set any POST or GET parameters by passing in a Map with the key and value and calling either .post() or .get().
You can also set additional header parameters by calling setHeaders(Map<String,String> headers) in the same way.

Some notes:
Some API's vary from the spec in one way or another. I tried to cover a lot of these variances as best I could. However, some sites like LinkedIn require the access_token as a query parameter rather than as an Authorization header and actually fails if both are used. To address this you can call shouldUseDefaultAuthorizationHeader and pass in a value of false and then simply set the access token as a query parameter yourself.
I will try to document other oddities as I come across them but everything in the examples folder has been tested. Feel free to contact me if you're adding an API and have trouble. [email protected]

Clone this wiki locally