├── LICENSE ├── README.md ├── credentials-quickstart ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── example │ │ │ └── credentialsbasic │ │ │ ├── MainActivity.java │ │ │ └── MockServer.java │ │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ├── credentials-signin ├── .gitignore ├── LICENSE ├── README.md ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── example │ │ │ └── credentialssignin │ │ │ └── MainActivity.java │ │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle └── sms-verification ├── android ├── .gitignore ├── README.md ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── samples │ │ │ └── smartlock │ │ │ └── sms_verify │ │ │ └── ExampleInstrumentedTest.java │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── google │ │ │ │ └── samples │ │ │ │ └── smartlock │ │ │ │ └── sms_verify │ │ │ │ ├── ApiHelper.java │ │ │ │ ├── AppSignatureHelper.java │ │ │ │ ├── PhoneNumberVerifier.java │ │ │ │ ├── PrefsHelper.java │ │ │ │ └── ui │ │ │ │ ├── AppCompatPreferenceActivity.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── PhoneNumberActivity.java │ │ │ │ ├── ResetActivity.java │ │ │ │ ├── SettingsActivity.java │ │ │ │ ├── SignUpActivity.java │ │ │ │ ├── StatusFragment.java │ │ │ │ └── VerifyingFragment.java │ │ └── res │ │ │ ├── drawable-hdpi │ │ │ └── ic_not_interested_black_24dp.png │ │ │ ├── drawable-mdpi │ │ │ └── ic_not_interested_black_24dp.png │ │ │ ├── drawable-xhdpi │ │ │ └── ic_not_interested_black_24dp.png │ │ │ ├── drawable-xxhdpi │ │ │ └── ic_not_interested_black_24dp.png │ │ │ ├── drawable-xxxhdpi │ │ │ └── ic_not_interested_black_24dp.png │ │ │ ├── drawable │ │ │ ├── ic_info_black_24dp.xml │ │ │ ├── ic_notifications_black_24dp.xml │ │ │ └── ic_sync_black_24dp.xml │ │ │ ├── layout │ │ │ ├── activity_main.xml │ │ │ ├── activity_phone_number.xml │ │ │ ├── activity_sign_up.xml │ │ │ ├── fragment_status.xml │ │ │ └── fragment_verifiying.xml │ │ │ ├── menu │ │ │ └── app_menu.xml │ │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── values-v21 │ │ │ └── styles.xml │ │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ │ ├── values │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ │ └── xml │ │ │ └── pref_main.xml │ │ └── test │ │ └── java │ │ └── com │ │ └── google │ │ └── samples │ │ └── smartlock │ │ └── sms_verify │ │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshots │ ├── MainActivity.png │ └── SignUpActivity.png └── settings.gradle └── bin └── sms_retriever_hash_v9.sh /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Google, LLC 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android-credentials 2 | This repo has been migrated to [github.com/android/identity][1]. Please check that repo for future updates. Thank you! 3 | 4 | [1]: https://github.com/android/identity 5 | 6 | -------------------------------------------------------------------------------- /credentials-quickstart/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | .DS_Store 4 | build/ 5 | .idea 6 | *.iml 7 | app/build 8 | *.apk 9 | *.aar 10 | 11 | -------------------------------------------------------------------------------- /credentials-quickstart/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 9 | 10 | * If you are an individual writing original source code and you're sure you 11 | own the intellectual property, then you'll need to sign an [individual CLA] 12 | (https://cla.developers.google.com). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA] 15 | (https://cla.developers.google.com). 16 | 17 | Follow either of the two links above to access the appropriate CLA and 18 | instructions for how to sign and return it. Once we receive it, we'll be able to 19 | accept your pull requests. 20 | 21 | ## Contributing A Patch 22 | 23 | 1. Submit an issue describing your proposed change to the repo in question. 24 | 1. The repo owner will respond to your issue promptly. 25 | 1. If your proposed change is accepted, and you haven't already done so, sign a 26 | Contributor License Agreement (see details above). 27 | 1. Fork the desired repo, develop and test your code changes. 28 | 1. Ensure that your code adheres to the existing style in the sample to which 29 | you are contributing. Refer to the 30 | [Android Code Style Guide] 31 | (https://source.android.com/source/code-style.html) for the 32 | recommended coding standards for this organization. 33 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 34 | 1. Submit a pull request. 35 | -------------------------------------------------------------------------------- /credentials-quickstart/README.md: -------------------------------------------------------------------------------- 1 | # credentials-quickstart 2 | 3 | ## Get Started 4 | This is a quickstart sample for the Android Credentials API, which is part of Smartlock for Passwords on Android. Visit the following link for more information: 5 | 6 | https://developers.google.com/identity/smartlock-passwords/android/get-started 7 | 8 | ## Optional 9 | ### Determining the SHA512 Hash of Your Keystore 10 | This application demonstrates the use and verification of ID Tokens retrieved from Credentials which 11 | is a great way to authenticate your client applications with your backend server. You will need to 12 | determine the SHA512 hash of your application and update `MockServer.java` accordingly. 13 | 14 | Run the quickstart and successfully load a credential. Then in the `adb logcat` logs, search for 15 | "IDToken Audience". There should be a log message containing the audience of the ID Token in the 16 | loaded credential which will have the following form: 17 | ``` 18 | android://@ 19 | ``` 20 | Copy the SHA512 from that log message and update `MockServer.java`. 21 | 22 | For example for this log message: 23 | ``` 24 | D/MockServer: IDToken Audience:android://_6Gx0cvSsFgTLF3NJCJIUs9BDaZMdSnXosAbPYYLiTqNWvR0IMc0C-UQehhmDu8t8l4fd3tEI6TlVCoqybFV5g==@com.google.example.credentialsbasic 25 | ``` 26 | The SHA512 hash is 27 | ``` 28 | _6Gx0cvSsFgTLF3NJCJIUs9BDaZMdSnXosAbPYYLiTqNWvR0IMc0C-UQehhmDu8t8l4fd3tEI6TlVCoqybFV5g== 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /credentials-quickstart/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 27 5 | buildToolsVersion "27.0.2" 6 | 7 | defaultConfig { 8 | applicationId "com.google.example.credentialsbasic" 9 | minSdkVersion 17 10 | targetSdkVersion 27 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 'com.android.support:appcompat-v7:27.0.2' 24 | 25 | compile 'com.google.android.gms:play-services-auth:11.8.0' 26 | 27 | compile 'com.google.api-client:google-api-client:1.22.0' 28 | } 29 | -------------------------------------------------------------------------------- /credentials-quickstart/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 /usr/local/google/home/samstern/android-sdk-linux/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 | -------------------------------------------------------------------------------- /credentials-quickstart/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 21 | 22 | 28 | 29 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /credentials-quickstart/app/src/main/java/com/google/example/credentialsbasic/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.example.credentialsbasic; 17 | 18 | import android.app.PendingIntent; 19 | import android.content.Intent; 20 | import android.content.IntentSender; 21 | import android.os.Bundle; 22 | import android.support.annotation.NonNull; 23 | import android.support.v7.app.AppCompatActivity; 24 | import android.support.v7.widget.Toolbar; 25 | import android.util.Log; 26 | import android.view.View; 27 | import android.widget.CheckBox; 28 | import android.widget.EditText; 29 | import android.widget.Toast; 30 | 31 | import com.google.android.gms.auth.api.credentials.Credential; 32 | import com.google.android.gms.auth.api.credentials.CredentialPickerConfig; 33 | import com.google.android.gms.auth.api.credentials.CredentialRequest; 34 | import com.google.android.gms.auth.api.credentials.CredentialRequestResponse; 35 | import com.google.android.gms.auth.api.credentials.Credentials; 36 | import com.google.android.gms.auth.api.credentials.CredentialsClient; 37 | import com.google.android.gms.auth.api.credentials.CredentialsOptions; 38 | import com.google.android.gms.auth.api.credentials.HintRequest; 39 | import com.google.android.gms.auth.api.credentials.IdToken; 40 | import com.google.android.gms.auth.api.credentials.IdentityProviders; 41 | import com.google.android.gms.common.api.ApiException; 42 | import com.google.android.gms.common.api.CommonStatusCodes; 43 | import com.google.android.gms.common.api.ResolvableApiException; 44 | import com.google.android.gms.tasks.OnCompleteListener; 45 | import com.google.android.gms.tasks.Task; 46 | 47 | /** 48 | * A minimal example of saving and loading username/password credentials from the Credentials API. 49 | * @author samstern@google.com 50 | */ 51 | public class MainActivity extends AppCompatActivity implements 52 | View.OnClickListener { 53 | 54 | private static final String TAG = MainActivity.class.getSimpleName(); 55 | private static final String KEY_IS_RESOLVING = "is_resolving"; 56 | private static final int RC_SAVE = 1; 57 | private static final int RC_HINT = 2; 58 | private static final int RC_READ = 3; 59 | 60 | private EditText mEmailField; 61 | private EditText mPasswordField; 62 | 63 | private CredentialsClient mCredentialsClient; 64 | private Credential mCurrentCredential; 65 | private boolean mIsResolving = false; 66 | 67 | @Override 68 | protected void onCreate(Bundle savedInstanceState) { 69 | super.onCreate(savedInstanceState); 70 | setContentView(R.layout.activity_main); 71 | 72 | setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); 73 | 74 | // Fields 75 | mEmailField = findViewById(R.id.edit_text_email); 76 | mPasswordField = findViewById(R.id.edit_text_password); 77 | 78 | // Buttons 79 | findViewById(R.id.button_save_credential).setOnClickListener(this); 80 | findViewById(R.id.button_load_credentials).setOnClickListener(this); 81 | findViewById(R.id.button_load_hint).setOnClickListener(this); 82 | findViewById(R.id.button_delete_loaded_credential).setOnClickListener(this); 83 | 84 | // Instance state 85 | if (savedInstanceState != null) { 86 | mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING); 87 | } 88 | 89 | // Instantiate client for interacting with the credentials API. For this demo 90 | // application we forcibly enable the SmartLock save dialog, which is sometimes 91 | // disabled when it would conflict with the Android autofill API. 92 | CredentialsOptions options = new CredentialsOptions.Builder() 93 | .forceEnableSaveDialog() 94 | .build(); 95 | mCredentialsClient = Credentials.getClient(this, options); 96 | } 97 | 98 | @Override 99 | public void onStart() { 100 | super.onStart(); 101 | 102 | // Attempt auto-sign in. 103 | if (!mIsResolving) { 104 | requestCredentials(); 105 | } 106 | } 107 | 108 | @Override 109 | protected void onSaveInstanceState(Bundle outState) { 110 | super.onSaveInstanceState(outState); 111 | outState.putBoolean(KEY_IS_RESOLVING, mIsResolving); 112 | } 113 | 114 | @Override 115 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 116 | super.onActivityResult(requestCode, resultCode, data); 117 | Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data); 118 | hideProgress(); 119 | 120 | switch (requestCode) { 121 | case RC_HINT: 122 | // Drop into handling for RC_READ 123 | case RC_READ: 124 | if (resultCode == RESULT_OK) { 125 | boolean isHint = (requestCode == RC_HINT); 126 | Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY); 127 | processRetrievedCredential(credential, isHint); 128 | } else { 129 | Log.e(TAG, "Credential Read: NOT OK"); 130 | showToast("Credential Read Failed"); 131 | } 132 | 133 | mIsResolving = false; 134 | break; 135 | case RC_SAVE: 136 | if (resultCode == RESULT_OK) { 137 | Log.d(TAG, "Credential Save: OK"); 138 | showToast("Credential Save Success"); 139 | } else { 140 | Log.e(TAG, "Credential Save: NOT OK"); 141 | showToast("Credential Save Failed"); 142 | } 143 | 144 | mIsResolving = false; 145 | break; 146 | } 147 | } 148 | 149 | /** 150 | * Called when the save button is clicked. Reads the entries in the email and password 151 | * fields and attempts to save a new Credential to the Credentials API. 152 | */ 153 | private void saveCredentialClicked() { 154 | String email = mEmailField.getText().toString(); 155 | String password = mPasswordField.getText().toString(); 156 | 157 | // Create a Credential with the user's email as the ID and storing the password. We 158 | // could also add 'Name' and 'ProfilePictureURL' but that is outside the scope of this 159 | // minimal sample. 160 | Log.d(TAG, "Saving Credential:" + email + ":" + anonymizePassword(password)); 161 | final Credential credential = new Credential.Builder(email) 162 | .setPassword(password) 163 | .build(); 164 | 165 | showProgress(); 166 | 167 | // NOTE: this method unconditionally saves the Credential built, even if all the fields 168 | // are blank or it is invalid in some other way. In a real application you should contact 169 | // your app's back end and determine that the credential is valid before saving it to the 170 | // Credentials backend. 171 | showProgress(); 172 | 173 | mCredentialsClient.save(credential).addOnCompleteListener( 174 | new OnCompleteListener() { 175 | @Override 176 | public void onComplete(@NonNull Task task) { 177 | if (task.isSuccessful()) { 178 | showToast("Credential saved."); 179 | hideProgress(); 180 | return; 181 | } 182 | 183 | Exception e = task.getException(); 184 | if (e instanceof ResolvableApiException) { 185 | // The first time a credential is saved, the user is shown UI 186 | // to confirm the action. This requires resolution. 187 | ResolvableApiException rae = (ResolvableApiException) e; 188 | resolveResult(rae, RC_SAVE); 189 | } else { 190 | // Save failure cannot be resolved. 191 | Log.w(TAG, "Save failed.", e); 192 | showToast("Credential Save Failed"); 193 | hideProgress(); 194 | } 195 | } 196 | }); 197 | } 198 | 199 | /** 200 | * Called when the Load Credentials button is clicked. Attempts to read the user's saved 201 | * Credentials from the Credentials API. This may show UX, such as a credential picker 202 | * or an account picker. 203 | * 204 | * Note: in a normal application loading credentials should happen without explicit user 205 | * action, this is only connected to a 'Load Credentials' button for easier demonstration 206 | * in this sample. Make sure not to load credentials automatically if the user has clicked 207 | * a "sign out" button in your application in order to avoid a sign-in loop. You can do this 208 | * with the function Auth.CredentialsApi.disableAuthSignIn(...). 209 | */ 210 | private void loadCredentialsClicked() { 211 | requestCredentials(); 212 | } 213 | 214 | /** 215 | * Called when the Load Hints button is clicked. Requests a Credential "hint" which will 216 | * be the basic profile information and an ID token for an account on the device. This is useful 217 | * to auto-fill sign-up forms with an email address, picture, and name or to do password-free 218 | * authentication with a server by providing an ID Token. 219 | */ 220 | private void loadHintClicked() { 221 | HintRequest hintRequest = new HintRequest.Builder() 222 | .setHintPickerConfig(new CredentialPickerConfig.Builder() 223 | .setShowCancelButton(true) 224 | .build()) 225 | .setIdTokenRequested(shouldRequestIdToken()) 226 | .setEmailAddressIdentifierSupported(true) 227 | .setAccountTypes(IdentityProviders.GOOGLE) 228 | .build(); 229 | 230 | ; 231 | PendingIntent intent = mCredentialsClient.getHintPickerIntent(hintRequest); 232 | try { 233 | startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0); 234 | mIsResolving = true; 235 | } catch (IntentSender.SendIntentException e) { 236 | Log.e(TAG, "Could not start hint picker Intent", e); 237 | mIsResolving = false; 238 | } 239 | } 240 | 241 | /** 242 | * Request Credentials from the Credentials API. 243 | */ 244 | private void requestCredentials() { 245 | // Request all of the user's saved username/password credentials. We are not using 246 | // setAccountTypes so we will not load any credentials from other Identity Providers. 247 | CredentialRequest request = new CredentialRequest.Builder() 248 | .setPasswordLoginSupported(true) 249 | .setIdTokenRequested(shouldRequestIdToken()) 250 | .build(); 251 | 252 | showProgress(); 253 | 254 | mCredentialsClient.request(request).addOnCompleteListener( 255 | new OnCompleteListener() { 256 | @Override 257 | public void onComplete(@NonNull Task task) { 258 | hideProgress(); 259 | 260 | if (task.isSuccessful()) { 261 | // Successfully read the credential without any user interaction, this 262 | // means there was only a single credential and the user has auto 263 | // sign-in enabled. 264 | processRetrievedCredential(task.getResult().getCredential(), false); 265 | return; 266 | } 267 | 268 | Exception e = task.getException(); 269 | if (e instanceof ResolvableApiException) { 270 | // This is most likely the case where the user has multiple saved 271 | // credentials and needs to pick one. This requires showing UI to 272 | // resolve the read request. 273 | ResolvableApiException rae = (ResolvableApiException) e; 274 | resolveResult(rae, RC_READ); 275 | return; 276 | } 277 | 278 | if (e instanceof ApiException) { 279 | ApiException ae = (ApiException) e; 280 | if (ae.getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED) { 281 | // This means only a hint is available, but we are handling that 282 | // elsewhere so no need to act here. 283 | } else { 284 | Log.w(TAG, "Unexpected status code: " + ae.getStatusCode()); 285 | } 286 | } 287 | } 288 | }); 289 | } 290 | 291 | /** 292 | * Called when the delete credentials button is clicked. This deletes the last Credential 293 | * that was loaded using the load button. 294 | */ 295 | private void deleteLoadedCredentialClicked() { 296 | if (mCurrentCredential == null) { 297 | showToast("Error: no credential to delete"); 298 | return; 299 | } 300 | 301 | showProgress(); 302 | 303 | mCredentialsClient.delete(mCurrentCredential).addOnCompleteListener( 304 | new OnCompleteListener() { 305 | @Override 306 | public void onComplete(@NonNull Task task) { 307 | hideProgress(); 308 | 309 | if (task.isSuccessful()) { 310 | // Credential delete succeeded, disable the delete button because we 311 | // cannot delete the same credential twice. Clear text fields. 312 | showToast("Credential Delete Success"); 313 | ((EditText) findViewById(R.id.edit_text_email)).setText(""); 314 | ((EditText) findViewById(R.id.edit_text_password)).setText(""); 315 | mCurrentCredential = null; 316 | } else { 317 | // Credential deletion either failed or was cancelled, this operation 318 | // never gives a 'resolution' so we can display the failure message 319 | // immediately. 320 | Log.e(TAG, "Credential Delete: NOT OK", task.getException()); 321 | showToast("Credential Delete Failed"); 322 | } 323 | } 324 | }); 325 | } 326 | 327 | /** 328 | * Attempt to resolve a non-successful result from an asynchronous request. 329 | * @param rae the ResolvableApiException to resolve. 330 | * @param requestCode the request code to use when starting an Activity for result, 331 | * this will be passed back to onActivityResult. 332 | */ 333 | private void resolveResult(ResolvableApiException rae, int requestCode) { 334 | // We don't want to fire multiple resolutions at once since that can result 335 | // in stacked dialogs after rotation or another similar event. 336 | if (mIsResolving) { 337 | Log.w(TAG, "resolveResult: already resolving."); 338 | return; 339 | } 340 | 341 | Log.d(TAG, "Resolving: " + rae); 342 | try { 343 | rae.startResolutionForResult(MainActivity.this, requestCode); 344 | mIsResolving = true; 345 | } catch (IntentSender.SendIntentException e) { 346 | Log.e(TAG, "STATUS: Failed to send resolution.", e); 347 | hideProgress(); 348 | } 349 | } 350 | 351 | /** 352 | * Process a Credential object retrieved from a successful request. 353 | * @param credential the Credential to process. 354 | * @param isHint true if the Credential is hint-only, false otherwise. 355 | */ 356 | private void processRetrievedCredential(Credential credential, boolean isHint) { 357 | Log.d(TAG, "Credential Retrieved: " + credential.getId() + ":" + 358 | anonymizePassword(credential.getPassword())); 359 | 360 | // If the Credential is not a hint, we should store it an enable the delete button. 361 | // If it is a hint, skip this because a hint cannot be deleted. 362 | if (!isHint) { 363 | showToast("Credential Retrieved"); 364 | mCurrentCredential = credential; 365 | findViewById(R.id.button_delete_loaded_credential).setEnabled(true); 366 | } else { 367 | showToast("Credential Hint Retrieved"); 368 | } 369 | 370 | mEmailField.setText(credential.getId()); 371 | mPasswordField.setText(credential.getPassword()); 372 | 373 | if (!credential.getIdTokens().isEmpty()) { 374 | IdToken idToken = credential.getIdTokens().get(0); 375 | 376 | // For the purposes of this sample we are using a background service in place of a real 377 | // web server. The client sends the Id Token to the server which uses the Google 378 | // APIs Client Library for Java to verify the token and gain a signed assertion 379 | // of the user's email address. This can be used to confirm the user's identity 380 | // and sign the user in even without providing a password. 381 | Intent intent = new Intent(this, MockServer.class) 382 | .putExtra(MockServer.EXTRA_IDTOKEN, idToken.getIdToken()); 383 | startService(intent); 384 | } else { 385 | // This state is reached if non-Google accounts are added to Gmail: 386 | // https://support.google.com/mail/answer/6078445 387 | Log.d(TAG, "Credential does not contain ID Tokens."); 388 | } 389 | } 390 | 391 | /** 392 | * Determine if we should request an ID token with Hints/Credentials. The default behavior 393 | * is to not request an ID token (for speed purposes) but by setting this value to true 394 | * an ID token will be returned with Hints/Credentials when possible. 395 | */ 396 | private boolean shouldRequestIdToken() { 397 | return ((CheckBox) findViewById(R.id.checkbox_request_idtoken)).isChecked(); 398 | } 399 | 400 | /** Make a password into asterisks of the right length, for logging. **/ 401 | private String anonymizePassword(String password) { 402 | if (password == null) { 403 | return "null"; 404 | } 405 | 406 | StringBuilder sb = new StringBuilder(); 407 | for (int i = 0; i < password.length(); i++) { 408 | sb.append('*'); 409 | } 410 | return sb.toString(); 411 | } 412 | 413 | /** Display a short Toast message **/ 414 | private void showToast(String msg) { 415 | Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 416 | } 417 | 418 | /** Show progress spinner and disable buttons **/ 419 | private void showProgress() { 420 | findViewById(R.id.progress_bar).setVisibility(View.VISIBLE); 421 | 422 | // Disable all buttons while progress indicator shows. 423 | setViewsEnabled(false, R.id.button_load_credentials, R.id.button_load_hint, 424 | R.id.button_save_credential, R.id.button_delete_loaded_credential); 425 | } 426 | 427 | /** Hide progress spinner and enable buttons **/ 428 | private void hideProgress() { 429 | findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); 430 | 431 | // Enable buttons once progress indicator is hidden. 432 | setViewsEnabled(true, R.id.button_load_credentials, R.id.button_load_hint, 433 | R.id.button_save_credential); 434 | } 435 | 436 | /** Enable or disable multiple views **/ 437 | private void setViewsEnabled(boolean enabled, int... ids) { 438 | for (int id : ids) { 439 | findViewById(id).setEnabled(enabled); 440 | } 441 | } 442 | 443 | @Override 444 | public void onClick(View v) { 445 | switch (v.getId()) { 446 | case R.id.button_save_credential: 447 | saveCredentialClicked(); 448 | break; 449 | case R.id.button_load_credentials: 450 | loadCredentialsClicked(); 451 | break; 452 | case R.id.button_load_hint: 453 | loadHintClicked(); 454 | break; 455 | case R.id.button_delete_loaded_credential: 456 | deleteLoadedCredentialClicked(); 457 | break; 458 | } 459 | } 460 | } 461 | -------------------------------------------------------------------------------- /credentials-quickstart/app/src/main/java/com/google/example/credentialsbasic/MockServer.java: -------------------------------------------------------------------------------- 1 | package com.google.example.credentialsbasic; 2 | 3 | import android.app.IntentService; 4 | import android.content.Intent; 5 | import android.util.Log; 6 | 7 | import com.google.android.gms.auth.api.credentials.IdentityProviders; 8 | import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; 9 | import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; 10 | import com.google.api.client.http.HttpTransport; 11 | import com.google.api.client.http.javanet.NetHttpTransport; 12 | import com.google.api.client.json.JsonFactory; 13 | import com.google.api.client.json.jackson2.JacksonFactory; 14 | 15 | import java.io.IOException; 16 | import java.security.GeneralSecurityException; 17 | import java.util.Arrays; 18 | 19 | /** 20 | * Mock server class to demonstrate how to use the Google APIs Client Library for Java 21 | * to verify an ID token obtained from a Credential. 22 | */ 23 | public class MockServer extends IntentService { 24 | 25 | public static final String TAG = "MockServer"; 26 | public static final String EXTRA_IDTOKEN = "id_token"; 27 | 28 | private static final String PACKAGE_NAME = "com.google.example.credentialsbasic"; 29 | private static final String SHA512_HASH = "YOUR_SHA512_HASH"; 30 | 31 | private static final HttpTransport transport = new NetHttpTransport(); 32 | private static final JsonFactory jsonFactory = new JacksonFactory(); 33 | 34 | // Verifier that checks that the token has the proper issuer and audience 35 | private static GoogleIdTokenVerifier verifier = 36 | new GoogleIdTokenVerifier.Builder(transport, jsonFactory) 37 | .setIssuer(IdentityProviders.GOOGLE) 38 | .setAudience(Arrays.asList(getAudienceString(SHA512_HASH, PACKAGE_NAME))) 39 | .build(); 40 | 41 | public MockServer() { 42 | super(TAG); 43 | } 44 | 45 | /** 46 | * Verify an ID token and log the email address and verification status. 47 | * @param idTokenString ID Token from a Credential. 48 | */ 49 | private static void verifyIdToken(String idTokenString) { 50 | // Print the audience to the logs 51 | logTokenAudience(idTokenString); 52 | 53 | try { 54 | // Verify ID Token 55 | GoogleIdToken idToken = verifier.verify(idTokenString); 56 | if (idToken == null) { 57 | Log.w(TAG, "ID Token Verification Failed, check the README for instructions."); 58 | return; 59 | } 60 | 61 | // Extract email address and verification 62 | GoogleIdToken.Payload payload = idToken.getPayload(); 63 | Log.d(TAG, "IdToken:" + payload.toPrettyString()); 64 | Log.d(TAG, "IdToken:Email:" + payload.getEmail()); 65 | Log.d(TAG, "IdToken:EmailVerified:" + payload.getEmailVerified()); 66 | } catch (GeneralSecurityException e) { 67 | Log.e(TAG, "verifyIdToken:GeneralSecurityException", e); 68 | } catch (IOException e) { 69 | Log.e(TAG, "verifyIdToken:IOException", e); 70 | } 71 | } 72 | 73 | /** 74 | * Print the audience of an unverified token string to the logs. 75 | * @param idTokenString the ID Token string. 76 | */ 77 | public static void logTokenAudience(String idTokenString) { 78 | try { 79 | GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, idTokenString); 80 | Log.d(TAG, "IDToken Audience:" + idToken.getPayload().getAudience()); 81 | } catch (IOException e) { 82 | Log.e(TAG, "IDToken Audience: Could not parse ID Token", e); 83 | } 84 | } 85 | 86 | /** 87 | * Determine the audience of the ID token based on the sha512 hash and the package name. 88 | * @param sha512Hash sha512 hash of the application, see README for instructions. 89 | * @param packageName package name of the application, 90 | */ 91 | private static String getAudienceString(String sha512Hash, String packageName) { 92 | String fmtString = "android://%s@%s"; 93 | return String.format(fmtString, sha512Hash, packageName); 94 | } 95 | 96 | @Override 97 | protected void onHandleIntent(Intent intent) { 98 | String idToken = intent.getStringExtra(EXTRA_IDTOKEN); 99 | if (idToken != null) { 100 | Log.d(TAG, "Processing ID Token:" + idToken); 101 | verifyIdToken(idToken); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /credentials-quickstart/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 16 | 22 | 23 | 31 | 32 | 41 | 42 | 43 | 44 | 54 | 55 | 64 | 65 | 73 | 74 |