项目作者: AmalH

项目描述 :
Example for implementing two factor authentication in Android using Twilio's Authy API and firebase. | TUTORIAL : https://pragmatictheories.tech/android-implementing-two-step-authentication-through-google-authenticator/
高级语言: Java
项目地址: git://github.com/AmalH/Android-2FA-with-Google-authenticator.git


Two-factor authentication in Android - Using Authy API

This is a sample for implementing two-factor authentication in Android using Authy API

Description

You can use this project and the following tutorials to implement:

  1. /** get auth creds from previous activity **/
  2. Bundle extras = getIntent().getExtras();
  3. if (extras != null) {
  4. userId= extras.getString("userId");
  5. }
  6. qrCodeCallUrl="https://api.authy.com/protected/json/users/"+userId+"/secret?api_key=CCb8fPiHfTdFp332cefjTuRjgMNprVOx";
  7. /** call authy api to get qr code **/
  8. JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,qrCodeCallUrl,null,
  9. new Response.Listener<JSONObject>() {
  10. @Override
  11. public void onResponse(JSONObject response) {
  12. try {
  13. String qrCodePath = response.getString("qr_code");
  14. /** set the imageView's src **/
  15. ImageView qrCodeImgVw = findViewById(R.id.qrCodeImgVw);
  16. Picasso.get().load(qrCodePath).into(qrCodeImgVw);
  17. } catch (JSONException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. },
  22. new Response.ErrorListener() {
  23. @Override
  24. public void onErrorResponse(VolleyError error) {
  25. Log.e("ERROR! ",error.getMessage());
  26. }
  27. });
  28. (AppSingleton.getInstance(getApplicationContext()).getRequestQueue()).add(jsObjRequest);
  29. /** pass the code provided by user to the Authy API to verify it **/
  30. (findViewById(R.id.confirmSignupBtn)).setOnClickListener(new View.OnClickListener() {
  31. @Override
  32. public void onClick(View v) {
  33. Statics.validateSecurityCode(((EditText)findViewById(R.id.validationCode)).getText().toString(),userId,QRCodeActivity.this,
  34. ((EditText)findViewById(R.id.validationCode)),((TextView)findViewById(R.id.errorTxt)));
  35. }
  36. });


  1. /*************************************************************************************************
  2. * 2FA using Authenticator app on this device *
  3. * **********************************************************************************************/
  4. (findViewById(R.id.authAppOnThisPhone)).setOnClickListener(new View.OnClickListener() {
  5. @Override
  6. public void onClick(View v) {
  7. Statics.usersTable.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
  8. @Override
  9. public void onDataChange(DataSnapshot dataSnapshot) {
  10. /** 1.Get user's creds! phone number included.. **/
  11. email = (dataSnapshot.getValue(User.class)).getEmailAddress();
  12. username = (dataSnapshot.getValue(User.class)).getFirstName()+" "+(dataSnapshot.getValue(User.class)).getLastName();
  13. phoneNumber = (dataSnapshot.getValue(User.class)).getPhoneNumber();
  14. countryCode = (dataSnapshot.getValue(User.class)).getPhoneCountryCode();
  15. addUserUrl = "https://api.authy.com/protected/json/users/new?user[email]="+email
  16. +"&user[cellphone]="+phoneNumber
  17. +"&user[country_code]="+countryCode+"&api_key=CCb8fPiHfTdFp332cefjTuRjgMNprVOx";
  18. /** 2.Add the user to the Authy API **/
  19. // post call for Authy api to add a user | response contains the added user's id
  20. JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,addUserUrl,null,
  21. new Response.Listener<JSONObject>() {
  22. @Override
  23. public void onResponse(JSONObject response) {
  24. Gson gson = new Gson();
  25. try {
  26. /** get the returned id **/
  27. JsonObject addedUser = gson.fromJson(response.getString("user"),JsonObject.class);
  28. addedUserId = (addedUser.get("id")).getAsString();
  29. //Toast.makeText(getApplicationContext(), "Res: "+addedUserId, Toast.LENGTH_LONG).show();
  30. /** 3.Call the Authy API to generate appropriate passcode
  31. * then open GoogleAuthenticator on this device to use it ! **/
  32. String uri = "otpauth://totp/AdsChain:" + email + "?secret=" + "811854" + "&issuer=AdsChain";
  33. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
  34. getContext().startActivity(intent);
  35. /** 4.Ask user for passcode and validate it **/
  36. AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
  37. ...
  38. ...
  39. alertDialog.setPositiveButton("Validate",
  40. new DialogInterface.OnClickListener() {
  41. public void onClick(DialogInterface dialog, int which) {
  42. /** call authy api to validate code provided by the user **/
  43. Statics.validateSecurityCode(input.getText().toString(),addedUserId,getContext());
  44. }
  45. });
  46. ...
  47. alertDialog.show();
  48. } catch (JSONException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. },
  53. new Response.ErrorListener() {
  54. @Override
  55. public void onErrorResponse(VolleyError error) {
  56. Log.e("ERROR! ",error.getMessage());
  57. }
  58. });
  59. (AppSingleton.getInstance(getContext()).getRequestQueue()).add(jsObjRequest);
  60. }
  61. });
  62. }
  63. });
  • Two-factor authentication using SMS code

Tutorial: Android - Implementing two-step authentication through SMS code


  1. /*************************************************************************************************
  2. * 2FA using text messages *
  3. * **********************************************************************************************/
  4. (findViewById(R.id.smsOptionLyt)).setOnClickListener(new View.OnClickListener() {
  5. @Override
  6. public void onClick(View v) {
  7. dismiss();
  8. Statics.usersTable.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
  9. @Override
  10. public void onDataChange(DataSnapshot dataSnapshot) {
  11. /** 1.Get user's creds! phone number included.. **/
  12. email = (dataSnapshot.getValue(User.class)).getEmailAddress();
  13. username = (dataSnapshot.getValue(User.class)).getFirstName() + " " + (dataSnapshot.getValue(User.class)).getLastName();
  14. phoneNumber = (dataSnapshot.getValue(User.class)).getPhoneNumber();
  15. countryCode = (dataSnapshot.getValue(User.class)).getPhoneCountryCode();
  16. addUserUrl = "https://api.authy.com/protected/json/users/new?user[email]=" + email
  17. + "&user[cellphone]=" + phoneNumber
  18. + "&user[country_code]=" + countryCode + "&api_key=CCb8fPiHfTdFp332cefjTuRjgMNprVOx";
  19. /** 2.Add the user to the Authy API **/
  20. // post call for Authy api to add a user | response contains the added user's id
  21. JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, addUserUrl, null,
  22. new Response.Listener<JSONObject>() {
  23. @Override
  24. public void onResponse(JSONObject response) {
  25. Gson gson = new Gson();
  26. try {
  27. /** get the returned id **/
  28. JsonObject addedUser = gson.fromJson(response.getString("user"), JsonObject.class);
  29. addedUserId = (addedUser.get("id")).getAsString();
  30. /** 3.call the Authy API to send a code through sms **/
  31. /** 4.call the Authy API to validate code provided by user [embedded in sendSecurityCodeTo method **/
  32. sendSecurityCodeTo(addedUserId);
  33. } catch (JSONException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. },
  38. new Response.ErrorListener() {
  39. @Override
  40. public void onErrorResponse(VolleyError error) {
  41. Log.e("ERROR! ", "ee: " + error.getMessage());
  42. }
  43. });
  44. (AppSingleton.getInstance(getContext()).getRequestQueue()).add(jsObjRequest);
  45. }
  46. @Override
  47. public void onCancelled(DatabaseError databaseError) {
  48. throw databaseError.toException();
  49. }
  50. });
  51. }
  52. });

Getting started

Clone this repository and import into Android Studio

  1. git clone https://github.com/AmalH/Android-2FA-with-Google-authenticator.git

Pre-requisites

  • Android SDK 27
  • Android Build Tools v27.0.3
  • Android Support Repository