Heimdall.droid


Source link: https://github.com/rheinfabrik/Heimdall.droid

Heimdall

Heimdall is an OAuth 2.0 client specifically designed for easy usage and high flexibility. It supports all grants as described in Section 4 as well as refreshing an access token as described in Section 6 of the The OAuth 2.0 Authorization Framework specification.

This library makes use of RxJava. Therefore you should be familar with Observables.

If you are an iOS Developer then please take a look at the Swift version of Heimdall.

Installation

Heimdall is ready to be used via jitpack.io. Simply add the following code to your root build.gradle:

allprojects {

  repositories {

jcenter()

maven {
 url "https://jitpack.io" 
}

  
}
 
}

Now add the gradle dependency in your application's build.gradle:

dependencies {

  compile 'com.github.rheinfabrik:Heimdall.droid:{
latest_version
}
' 
}

Examples

Heimdall's main class is the OAuth2AccessTokenManager. It is responsible for retrieving a new access token and keeping it valid by refreshing it.

In order to initialize an OAuth2AccessTokenManager instance, you need to pass an object implementing the OAuth2AccessTokenStorage interface. You can use the predefined SharedPreferencesOAuth2AccessTokenStorage if it suits your needs. Make sure that your OAuth2AccessTokenStorage is as secure as possible!

SharedPreferencesOAuth2AccessTokenStorage<OAuth2AccessToken> storage = new SharedPreferencesOAuth2AccessTokenStorage<>(mySharedPreferences, OAuth2AccessToken.class);
 OAuth2AccessTokenManager<> manager = new OAuth2AccessTokenManager<OAuth2AccessToken>(storage);
 

On your manager instance you can now call grantNewAccessToken(grant) to receive a new access token. The grant instance you pass must implement the OAuth2Grant interface and your actual server call.

Here is an example of an OAuth2ResourceOwnerPasswordCredentialsGrant.

public class MyOAuth2Grant extends OAuth2ResourceOwnerPasswordCredentialsGrant<OAuth2AccessToken> {

// Constructor

@Override
  public Observable<OAuth2AccessToken> grantNewAccessToken() {

// Create the network request based on the username, the password and the grant type.

// You can use Retrofit to make things easier.
  
}
 
}

Your manager instance also has a method called getValidAccessToken(refreshGrant). This is probably the main reason we build this library. It firstly checks if the stored access token is expired and then either emits the unexpired one or refreshs it if it is expired using the passed refresh grant.

Here is an example of an OAuth2RefreshAccessTokenGrant.

public class MyOAuth2Grant extends OAuth2RefreshAccessTokenGrant<OAuth2AccessToken> {

// Constructor

@Override
  public Observable<OAuth2AccessToken> grantNewAccessToken() {

// Create the network request based on the grant type and the refresh token.

// You can use Retrofit to make things easier.
  
}
 
}

Mostly you will use the OAuth2AuthorizationCodeGrant to authorize the user via a third party service such as Trakt.tv.

The implemention of a grant authorizing with Trakt.tv might look as following:

public final class TraktTVAuthorizationCodeGrant extends OAuth2AuthorizationCodeGrant<OAuth2AccessToken> {

public String clientSecret;

@Override
  public Uri buildAuthorizationUri() {

return Uri.parse("https://trakt.tv/oauth/authorize")

  .buildUpon()

  .appendQueryParameter("client_id", clientId)

  .appendQueryParameter("redirect_uri", redirectUri)

  .appendQueryParameter("response_type", RESPONSE_TYPE).build();

  
}

@Override
  public Observable<OAuth2AccessToken> exchangeTokenForCode(String code) {

// Create the network request based on the grant type, clientSecret and the retrieved code.

// You can use Retrofit to make things easier.
  
}
 
}

Using that grant with an Android WebView might look like this (please note that we use Retrolambda here):

// Create the grant TraktTVAuthorizationCodeGrant grant = new TraktTVAuthorizationCodeGrant();
 grant.clientSecret = "secret" grant.clientId = "id" grant.redirectUri = "uri"  // Set up web view loading webView.setWebViewClient(new WebViewClient() {

@Override
  public void onPageFinished(WebView view, String url) {

super.onPageFinished(view, url);

 // Tell the grant we loaded an url

grant.onUrlLoadedCommand.onNext(Uri.parse(url));

  
}
 
}
);
  // Load the authorization url once build grant.authorizationUri()
  .map(Uri::parse)  .observeOn(AndroidSchedulers.mainThread())  .subscribe(myWebView::load)  // Start the authorization process grant.grantNewAccessToken()  .subscribe(token -> Log.d("Heimdall", "New token: " + token)) 

Sample Application

Please also check out our sample application which performs an authorization against trakt.tv and displays a simple list of the user's watchlists.

Note: In order to build the sample by yourself you have to create a new application on trakt.tv and add the credentials wherever TraktTvAPIConfiguration.java is used.

About

Heimdall was built by trivago 🏭

License

Heimdall is licensed under Apache Version 2.0.

Resources

Default colors and dimens per Material Design guidelines and Android Design guidelines inside one library.

Android port of Google's libphonenumber.

Dynamic iOS-like blur of underlying Views for Android.

This is a simple Rx Event Bus implementation using Kotlin.

Code beautifier for Android - a wrapper around a WebView running HighlightJS.

That image ViewPager you have to code for every Android project - use this instead.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes