-
-
Save mcxiaoke/1851321 to your computer and use it in GitHub Desktop.
OAuthActivity implements OAuth logg in in your Android application
This file contains 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
public class OAuthActivity extends Activity { | |
public static String OAUTH_URL = "https://github.com/login/oauth/authorize"; | |
public static String OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"; | |
public static String CLIENT_ID = "YOUR_CLIENT_ID"; | |
public static String CLIENT_SECRET = "YOUR_CLIENT_SECRET"; | |
public static String CALLBACK_URL = "http://localhost"; | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
String url = OAUTH_URL + "?client_id=" + CLIENT_ID; | |
WebView webview = (WebView)findViewById(R.id.webview); | |
webview.getSettings().setJavaScriptEnabled(true); | |
webview.setWebViewClient(new WebViewClient() { | |
public void onPageStarted(WebView view, String url, Bitmap favicon) { | |
String accessTokenFragment = "access_token="; | |
String accessCodeFragment = "code="; | |
// We hijack the GET request to extract the OAuth parameters | |
if (url.contains(accessTokenFragment)) { | |
// the GET request contains directly the token | |
String accessToken = url.substring(url.indexOf(accessTokenFragment)); | |
TokenStorer.setAccessToken(accessToken); | |
} else if(url.contains(accessCodeFragment)) { | |
// the GET request contains an authorization code | |
String accessCode = url.substring(url.indexOf(accessCodeFragment)); | |
TokenStorer.setAccessCode(accessCode); | |
String query = "client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&code=" + accessCode; | |
view.postUrl(OAUTH_ACCESS_TOKEN_URL, query.getBytes()); | |
} | |
} | |
}); | |
webview.loadUrl(url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment