Home > OS >  Authentification for Android without third-party library
Authentification for Android without third-party library

Time:09-23

Is there any way to authenticate using OAuth 2 without using third-party libraries other than Retrofit?

CodePudding user response:

If you are talking about Bearer token based authentication you just need to add an "Authorization" header to your requests.

if you using HttpURLConnection

URL url = new URL("http://www.my-back-end.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", "Bearer yourToken");
urlConnection.setRequestMethod("POST"); // Can be GET or something else

try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     parseResponse(in);
} finally {
    urlConnection.disconnect();
}

CodePudding user response:

Well mobile apps are encouraged to meet requirements in RFC8252, of which these are the two most important:

  • Users login via the system browser so that the app never sees the password. On Android the most user friendly way to do this is to use a Chrome Custom Tab, as used by Gmail and other secure apps.

  • A standards based Authorization Code Flow (PKCE) is used, including various security checks and a tricky HTTP language.

You could code this yourself, but Retrofit is based on JSON and OAuth messages are based on browser redirects and form URL encoded posts.

The recommended Android solution is to use AppAuth libraries to implement these requirements - my blog post shows how this looks and enables you to run a working app quickly. A full solution is not a quick job though and may require discussion with stakeholders.

There are potential benefits to the UX once OAuth is implemented, such as use of WebAuthn for secure password-less logins.

  • Related