├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── org │ │ └── keycloak │ │ └── keycloakaccountprovider │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── org │ │ └── keycloak │ │ └── keycloakaccountprovider │ │ ├── KeyCloak.java │ │ ├── KeyCloakAccount.java │ │ ├── KeyCloakAccountAuthenticator.java │ │ ├── KeyCloakAuthenticatorService.java │ │ ├── KeyCloakConfig.java │ │ ├── KeycloakAuthenticationActivity.java │ │ ├── token │ │ └── AccessTokenExchangeLoader.java │ │ └── util │ │ ├── IOUtils.java │ │ ├── ObjectUtils.java │ │ └── TokenExchangeUtils.java │ └── res │ ├── drawable-hdpi │ ├── ic_launcher.png │ └── keycloak_logo.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ ├── ic_launcher.png │ └── login_bg.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── layout-w600dp-land │ └── keycloak_login_fragment_old.xml │ ├── layout │ ├── activity_my.xml │ └── keycloak_login_fragment.xml │ ├── menu │ └── my.xml │ ├── raw │ └── keycloak.json │ ├── values-w820dp │ └── dimens.xml │ ├── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml │ └── xml │ ├── account_preferences.xml │ └── authenticator.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | ########## Intellij ######### 2 | 3 | *.iml 4 | .idea/ 5 | out/ 6 | gen-external-apklibs/ 7 | 8 | ########## Eclipse ########## 9 | 10 | .classpath 11 | .settings/ 12 | .project 13 | classes/ 14 | libs/ 15 | bin/ 16 | project.properties 17 | 18 | ########### Maven ########### 19 | 20 | target/ 21 | tmp/ 22 | 23 | ########### Gradle ########### 24 | 25 | .gradle/ 26 | build/ 27 | local.properties 28 | 29 | ########### Android ########### 30 | 31 | gen/ 32 | lint.xml -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # KeyCloak Authenticator 2 | 3 | This is an implementation of AbstractAccountAuthenticator for KeyCloak. 4 | 5 | # Installation 6 | 7 | Create a OAuth Client in keycloak and put its keycloak.xml file in the `res/raw` directory. In theory it should do the right thing based on what it finds there. 8 | 9 | # What is working 10 | 11 | If you log into an existing KeyCloak account then the Authenticator will add it to Android's known accounts. After this you can get a reference to the account with: 12 | 13 | ```` 14 | Account account = am.getAccountsByType("org.keycloak.Account")[0]; 15 | ```` 16 | 17 | from any application (which declares the correct permissions). 18 | 19 | # What isn't working 20 | * Social Login 21 | * Error Handling 22 | * Removing an Account 23 | * Updating Auth token 24 | * I'm sure quite a few other things 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion '26.0.1' 6 | 7 | defaultConfig { 8 | applicationId "org.keycloak.keycloakaccountprovider" 9 | minSdkVersion 19 10 | targetSdkVersion 26 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'org.jboss.aerogear:aerogear-android-pipe:3.2.0' 25 | compile 'com.google.code.gson:gson:2.8.1' 26 | } 27 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Users\Summers\Programs\adt-bundle-windows-x86_64-20130219\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/org/keycloak/keycloakaccountprovider/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeyCloak.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | import org.keycloak.keycloakaccountprovider.util.IOUtils; 7 | 8 | import java.util.UUID; 9 | 10 | /** 11 | * Created by Summers on 9/13/2014. 12 | */ 13 | public class KeyCloak { 14 | 15 | public static final String ACCOUNT_KEY = "org.keycloak.KeyCloakAccount"; 16 | public static final String ACCOUNT_TYPE = "org.keycloak.Account"; 17 | public static final String ACCOUNT_AUTHTOKEN_TYPE = "org.keycloak.Account.authToken"; 18 | private final KeyCloakConfig config; 19 | private final Context context; 20 | 21 | public KeyCloak(Context context) { 22 | this.config = KeyCloakConfig.getInstance(context); 23 | this.context = context.getApplicationContext(); 24 | } 25 | 26 | public String createLoginUrl() { 27 | String state = UUID.randomUUID().toString(); 28 | String redirectUri = getRedirectUri(); 29 | 30 | saveState(state); 31 | 32 | String url = config.realmUrl 33 | + "/protocol/openid-connect/auth" 34 | + "?client_id=" + IOUtils.encodeURIComponent(config.clientId) 35 | + "&redirect_uri=" + IOUtils.encodeURIComponent(redirectUri) 36 | + "&state=" + IOUtils.encodeURIComponent(state) 37 | + "&response_type=code"; 38 | 39 | 40 | return url; 41 | } 42 | 43 | private void saveState(String state) { 44 | SharedPreferences prefs = context.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE); 45 | prefs.edit().putString("state", state).commit(); 46 | } 47 | 48 | public String getClientId() { 49 | return config.clientId; 50 | } 51 | 52 | public String getRedirectUri() { 53 | return "urn:ietf:wg:oauth:2.0:oob"; 54 | } 55 | 56 | public String getClientSecret() { 57 | return config.clientSecret; 58 | } 59 | 60 | public String getBaseURL() { 61 | return config.realmUrl; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeyCloakAccount.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | import android.util.Base64; 6 | import android.util.Log; 7 | 8 | import org.json.JSONException; 9 | import org.json.JSONObject; 10 | 11 | import java.io.Serializable; 12 | import java.util.Date; 13 | 14 | /** 15 | * Created by Summers on 9/13/2014. 16 | */ 17 | public class KeyCloakAccount { 18 | 19 | private String name, 20 | givenName, 21 | familyName, 22 | middleName, 23 | nickname, 24 | preferredUsername, 25 | profile, 26 | picture, 27 | website, 28 | email, 29 | emailVerified, 30 | gender, 31 | birthdate, 32 | zoneinfo, 33 | locale, 34 | phoneNumber, 35 | phoneNumberVerified, 36 | address, 37 | updatedAt, 38 | formatted, 39 | streetAddress, 40 | locality, 41 | region, 42 | postalCode, 43 | country, 44 | claimsLocales, 45 | accessToken, 46 | expiresIn, 47 | refreshToken, 48 | tokenType, 49 | idToken, 50 | notBeforePolicy, 51 | sessionState; 52 | 53 | private Long expiresOn; 54 | 55 | public KeyCloakAccount() { 56 | } 57 | 58 | 59 | private void extractIdProperties(JSONObject token) { 60 | name = token.optString("name"); 61 | givenName = token.optString("given_name"); 62 | familyName = token.optString("family_name"); 63 | middleName = token.optString("middle_name"); 64 | nickname = token.optString("nickname"); 65 | preferredUsername = token.optString("preferred_username"); 66 | profile = token.optString("profile"); 67 | picture = token.optString("picture"); 68 | website = token.optString("website"); 69 | email = token.optString("email"); 70 | emailVerified = token.optString("email_verified"); 71 | gender = token.optString("gender"); 72 | birthdate = token.optString("birthdate"); 73 | zoneinfo = token.optString("zoneinfo"); 74 | locale = token.optString("locale"); 75 | phoneNumber = token.optString("phone_number"); 76 | phoneNumberVerified = token.optString("phone_number_verified"); 77 | address = token.optString("address"); 78 | updatedAt = token.optString("updated_at"); 79 | formatted = token.optString("formatted"); 80 | streetAddress = token.optString("street_address"); 81 | locality = token.optString("locality"); 82 | region = token.optString("region"); 83 | postalCode = token.optString("postal_code"); 84 | country = token.optString("country"); 85 | claimsLocales = token.optString("claims_locales"); 86 | expiresOn = new Date().getTime() + Long.parseLong(expiresIn) * 1000; 87 | } 88 | 89 | public void extractTokenProperties(JSONObject token) { 90 | accessToken = token.optString("access_token"); 91 | expiresIn = token.optString("expires_in"); 92 | refreshToken = token.optString("refresh_token"); 93 | tokenType = token.optString("token_type"); 94 | idToken = token.optString("id_token"); 95 | notBeforePolicy = token.optString("not-before-policy"); 96 | sessionState = token.optString("session-state"); 97 | 98 | try { 99 | extractIdProperties(new JSONObject(new String(Base64.decode(accessToken.split("\\.")[1].getBytes(), Base64.DEFAULT)))); 100 | } catch (JSONException e) { 101 | throw new RuntimeException(e); 102 | } 103 | 104 | } 105 | 106 | public String getName() { 107 | return name; 108 | } 109 | 110 | public void setName(String name) { 111 | this.name = name; 112 | } 113 | 114 | public String getGivenName() { 115 | return givenName; 116 | } 117 | 118 | public void setGivenName(String givenName) { 119 | this.givenName = givenName; 120 | } 121 | 122 | public String getFamilyName() { 123 | return familyName; 124 | } 125 | 126 | public void setFamilyName(String familyName) { 127 | this.familyName = familyName; 128 | } 129 | 130 | public String getMiddleName() { 131 | return middleName; 132 | } 133 | 134 | public void setMiddleName(String middleName) { 135 | this.middleName = middleName; 136 | } 137 | 138 | public String getNickname() { 139 | return nickname; 140 | } 141 | 142 | public void setNickname(String nickname) { 143 | this.nickname = nickname; 144 | } 145 | 146 | public String getPreferredUsername() { 147 | return preferredUsername; 148 | } 149 | 150 | public void setPreferredUsername(String preferredUsername) { 151 | this.preferredUsername = preferredUsername; 152 | } 153 | 154 | public String getProfile() { 155 | return profile; 156 | } 157 | 158 | public void setProfile(String profile) { 159 | this.profile = profile; 160 | } 161 | 162 | public String getPicture() { 163 | return picture; 164 | } 165 | 166 | public void setPicture(String picture) { 167 | this.picture = picture; 168 | } 169 | 170 | public String getWebsite() { 171 | return website; 172 | } 173 | 174 | public void setWebsite(String website) { 175 | this.website = website; 176 | } 177 | 178 | public String getEmail() { 179 | return email; 180 | } 181 | 182 | public void setEmail(String email) { 183 | this.email = email; 184 | } 185 | 186 | public String getEmailVerified() { 187 | return emailVerified; 188 | } 189 | 190 | public void setEmailVerified(String emailVerified) { 191 | this.emailVerified = emailVerified; 192 | } 193 | 194 | public String getGender() { 195 | return gender; 196 | } 197 | 198 | public void setGender(String gender) { 199 | this.gender = gender; 200 | } 201 | 202 | public String getBirthdate() { 203 | return birthdate; 204 | } 205 | 206 | public void setBirthdate(String birthdate) { 207 | this.birthdate = birthdate; 208 | } 209 | 210 | public String getZoneinfo() { 211 | return zoneinfo; 212 | } 213 | 214 | public void setZoneinfo(String zoneinfo) { 215 | this.zoneinfo = zoneinfo; 216 | } 217 | 218 | public String getLocale() { 219 | return locale; 220 | } 221 | 222 | public void setLocale(String locale) { 223 | this.locale = locale; 224 | } 225 | 226 | public String getPhoneNumber() { 227 | return phoneNumber; 228 | } 229 | 230 | public void setPhoneNumber(String phoneNumber) { 231 | this.phoneNumber = phoneNumber; 232 | } 233 | 234 | public String getPhoneNumberVerified() { 235 | return phoneNumberVerified; 236 | } 237 | 238 | public void setPhoneNumberVerified(String phoneNumberVerified) { 239 | this.phoneNumberVerified = phoneNumberVerified; 240 | } 241 | 242 | public String getAddress() { 243 | return address; 244 | } 245 | 246 | public void setAddress(String address) { 247 | this.address = address; 248 | } 249 | 250 | public String getUpdatedAt() { 251 | return updatedAt; 252 | } 253 | 254 | public void setUpdatedAt(String updatedAt) { 255 | this.updatedAt = updatedAt; 256 | } 257 | 258 | public String getFormatted() { 259 | return formatted; 260 | } 261 | 262 | public void setFormatted(String formatted) { 263 | this.formatted = formatted; 264 | } 265 | 266 | public String getStreetAddress() { 267 | return streetAddress; 268 | } 269 | 270 | public void setStreetAddress(String streetAddress) { 271 | this.streetAddress = streetAddress; 272 | } 273 | 274 | public String getLocality() { 275 | return locality; 276 | } 277 | 278 | public void setLocality(String locality) { 279 | this.locality = locality; 280 | } 281 | 282 | public String getRegion() { 283 | return region; 284 | } 285 | 286 | public void setRegion(String region) { 287 | this.region = region; 288 | } 289 | 290 | public String getPostalCode() { 291 | return postalCode; 292 | } 293 | 294 | public void setPostalCode(String postalCode) { 295 | this.postalCode = postalCode; 296 | } 297 | 298 | public String getCountry() { 299 | return country; 300 | } 301 | 302 | public void setCountry(String country) { 303 | this.country = country; 304 | } 305 | 306 | public String getClaimsLocales() { 307 | return claimsLocales; 308 | } 309 | 310 | public void setClaimsLocales(String claimsLocales) { 311 | this.claimsLocales = claimsLocales; 312 | } 313 | 314 | public String getAccessToken() { 315 | return accessToken; 316 | } 317 | 318 | public void setAccessToken(String accessToken) { 319 | this.accessToken = accessToken; 320 | } 321 | 322 | public String getExpiresIn() { 323 | return expiresIn; 324 | } 325 | 326 | public void setExpiresIn(String expiresIn) { 327 | this.expiresIn = expiresIn; 328 | expiresOn = new Date().getTime() + Long.parseLong(expiresIn) * 1000; 329 | } 330 | 331 | public String getRefreshToken() { 332 | return refreshToken; 333 | } 334 | 335 | public void setRefreshToken(String refreshToken) { 336 | this.refreshToken = refreshToken; 337 | } 338 | 339 | public String getTokenType() { 340 | return tokenType; 341 | } 342 | 343 | public void setTokenType(String tokenType) { 344 | this.tokenType = tokenType; 345 | } 346 | 347 | public String getIdToken() { 348 | return idToken; 349 | } 350 | 351 | public void setIdToken(String idToken) { 352 | this.idToken = idToken; 353 | } 354 | 355 | public String getNotBeforePolicy() { 356 | return notBeforePolicy; 357 | } 358 | 359 | public void setNotBeforePolicy(String notBeforePolicy) { 360 | this.notBeforePolicy = notBeforePolicy; 361 | } 362 | 363 | public String getSessionState() { 364 | return sessionState; 365 | } 366 | 367 | public void setSessionState(String sessionState) { 368 | this.sessionState = sessionState; 369 | } 370 | 371 | public Long getExpiresOn() { 372 | return expiresOn; 373 | } 374 | 375 | } 376 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeyCloakAccountAuthenticator.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.accounts.AbstractAccountAuthenticator; 4 | import android.accounts.Account; 5 | import android.accounts.AccountAuthenticatorResponse; 6 | import android.accounts.AccountManager; 7 | import android.accounts.NetworkErrorException; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.os.Bundle; 11 | 12 | import com.google.gson.Gson; 13 | 14 | import org.jboss.aerogear.android.pipe.http.HttpException; 15 | import org.keycloak.keycloakaccountprovider.util.TokenExchangeUtils; 16 | 17 | import java.util.Date; 18 | 19 | 20 | /** 21 | * Created by Summers on 9/12/2014. 22 | */ 23 | public class KeyCloakAccountAuthenticator extends AbstractAccountAuthenticator { 24 | 25 | private final Context context; 26 | private final AccountManager am; 27 | private final KeyCloak kc; 28 | public KeyCloakAccountAuthenticator(Context context) { 29 | super(context); 30 | this.context = context.getApplicationContext(); 31 | this.am = AccountManager.get(context); 32 | this.kc = new KeyCloak(context); 33 | } 34 | 35 | @Override 36 | public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String s) { 37 | return null; 38 | } 39 | 40 | @Override 41 | public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { 42 | Bundle toReturn = new Bundle(); 43 | AccountManager am = AccountManager.get(context); 44 | 45 | if (options == null || options.getString(KeyCloak.ACCOUNT_KEY) == null) { 46 | toReturn.putParcelable(AccountManager.KEY_INTENT, new Intent(context, KeycloakAuthenticationActivity.class).putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)); 47 | toReturn.putParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); 48 | } else { 49 | KeyCloakAccount account = new Gson().fromJson(options.getString(KeyCloak.ACCOUNT_KEY), KeyCloakAccount.class); 50 | am.removeAccount(new Account(account.getPreferredUsername(), KeyCloak.ACCOUNT_TYPE), null, null); 51 | am.addAccountExplicitly(new Account(account.getPreferredUsername(), KeyCloak.ACCOUNT_TYPE), null, options); 52 | toReturn.putString(AccountManager.KEY_ACCOUNT_NAME, account.getPreferredUsername()); 53 | toReturn.putString(AccountManager.KEY_ACCOUNT_TYPE, KeyCloak.ACCOUNT_TYPE); 54 | 55 | } 56 | 57 | return toReturn; 58 | } 59 | 60 | @Override 61 | public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle bundle) throws NetworkErrorException { 62 | return null; 63 | } 64 | 65 | @Override 66 | public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException { 67 | 68 | 69 | Account[] accounts = am.getAccountsByType(KeyCloak.ACCOUNT_TYPE); 70 | for (Account existingAccount : accounts) { 71 | if (existingAccount.name == account.name) { 72 | break; 73 | } 74 | } 75 | 76 | 77 | String keyCloackAccount = am.getUserData(account, KeyCloak.ACCOUNT_KEY); 78 | KeyCloakAccount kcAccount = new Gson().fromJson(keyCloackAccount, KeyCloakAccount.class); 79 | if (kcAccount == null) { 80 | Bundle toReturn = new Bundle(); 81 | toReturn.putParcelable(AccountManager.KEY_INTENT, new Intent(context, KeycloakAuthenticationActivity.class).putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse)); 82 | toReturn.putParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); 83 | return toReturn; 84 | 85 | } 86 | if (new Date(kcAccount.getExpiresOn()).before(new Date())) { 87 | try { 88 | TokenExchangeUtils.refreshToken(kcAccount, kc); 89 | String accountJson = new Gson().toJson(kcAccount); 90 | am.setUserData(new Account(kcAccount.getPreferredUsername(), KeyCloak.ACCOUNT_TYPE), KeyCloak.ACCOUNT_KEY, accountJson); 91 | } catch (HttpException e) { 92 | if (e.getStatusCode() / 100 == 4) { 93 | Bundle toReturn = new Bundle(); 94 | toReturn.putParcelable(AccountManager.KEY_INTENT, new Intent(context, KeycloakAuthenticationActivity.class).putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse)); 95 | toReturn.putParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse); 96 | return toReturn; 97 | } else { 98 | Bundle toReturn = new Bundle(); 99 | toReturn.putString(AccountManager.KEY_ERROR_CODE, e.getStatusCode() + ""); 100 | toReturn.putString(AccountManager.KEY_ERROR_MESSAGE, e.getMessage()); 101 | return toReturn; 102 | } 103 | } 104 | } 105 | 106 | Bundle toReturn = new Bundle(); 107 | toReturn.putString(AccountManager.KEY_AUTHTOKEN, kcAccount.getAccessToken()); 108 | toReturn.putString(AccountManager.KEY_ACCOUNT_NAME, kcAccount.getPreferredUsername()); 109 | toReturn.putString(AccountManager.KEY_ACCOUNT_TYPE, KeyCloak.ACCOUNT_TYPE); 110 | return toReturn; 111 | } 112 | 113 | 114 | @Override 115 | public String getAuthTokenLabel(String s) { 116 | return "KeyCloak Token"; 117 | } 118 | 119 | @Override 120 | public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException { 121 | 122 | String keyCloackAccount = AccountManager.get(context).getUserData(account, KeyCloak.ACCOUNT_KEY); 123 | KeyCloakAccount kca = new Gson().fromJson(keyCloackAccount, KeyCloakAccount.class); 124 | 125 | if (kca.getExpiresOn() < new Date().getTime()) { 126 | throw new RuntimeException("token expired"); 127 | } 128 | 129 | Bundle toReturn = new Bundle(); 130 | toReturn.putString(AccountManager.KEY_ACCOUNT_NAME, kca.getPreferredUsername()); 131 | toReturn.putString(AccountManager.KEY_ACCOUNT_TYPE, KeyCloak.ACCOUNT_TYPE); 132 | 133 | return toReturn; 134 | } 135 | 136 | @Override 137 | public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] strings) throws NetworkErrorException { 138 | return null; 139 | } 140 | 141 | 142 | 143 | } 144 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeyCloakAuthenticatorService.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.app.Service; 4 | import android.content.Intent; 5 | import android.os.IBinder; 6 | 7 | public class KeyCloakAuthenticatorService extends Service { 8 | 9 | private KeyCloakAccountAuthenticator authenticator; 10 | 11 | @Override 12 | public void onCreate() { 13 | super.onCreate(); 14 | authenticator = new KeyCloakAccountAuthenticator(this); 15 | } 16 | 17 | @Override 18 | public IBinder onBind(Intent intent) { 19 | return authenticator.getIBinder(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeyCloakConfig.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | import org.keycloak.keycloakaccountprovider.util.IOUtils; 9 | import org.keycloak.keycloakaccountprovider.util.ObjectUtils; 10 | 11 | import java.io.InputStream; 12 | import java.io.UnsupportedEncodingException; 13 | import java.net.URLEncoder; 14 | 15 | /** 16 | * Created by Summers on 9/13/2014. 17 | */ 18 | public final class KeyCloakConfig { 19 | 20 | private static final String TAG = KeyCloakConfig.class.getSimpleName().toUpperCase(); 21 | 22 | public final String realmUrl; 23 | public final String authServerUrl; 24 | public final String realm; 25 | public final String clientId; 26 | public final String clientSecret; 27 | 28 | private static KeyCloakConfig instace; 29 | 30 | private KeyCloakConfig(Context context) { 31 | InputStream fileStream = context.getResources().openRawResource(R.raw.keycloak); 32 | String configText = IOUtils.getString(fileStream); 33 | IOUtils.close(fileStream); 34 | 35 | try { 36 | JSONObject configFile = new JSONObject(configText); 37 | realm = configFile.getString("realm"); 38 | authServerUrl = configFile.getString("auth-server-url"); 39 | realmUrl = authServerUrl + "/realms/" + URLEncoder.encode(realm, "UTF-8"); 40 | clientId = configFile.getString("resource"); 41 | clientSecret = ObjectUtils.getOrDefault(configFile.optJSONObject("credentials"), new JSONObject()).optString("secret"); 42 | } catch (JSONException e) { 43 | Log.e(TAG, e.getMessage(), e); 44 | throw new RuntimeException(e); 45 | } catch (UnsupportedEncodingException e) { 46 | throw new RuntimeException("You don't support UTF-8", e); 47 | } 48 | } 49 | 50 | public static synchronized KeyCloakConfig getInstance(Context context) { 51 | if (instace == null) { 52 | instace = new KeyCloakConfig(context); 53 | } 54 | return instace; 55 | } 56 | 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/KeycloakAuthenticationActivity.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider; 2 | 3 | import android.accounts.Account; 4 | import android.accounts.AccountAuthenticatorActivity; 5 | import android.accounts.AccountAuthenticatorResponse; 6 | import android.accounts.AccountManager; 7 | import android.accounts.AccountManagerCallback; 8 | import android.accounts.AccountManagerFuture; 9 | import android.app.Activity; 10 | import android.app.Fragment; 11 | import android.app.LoaderManager; 12 | import android.content.Context; 13 | import android.content.Loader; 14 | import android.os.Bundle; 15 | import android.util.Log; 16 | import android.view.LayoutInflater; 17 | import android.view.View; 18 | import android.view.ViewGroup; 19 | import android.webkit.WebView; 20 | import android.webkit.WebViewClient; 21 | 22 | import com.google.gson.Gson; 23 | 24 | import org.keycloak.keycloakaccountprovider.token.AccessTokenExchangeLoader; 25 | import org.keycloak.keycloakaccountprovider.util.IOUtils; 26 | 27 | import java.security.Key; 28 | 29 | 30 | public class KeycloakAuthenticationActivity extends AccountAuthenticatorActivity implements LoaderManager.LoaderCallbacks { 31 | 32 | private KeyCloak kc; 33 | private static final String ACCESS_TOKEN_KEY = "accessToken"; 34 | 35 | @Override 36 | protected void onCreate(Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | setContentView(R.layout.activity_my); 39 | 40 | kc = new KeyCloak(this); 41 | Account[] accounts = AccountManager.get(this).getAccountsByType(KeyCloak.ACCOUNT_TYPE); 42 | if (savedInstanceState == null) { 43 | getFragmentManager().beginTransaction() 44 | .add(R.id.container, new PlaceholderFragment()) 45 | .commit(); 46 | } 47 | } 48 | 49 | @Override 50 | public Loader onCreateLoader(int i, Bundle bundle) { 51 | return new AccessTokenExchangeLoader(this, bundle.getString(ACCESS_TOKEN_KEY)); 52 | } 53 | 54 | @Override 55 | public void onLoadFinished(Loader keyCloakAccountLoader, KeyCloakAccount keyCloakAccount) { 56 | AccountAuthenticatorResponse response = getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); 57 | String keyCloakAccountJson = new Gson().toJson(keyCloakAccount); 58 | final Bundle accountBundle = new Bundle(); 59 | accountBundle.putString(KeyCloak.ACCOUNT_KEY, keyCloakAccountJson); 60 | 61 | 62 | final AccountManager am = AccountManager.get(this); 63 | final Account androidAccount = new Account(keyCloakAccount.getPreferredUsername(), KeyCloak.ACCOUNT_TYPE); 64 | Account[] accounts = am.getAccountsByType(KeyCloak.ACCOUNT_TYPE); 65 | for (Account existingAccount : accounts) { 66 | if (existingAccount.name == androidAccount.name) { 67 | am.setUserData(androidAccount, KeyCloak.ACCOUNT_KEY, keyCloakAccountJson); 68 | if (response != null) { 69 | response.onResult(accountBundle); 70 | } 71 | finish(); 72 | } 73 | } 74 | 75 | am.removeAccount(androidAccount, new AccountManagerCallback() { 76 | @Override 77 | public void run(AccountManagerFuture accountManagerFuture) { 78 | boolean result = am.addAccountExplicitly(androidAccount, null, accountBundle); 79 | 80 | } 81 | }, null); 82 | 83 | 84 | if (response != null) { 85 | response.onResult(accountBundle); 86 | } 87 | finish(); 88 | 89 | 90 | } 91 | 92 | @Override 93 | public void onLoaderReset(Loader keyCloakAccountLoader) { 94 | 95 | } 96 | 97 | 98 | /** 99 | * A placeholder fragment containing a simple view. 100 | */ 101 | public static class PlaceholderFragment extends Fragment { 102 | 103 | private KeyCloak kc; 104 | private WebView webView; 105 | 106 | public PlaceholderFragment() { 107 | 108 | } 109 | 110 | @Override 111 | public void onAttach(Context activity) { 112 | super.onAttach(activity); 113 | if (kc == null) { 114 | kc = new KeyCloak(activity); 115 | } 116 | } 117 | 118 | @Override 119 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 120 | Bundle savedInstanceState) { 121 | View rootView = inflater.inflate(R.layout.keycloak_login_fragment, container, false); 122 | webView = (WebView) rootView.findViewById(R.id.webview); 123 | webView.setWebViewClient(new WebViewClient() { 124 | @Override 125 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 126 | 127 | if (url.contains("code=")) { 128 | final String token = IOUtils.fetchToken(url); 129 | Log.d("TOKEN", token); 130 | 131 | Bundle data = new Bundle(); 132 | data.putString(ACCESS_TOKEN_KEY, token); 133 | getLoaderManager().initLoader(1, data, (LoaderManager.LoaderCallbacks) (getActivity())).forceLoad(); 134 | 135 | return true; 136 | } 137 | 138 | return false; 139 | } 140 | 141 | 142 | }); 143 | webView.loadUrl(kc.createLoginUrl()); 144 | return rootView; 145 | } 146 | 147 | @Override 148 | public void onStart() { 149 | super.onStart(); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/token/AccessTokenExchangeLoader.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider.token; 2 | 3 | import android.content.AsyncTaskLoader; 4 | import android.content.Context; 5 | import android.content.Loader; 6 | import android.util.Base64; 7 | import android.util.Pair; 8 | 9 | 10 | import org.json.JSONObject; 11 | import org.keycloak.keycloakaccountprovider.KeyCloak; 12 | import org.keycloak.keycloakaccountprovider.KeyCloakAccount; 13 | import org.keycloak.keycloakaccountprovider.util.IOUtils; 14 | import org.keycloak.keycloakaccountprovider.util.TokenExchangeUtils; 15 | 16 | import java.io.BufferedOutputStream; 17 | import java.io.OutputStream; 18 | import java.io.UnsupportedEncodingException; 19 | import java.net.HttpURLConnection; 20 | import java.net.MalformedURLException; 21 | import java.net.URL; 22 | import java.net.URLConnection; 23 | import java.net.URLEncoder; 24 | import java.nio.charset.Charset; 25 | import java.util.Date; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | /** 30 | * Created by Summers on 9/13/2014. 31 | */ 32 | public class AccessTokenExchangeLoader extends AsyncTaskLoader { 33 | 34 | 35 | private final KeyCloak kc; 36 | private final String accessToken; 37 | private KeyCloakAccount account; 38 | 39 | public AccessTokenExchangeLoader(Context context, String accessToken) { 40 | super(context); 41 | this.kc = new KeyCloak(context); 42 | this.accessToken = accessToken; 43 | } 44 | 45 | @Override 46 | public KeyCloakAccount loadInBackground() { 47 | return TokenExchangeUtils.exchangeForAccessCode(accessToken, kc); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/util/IOUtils.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider.util; 2 | 3 | import android.net.Uri; 4 | import android.util.Log; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.io.InputStreamReader; 10 | import java.io.UnsupportedEncodingException; 11 | import java.net.URLEncoder; 12 | 13 | 14 | public class IOUtils { 15 | public static String getString(InputStream fileStream) { 16 | InputStreamReader inputreader = new InputStreamReader(fileStream); 17 | BufferedReader buffreader = new BufferedReader(inputreader); 18 | String line; 19 | StringBuilder text = new StringBuilder(); 20 | 21 | try { 22 | while (( line = buffreader.readLine()) != null) { 23 | text.append(line); 24 | text.append('\n'); 25 | } 26 | } catch (IOException e) { 27 | return null; 28 | } 29 | return text.toString(); 30 | } 31 | 32 | public static void close(InputStream fileStream) { 33 | try { 34 | fileStream.close(); 35 | } catch (IOException e) { 36 | Log.e("IOUtils", e.getMessage(), e); 37 | } 38 | } 39 | 40 | public static String encodeURIComponent(String string) { 41 | try { 42 | return URLEncoder.encode(string, "UTF-8"); 43 | } catch (UnsupportedEncodingException e) { 44 | throw new RuntimeException(e); 45 | } 46 | } 47 | 48 | public static String fetchToken(String url) { 49 | return fetchURLParam(url, "code"); 50 | } 51 | public static String fetchError(String url) { 52 | return fetchURLParam(url, "error"); 53 | } 54 | public static String fetchURLParam(String url, String param) { 55 | Uri uri = Uri.parse(url); 56 | return uri.getQueryParameter(param); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/util/ObjectUtils.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider.util; 2 | 3 | import org.json.JSONObject; 4 | 5 | /** 6 | * Created by Summers on 9/13/2014. 7 | */ 8 | public class ObjectUtils { 9 | public static T getOrDefault(T mayBeNull, T defaultIfNull) { 10 | if (mayBeNull != null) { 11 | return mayBeNull; 12 | } else { 13 | return defaultIfNull; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/org/keycloak/keycloakaccountprovider/util/TokenExchangeUtils.java: -------------------------------------------------------------------------------- 1 | package org.keycloak.keycloakaccountprovider.util; 2 | 3 | import android.accounts.NetworkErrorException; 4 | import android.util.Base64; 5 | import android.util.Log; 6 | 7 | import org.jboss.aerogear.android.pipe.http.HeaderAndBody; 8 | import org.jboss.aerogear.android.pipe.http.HttpException; 9 | import org.jboss.aerogear.android.pipe.http.HttpRestProvider; 10 | import org.json.JSONException; 11 | import org.json.JSONObject; 12 | import org.keycloak.keycloakaccountprovider.KeyCloak; 13 | import org.keycloak.keycloakaccountprovider.KeyCloakAccount; 14 | 15 | import java.io.UnsupportedEncodingException; 16 | import java.net.URL; 17 | import java.net.URLEncoder; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | public final class TokenExchangeUtils { 22 | 23 | private static final String TAG = TokenExchangeUtils.class.getSimpleName(); 24 | 25 | private TokenExchangeUtils() { 26 | } 27 | 28 | public static KeyCloakAccount exchangeForAccessCode(String accessToken, KeyCloak kc) { 29 | 30 | final Map data = new HashMap(); 31 | data.put("code", accessToken); 32 | data.put("client_id", kc.getClientId()); 33 | data.put("redirect_uri", kc.getRedirectUri()); 34 | 35 | data.put("grant_type", "authorization_code"); 36 | if (kc.getClientSecret() != null) { 37 | data.put("client_secret", kc.getClientSecret()); 38 | } 39 | 40 | try { 41 | URL accessTokenEndpoint = new URL(kc.getBaseURL() + "/protocol/openid-connect/token"); 42 | 43 | if (kc.getClientSecret() == null) { 44 | accessTokenEndpoint = new URL(kc.getBaseURL() + "/protocol/openid-connect/token&client_id=" + IOUtils.encodeURIComponent(kc.getClientId())); 45 | } 46 | 47 | String bodyString = getBody(data); 48 | 49 | HttpRestProvider provider = getHttpProvider(kc, accessTokenEndpoint); 50 | 51 | HeaderAndBody result = provider.post(bodyString); 52 | 53 | JSONObject accessResponse = handleResult(result); 54 | KeyCloakAccount account = new KeyCloakAccount(); 55 | account.extractTokenProperties(accessResponse); 56 | 57 | return account; 58 | } catch (Exception e) { 59 | throw new RuntimeException(e); 60 | } 61 | 62 | 63 | } 64 | 65 | public static KeyCloakAccount refreshToken(KeyCloakAccount account, KeyCloak kc) throws NetworkErrorException { 66 | final Map data = new HashMap(); 67 | data.put("refresh_token", account.getRefreshToken()); 68 | data.put("grant_type", "refresh_token"); 69 | 70 | 71 | try { 72 | URL refreshTokenEndpoint = new URL(kc.getBaseURL() + "/protocol/openid-connect/token/refresh"); 73 | 74 | if (kc.getClientSecret() == null) { 75 | refreshTokenEndpoint = new URL(kc.getBaseURL() + "/protocol/openid-connect/token/refresh&client_id=" + IOUtils.encodeURIComponent(kc.getClientId())); 76 | } 77 | 78 | String bodyString = getBody(data); 79 | 80 | HttpRestProvider provider = getHttpProvider(kc, refreshTokenEndpoint); 81 | 82 | HeaderAndBody result = provider.post(bodyString); 83 | 84 | JSONObject accessResponse = handleResult(result); 85 | account.extractTokenProperties(accessResponse); 86 | 87 | return account; 88 | } catch (HttpException e) { 89 | throw e; 90 | } catch (Exception e) { 91 | throw new NetworkErrorException(e); 92 | } 93 | } 94 | 95 | private static JSONObject handleResult(HeaderAndBody result) { 96 | byte[] bodyData = result.getBody(); 97 | String body = new String(bodyData); 98 | try { 99 | return new JSONObject(body); 100 | } catch (JSONException e) { 101 | Log.e(TAG, e.getMessage(), e); 102 | throw new RuntimeException(e); 103 | } 104 | } 105 | 106 | private static String getBody(Map data) { 107 | final StringBuilder bodyBuilder = new StringBuilder(); 108 | final String formTemplate = "%s=%s"; 109 | 110 | String amp = ""; 111 | for (Map.Entry entry : data.entrySet()) { 112 | bodyBuilder.append(amp); 113 | try { 114 | bodyBuilder.append(String.format(formTemplate, entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8"))); 115 | } catch (UnsupportedEncodingException e) { 116 | throw new RuntimeException(e); 117 | } 118 | amp = "&"; 119 | } 120 | 121 | return bodyBuilder.toString(); 122 | 123 | } 124 | 125 | private static HttpRestProvider getHttpProvider(KeyCloak kc, URL url) { 126 | HttpRestProvider provider = new HttpRestProvider(url); 127 | 128 | provider.setDefaultHeader("Content-Type", "application/x-www-form-urlencoded"); 129 | 130 | if (kc.getClientSecret() != null) { 131 | try { 132 | provider.setDefaultHeader("Authorization", "Basic " + Base64.encodeToString((kc.getClientId() + ":" + kc.getClientSecret()).getBytes("UTF-8"), Base64.DEFAULT | Base64.NO_WRAP)); 133 | } catch (UnsupportedEncodingException e) { 134 | Log.e(TAG, e.getMessage(), e); 135 | throw new RuntimeException(e); 136 | } 137 | } 138 | return provider; 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/keycloak_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-hdpi/keycloak_logo.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/login_bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-xhdpi/login_bg.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/secondsun/keycloak-android-authenticator/9c996e38d585f4fc5ecdd225d51838063525c682/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/layout-w600dp-land/keycloak_login_fragment_old.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | 16 | 17 | 22 | 23 | 31 | 32 | 41 | 42 | 48 | 49 | 57 | 58 | 65 | 66 | 76 | 77 |