Android SDK
How to use authgear android SDK

Setup Application in Authgear

Signup for an Authgear Portal account in https://portal.authgearapps.com/. Or you can use your self-deployed Authgear.
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Portal
authgear.yaml (self-deployed)
Create an application
  1. 1.
    Go to Applications on the left menu bar.
  2. 2.
    Click ⊕Add Application in the top tool bar.
  3. 3.
    Input the name of your application, e.g. "MyAwesomeApp".
  4. 4.
    Under Authorized Redirect URIs, Click "⊕Add URI".
  5. 5.
    In your IDE (e.g. Android Studio), define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path.[^1]
  6. 6.
    Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
  7. 7.
    Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
  8. 8.
    (Optional) Click "Edit" if you wish to configure more authentication settings.
Could not load image
If you wish to validate JSON Web Token (JWT) in your own application server, select "Issue JWT as access token".[^2] If you wish to forward authentication requests to Authgear Resolver Endpoint, leave this unchecked. See comparisons in Backend Integration.
1
oauth:
2
clients:
3
- name: your_app_name
4
client_id: a_random_generated_string
5
redirect_uris:
6
- "com.myapp://host/path"
7
grant_types:
8
- authorization_code
9
- refresh_token
10
response_types:
11
- code
12
- none
Copied!

Get the SDK

  1. 1.
    Add jitpack repository to gradle
    1
    allprojects {
    2
    repositories {
    3
    // Other repository
    4
    maven { url 'https://jitpack.io' }
    5
    }
    6
    }
    Copied!
  2. 2.
    Add authgear in dependencies. Use $branch-SNAPSHOT (e.g. main-SNAPSHOT) for the latest version in a branch or a release tag/git commit hash of the desired version.
    1
    dependencies {
    2
    // Other implementations
    3
    implementation 'com.github.authgear:authgear-sdk-android:SNAPSHOT'
    4
    }
    Copied!

Setup Redirect URI for Your Android App

Add the following activity entry to the AndroidManifest.xml of your app. The intent system would dispatch the redirect URI to OauthRedirectActivity and the SDK would handle the rest.
1
<!-- Your application configuration. Omitted here for brevity -->
2
<application>
3
<!-- Other activities or entries -->
4
5
<!-- Add the following activity -->
6
<activity android:name="com.oursky.authgear.OauthRedirectActivity"
7
android:exported="false"
8
android:launchMode="singleTask">
9
<intent-filter>
10
<action android:name="android.intent.action.VIEW" />
11
<category android:name="android.intent.category.DEFAULT" />
12
<category android:name="android.intent.category.BROWSABLE" />
13
<!-- Configure data to be the exact redirect URI your app uses. -->
14
<!-- Here, we are using com.myapp://host/path as configured in authgear.yaml. -->
15
<!-- NOTE: The redirectURI supplied in AuthorizeOptions *has* to match as well -->
16
<data android:scheme="com.myapp"
17
android:host="host"
18
android:pathPrefix="/path"/>
19
</intent-filter>
20
</activity>
21
</application>
Copied!

Initialize Authgear

Add the following code to your app's Application class. If there is none, add a class that extends Application. Make sure it is declared in AndroidManifest.xml's application tag with the name attribute as described here.
1
public class MyAwesomeApplication extends Application {
2
// The client ID of the oauth client.
3
private static final String CLIENT_ID = "a_random_generated_string"
4
// Deployed authgear's endpoint
5
private static final String AUTHGEAR_ENDPOINT = "http://<myapp>.authgearapps.com/"
6
private Authgear mAuthgear;
7
public void onCreate() {
8
super.onCreate();
9
mAuthgear = new Authgear(this, CLIENT_ID, AUTHGEAR_ENDPOINT);
10
mAuthgear.configure(new OnConfigureListener() {
11
@Override
12
public void onConfigured() {
13
// Authgear can be used.
14
}
15
16
@Override
17
public void onConfigurationFailed(@NonNull Throwable throwable) {
18
Log.d(TAG, throwable.toString());
19
// Something went wrong, check the client ID or endpoint.
20
}
21
});
22
}
23
24
public Authgear getAuthgear() {
25
return mAuthgear;
26
}
27
}
Copied!

Authorize a user

Add the following code to your view model. Do NOT call these codes in activity as this can lead to memory leak when your activity instance is destroyed. You can read more on the view model in the official documentation here.
1
class MyAwesomeViewModel extends AndroidViewModel {
2
// Other methods
3
4
// This is called when login button is clicked.
5
public void login() {
6
MyAwesomeApplication app = getApplication();
7
app.getAuthgear().authorize(new AuthorizeOptions(
8
"com.myapp://host/path",
9
null,
10
null,
11
null,
12
null
13
), new OnAuthorizeListener() {
14
@Override
15
public void onAuthorized(@Nullable String state) {
16
// The user is logged in!
17
}
18
19
@Override
20
public void onAuthorizationFailed(@NonNull Throwable throwable) {
21
// Something went wrong.
22
}
23
});
24
}
25
}
Copied!
The above call of authorize passes in the exact redirect URI as configured in the applications and manifest, the callback then indicates authorization success or failure. By default, the callback is called on the main thread.

Using the Access Token in HTTP Requests

Call refreshAccessTokenIfNeeded every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of your application request. If you are using OKHttp in your project, you can also use the interceptor extension provided by the SDK, see detail.
1
// Suppose we are preparing an http request in a background thread.
2
3
// Setting up the request, e.g. preparing a URLConnection
4
5
try {
6
authgear.refreshAccessTokenIfNeededSync();
7
} catch (OauthException e) {
8
// The token is expired.
9
}
10
String accessToken = authgear.getAccessToken();
11
if (accessToken == null) {
12
// The user is not logged in, or the token is expired.
13
// It is up to the caller to decide how to handle this situation.
14
// Typically, the request could be aborted
15
// immediately as the response would be 401 anyways.
16
return;
17
}
18
19
HashMap<String, String> headers = new HashMap<>();
20
headers.put("authorization", "Bearer " + accessToken);
21
22
// Submit the request with the headers...
Copied!

Logout

To log out the user from the current app session, you need to invoke thelogoutfunction.
1
class MyAwesomeViewModel extends AndroidViewModel {
2
// Other methods
3
4
// This is called when logout button is clicked.
5
public void logout() {
6
MyAwesomeApplication app = getApplication();
7
app.getAuthgear().logout(.logout(new OnLogoutListener() {
8
@Override
9
public void onLogout() {
10
// Logout successfully
11
}
12
13
@Override
14
public void onLogoutFailed(@NonNull Throwable throwable) {
15
// Failed to logout
16
}
17
});
18
}
19
}
Copied!

Next steps

To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.

Android SDK Reference

For detailed documentation on the Flutter SDK, visit Android SDK Reference

Footnote

[^1]: For futher instruction on setting up custom URI scheme in Android, see https://developer.android.com/training/app-links/deep-linking [^2]: For more explaination on JWT, see https://en.wikipedia.org/wiki/JSON_Web_Token