Skip to content

Instantly share code, notes, and snippets.

@bholota
Created August 31, 2015 14:19
Show Gist options
  • Save bholota/469748bac9efc0ea2bb0 to your computer and use it in GitHub Desktop.
Save bholota/469748bac9efc0ea2bb0 to your computer and use it in GitHub Desktop.
Sample oAuth2 code flow, based on gist service
/**
* Sample oauth2 based on code flow
*/
public class MainActivity extends AppCompatActivity {
private static final String REDIRECT_URL = "http://redirect.com";
private static final String CLIENT_ID = "your_client_id(oauth_key)";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser = (WebView) findViewById(R.id.browser);
browser.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(REDIRECT_URL)) {
HashMap<String, String> params = ParseUrlParams(url);
if(params != null) {
//get access token and stuff
return true;
}
}
return super.shouldOverrideUrlLoading(view, url);
}
});
String params = "?client_id=" + CLIENT_ID + "&response_type=code&redirect_uri=" + REDIRECT_URL;
browser.loadUrl("https://gitter.im/login/oauth/authorize" + params);
}
public static @Nullable
HashMap<String, String> ParseUrlParams(String url) {
String params = null;
try {
params = new URL(url).getQuery();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
String[] exploded = params.split("&");
HashMap<String, String> uniqueParams = new HashMap<String, String>();
for (String keyValue : exploded) {
String[] split = keyValue.split("=");
uniqueParams.put(split[0], split[1]);
}
return uniqueParams;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment