Movatterモバイル変換


[0]ホーム

URL:


AppAuth for Android

View the Project on GitHubopenid/AppAuth-Android

Browse the API documentation

AppAuth for Android is a client SDK for communicating withOAuth 2.0 andOpenID Connect providers. It strives todirectly map the requests and responses of those specifications, while followingthe idiomatic style of the implementation language. In addition to mapping theraw protocol flows, convenience methods are available to assist with commontasks like performing an action with fresh tokens.

The library follows the best practices set out inOAuth 2.0 for Native Appsincluding usingCustom Tabsfor the auth request. For this reason,WebView is explicitlynot supported due to usability and security reasons.

The library also supports thePKCEextension to OAuth which was created to secure authorization codes in publicclients when custom URI scheme redirects are used. The library is friendly toother extensions (standard or otherwise) with the ability to handle additionalparameters in all protocol requests and responses.

Specification

Supported Android Versions

AppAuth supports Android API 16 (Jellybean) and above.

When a Custom Tabs implementation is provided by a browser on the device (forexample byChrome), CustomTabs are used for authorization requests. Otherwise, the default browser is usedas a fallback.

Authorization Server Support

Both Custom URI Schemes (all supported versions of Android) and App Links(API 23+) can be used with the library.

In general, AppAuth can work with any Authorization Server (AS) that supportsnative apps,either through custom URI scheme redirects, or App Links.AS's that assume all clients are web-based or require clients to maintainconfidentiality of the client secrets may not work well.

Building the Project

Prerequisites

The project requires the Android SDK for API level 23 (Marshmallow) to build,though the produced binaries only require API level 16 (Jellybean) to beused.

Configure the Demo App

Follow the instructions inapp/README.md to configure thedemo app with your own OAuth client (you need to update 3 configuration pointswith your client info to try the demo).

Building from the Command line

AppAuth for Android uses Gradle as its build system. In order to buildthe library and app binaries, run./gradlew assemble.The library AAR files are output tolibrary/build/outputs/aar, while thedemo app is output toapp/build/outputs/apk.In order to run the tests and code analysis, run./gradlew check.

The build script attemptsto guess the location of your SDK by looking at the values of $ANDROID_SDK_HOMEand $ANDROID_HOME. If neither of these are defined or are not the SDK youwish to use, you must create alocal.properties file in the project root.This file must define a propertysdk.dir that points to your SDK rootdirectory. For example:

sdk.dir=/path/to/android-sdk

Building from Android Studio

In AndroidStudio, File -> New -> Import project. Select the root folder(the one with thebuild.gradle file).

If you get an error like:Error:Could not find com.android.support:customtabs:23.2.0. then be sure youhave installed the Android Support Library from the Android SDK Manager.Follow the Android Studio prompts to resolve the dependencies automatically.

Auth Flow

AppAuth supports both manual interaction with the Authorization Serverwhere you need to perform your own token exchanges, as well as conveniencemethods that perform some of this logic for you. This exampleperforms a manual exchange, and stores the result as anAuthState object.

Tracking authorization state

AuthState is a class that keeps track of the authorization and tokenrequests and responses, and provides a convenience method to call an API withfresh tokens. This is the only object that you need to serialize to retain theauthorization state of the session. Typically, one would do this by storingthe authorization state in SharedPreferences or some other persistent storeprivate to the app:

@NonNullpublicAuthState readAuthState() {SharedPreferences authPrefs= getSharedPreferences("auth",MODE_PRIVATE);String stateJson= authPrefs.getString("stateJson");AuthState state;if (stateStr!=null) {returnAuthState.fromJsonString(stateJson);  }else {returnnewAuthState();  }}publicvoid writeAuthState(@NonNullAuthState state) {SharedPreferences authPrefs= getSharedPreferences("auth",MODE_PRIVATE);  authPrefs.edit()      .putString("stateJson", state.toJsonString())      .apply();}

Configuration

You can configure AppAuth by specifying the endpoints directly:

AuthorizationServiceConfiguration config=newAuthorizationServiceConfiguration(name, mAuthEndpoint, mTokenEndpoint);// perform the auth request...

Or through discovery:

Uri issuerUri=Uri.parse("https://accounts.google.com");AuthorizationServiceConfiguration config=AuthorizationServiceConfiguration.fetchFromIssuer(        issuerUri,newRetrieveConfigurationCallback() {@OverridepublicvoidonFetchConfigurationCompleted(@NullableAuthorizationServiceConfigurationserviceConfiguration,@NullableAuthorizationExceptionex) {if (ex!=null) {Log.w(TAG,"Failed to retrieve configuration for"+ idp.name, ex);            }else {// service configuration retrieved, proceed to authorization...            }          }      });

Authorizing

After configuring or retrieving an authorization service configuration,an authorization request can be constructed for dispatch

AuthorizationRequest req=newAuthorizationRequest.Builder(    config,    clientId,AuthorizationRequest.RESPONSE_TYPE_CODE,    redirectUri);

Requests are dispatched with the help ofAuthorizationService. As thiswill open a custom tab or browser instance to fulfill this request, theresponse is delivered via an intent to an activity of your choosing:

AuthorizationService service=newAuthorizationService(context);service.performAuthorizationRequest(    req,newIntent(context,MyAuthResultHandlerActivity.class));

Handling the Redirect

The response is delivered to the specified handler, and can be extractedfrom the intent data:

publicvoid onCreate(Bundle b) {// ...AuthorizationResponse resp=AuthorizationResponse.fromIntent(getIntent());AuthorizationException ex=AuthorizationException.fromIntent(getIntent());if (resp!=null) {// authorization succeeded  }else {// authorization failed, check ex for more details  }// ...}

Given the auth response, a token request can be created to exchange theauthorization code:

service.performTokenRequest(    resp.createTokenExchangeRequest(),newAuthorizationService.TokenResponseCallback() {@OverridepublicvoidonTokenRequestCompleted(TokenResponseresp,AuthorizationExceptionex) {if (resp!=null) {// exchange succeeded          }else {// authorization failed, check ex for more details          }        }    });

Making API Calls

With an updated AuthState based on the token exchange, it is then possible tomake requests using guaranteed fresh tokens at any future point:

AuthState state = readAuthState();state.performActionWithFreshTokens(service, new AuthStateAction() {  @Override public void execute(      String accessToken,      String idToken,      AuthorizationException ex) {    if (ex != null) {      // negotiation for fresh tokens failed, check ex for more details      return;    }    // use the access token to do something ...  }});

API Documentation

Browse theAPI documentation.


[8]ページ先頭

©2009-2025 Movatter.jp