Firebase Authentication API Email/Password Android - android

I am attempting to write an app for android that uses Firebase Authentication via Email/Password. It is enabled. However the tutorial, and the code in Github for the examples are showing:
private FirebaseAuth mAuth;
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.google.firebase:firebase-core:9.0.2'
}
apply plugin: 'com.google.gms.google-services'
However, I get an error as if the "FirebaseAuth" doesn't exist. However the latest documentation says otherwise.
Github sample code
Any help would be greatly appreciated.

Replace the com.google.firebase:firebase-core:9.0.2' dependency with the com.google.firebase:firebase-auth:9.0.2 dependency. So:
compile 'com.google.firebase:firebase-auth:9.0.2'
instead of
compile 'com.google.firebase:firebase-core:9.0.2' under your dependencies.
I did not find the FirebaseAuth class in the core dependency but I did find it in the auth dependency. Furthermore, if you checkout their dependencies list, they do not add the core dependency, they add the auth dependency instead.

According to documentation in the firebase web page you should create a Firebase object using the URL from your firebase and from there create usernames with passwords or log them in. The code you showed used this FirebaseAuth for that.
Here is the code to create a new user:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.createUser("bobtony#firebase.com", "correcthorsebatterystaple", new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
#Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
Here is the code to log him in:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithPassword("bobtony#firebase.com", "correcthorsebatterystaple", new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
}
});
Got all of this info from the quick start guide here: https://www.firebase.com/docs/android/guide/login/password.html#section-logging-in
Hope it helps.

Related

signInAnonymously:FAILURE com.google.firebase.auth.FirebaseAuthException: despite Anonymous Sign in enabled

Despite I have enabled in my Firebase project anonymous sign in, my mobile (Android) app is not able to authenticate and I'm getting this error (on emulator and on physical device too).
signInAnonymously:FAILURE
com.google.firebase.auth.FirebaseAuthException: This operation is restricted to administrators only.
My Firebase config:
My code:
mAuth = FirebaseAuth.getInstance();
...
// Sign in anonymously. Authentication is required to read or write from Firebase Storage.
mAuth
.signInAnonymously()
.addOnSuccessListener(
mActivity,
authResult -> {
Log.d(TAG, "signInAnonymously:SUCCESS");
try {
upload();
} catch (Exception e) {
Log.e(TAG, "upload:FAILURE", e);
}
})
.addOnFailureListener(
mActivity,
exception -> {
Log.e(TAG, "signInAnonymously:FAILURE", exception);
});
}
Dependencies:
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-storage:20.0.0'
implementation "com.google.firebase:firebase-core:18.0.2"
Does anybody had the same problem?
Well, in the end, I updated packages to this:
+ implementation platform('com.google.firebase:firebase-bom:29.0.2')
+ implementation 'com.google.firebase:firebase-auth'
+ implementation 'com.google.firebase:firebase-storage'
... implementation "com.google.firebase:firebase-core:18.0.2" //not updated
Make the Firebase storage rules look like this(disclaimer: for my debug version, production I suppose will be more strict):
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
​
And it started to work. But honestly not sure why ¯\(ツ)/¯.

Firebase phone authentication error in Android Studio

I'm getting error for phone authentication. I received OTP successfully, but after I share my project with my team member with GitHub, I'm getting this errors.
I also I added MY SHA 1 & SHA 256 in my new firebase console. I also added dependencies, but still I get this error.
I also want to inform that after transfer my project with GitHub, I make new firebase account and add SHA 1 & SHA 256 in this project
Logcat:
03-16 16:19:40.001 8163-8163/com.roundtripride E/zzf: Problem retrieving SafetyNet Token: 7:
03-16 16:19:40.679 8163-8235/com.roundtripride E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
03-16 16:19:40.713 8163-8163/com.roundtripride E/zzf: Failed to get reCAPTCHA token with error [There was an error while trying to get your package certificate hash.]- calling backend without app verification
03-16 16:19:41.202 8163-8201/com.roundtripride E/FirebaseAuth: [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17093 null
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : com.google.firebase.auth.FirebaseAuthException: This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
Dependencies:
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:18.0.0'
implementation 'com.google.android.libraries.places:places:2.4.0'
implementation platform('com.google.firebase:firebase-bom:26.7.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-auth:20.0.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
implementation 'com.intuit.sdp:sdp-android:1.0.6'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.amitshekhar.android:jackson-android-networking:1.0.2'
implementation 'com.github.prolificinteractive:material-calendarview:1.6.0'
implementation 'androidx.browser:browser:1.3.0'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
}
Code:
public class OTPVerifyActivity extends BaseActivity implements View.OnClickListener {
Context context;
private FirebaseAuth mAuth;
private String mVerificationId;
String idToken = "", mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verify);
Utility.setLoginStatusColor(this);
context = this;
txt_finish = findViewById(R.id.txt_finish);
edt_1 = findViewById(R.id.edt_1);
mAuth = FirebaseAuth.getInstance();
mobile = getIntent().getStringExtra("mobile");
sendVerificationCode();
txt_finish.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == txt_finish) {
Utility.hideSoftKeyboard(edt_1, context);
if (edt_1.getText().toString().equals("")) {
Utility.errDialog("Please enter OTP", context);
} else {
verifyVerificationCode(edt_1.getText().toString().trim());
}
}
}
private void sendVerificationCode() {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + mobile) // Phone number to verify
.setTimeout(30L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Log.e("Tag", "get Data : " + phoneAuthCredential.getSmsCode());
Utility.dismissProgressDialog(pd);
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
edt_1.setText(code);
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Utility.dismissProgressDialog(pd);
Log.e("Tag", "onVerificationFailed : " + e.getMessage());
Log.e("Tag", "onVerificationFailed : " + e.getLocalizedMessage());
Log.e("Tag", "onVerificationFailed : " + e.toString());
Utility.errDialog(e.getMessage(), context);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
mVerificationId = s;
Utility.dismissProgressDialog(pd);
}
};
private void verifyVerificationCode(String code) {
//Log.e("Tag","Verify code : "+code);
pd = Utility.showProgressDialog(context);
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);
signInWithPhoneAuthCredential(credential);
} catch (Exception e) {
Log.e("Tag", "PhoneAuthCredential Exception " + e.getMessage());
}
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(OTPVerifyActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
user.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
idToken = task.getResult().getToken();
Utility.dismissProgressDialog(pd);
Log.e("Tag", "Success OTP " + isDriver);
MyPreference.setPreferenceValue(context,"isLogin","true");
}
}
});
} else {
Utility.dismissProgressDialog(pd);
//verification unsuccessful.. display an error message
String message = "Something is wrong, we will fix it soon...";
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
message = "Invalid code entered...";
}
Log.e("Tag", message);
Utility.errDialog(message, context);
}
}
});
}
}
Remove your debug SHA-1 and SHA-256 from your old firebase account .
Open android studio and click on gradle in right corner > click your project > select app > select tasks > select android > click on signing report > copy our SHA1 and SHA-256 from there.
Add SHA1 and SHA-256 in your new firebase account .(if you are building apk from 2 system add both system's SHA1 and SHA-256).
You need to make sure that you enabled PHONE AUTHENTICATION in Firebase console => Authentication => Sign-in Methods.
Add dependency in build.gradle(:app)
implementation 'androidx.browser:browser:1.3.0'
Go to google cloud console , select your project .
Click on navigation menu and select APis & services and then select Dashboard .
Click on enable api and services and enable api " Android Device Verification".
Download and replace the latest google-services.json file in your project.
implementation 'androidx.browser:browser:1.3.0'
please add this dependency then check sha1 and sha256 one more time then try it

how i can get list of name of folder in firebase storage android?

How can I get list of all folder file/,R52H50TN40F/,R58H42X2DCE/...
It's possible. Make sure you have this dependency in your build.gradle file:
dependencies {
...
implementation 'com.google.firebase:firebase-storage:19.1.1' // or later
}
This is how you can iterate over a list of directories and their entries:
listRef = FirebaseStorage.getInstance().getReference("/");
listRef.listAll()
.addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult listResult) {
Log.d(TAG, listRef.getName());
for (StorageReference prefix : listResult.getPrefixes()) {
Log.d(TAG, prefix.getName());
// This will give you a folder name
// You may call listAll() recursively on them.
}
for (StorageReference item : listResult.getItems()) {
// All the items under listRef.
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Uh-oh, an error occurred!
}
});
It's not possible to get list of all folders with the firebase client api
But you can combine Firebase Functions and Cloud Storage bucket API.
Create a firebase function (documentation)
Use Firebase Bucket getFiles function

AWS DynamoDB access from Android, access denied to table

I'm trying to do CRUD operations on a NoSQL DynamoDB, I originally had not integrated a CognitoPool with my project on the AWS Mobile Hub but I have no done that and replaced my json file in the "raw" directory in my project. The DB is completely public both read and write but for some reason I keep getting this error:
com.amazonaws.AmazonServiceException: User: arn:aws:sts::1234567890:assumed-role/shoppinglist_unauth_MOBILEHUB_1234567890/CognitoIdentityCredentials is not authorized to perform: dynamodb:DescribeTable on resource: arn:aws:dynamodb:us-east-1:1234567890:table/ShoppingLists (Service: AmazonDynamoDB; Status Code: 400; Error Code: AccessDeniedException; Request ID: BQ0HAP7PUGO6AUC04LOHUND1V3VV4KQNSO5AEMVJF66Q9ASUAAJG)
I've changed all the identifying numbers to 1234567890 for security reasons.
This is my .json file:
{
"UserAgent": "MobileHub/1.0",
"Version": "1.0",
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "us-east-1******************,
"Region": "us-east-1"
}
}
},
"IdentityManager": {
"Default": {}
},
"CognitoUserPool": {
"Default": {
"PoolId": "us-east-1_*******",
"AppClientId": "5lg571jsd60ruvair8jiqpefbs",
"AppClientSecret": "bqn8edlp19gfgogfhf4j9qg1mq8u8ftpb328f652n0451gl2dnt",
"Region": "us-east-1"
}
},
"DynamoDBObjectMapper": {
"Default": {
"Region": "us-east-1"
}
},
"PinpointAnalytics": {
"Default": {
"AppId": "27e0f3ee2e63419c9dc8f18f23a294fe",
"Region": "us-east-1"
}
},
"PinpointTargeting": {
"Default": {
"Region": "us-east-1"
}
}
}
This is my onCreate() method in my main activity class
AWSMobileClient.getInstance().initialize(this, awsStartupResult ->
Log.d("YourMainActivity", "AWSMobileClient is instantiated and you are connected to AWS!"))
.execute();
// Instantiate a AmazonDynamoDBMapperClient
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
Runnable runnable = () -> {
dbClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
// Create a table reference
dbTable = Table.loadTable(dbClient, "ShoppingLists");
Document memo = new Document();
memo.put("Apple", "apple");
dbTable.putItem(memo);
};
Thread myThread = new Thread(runnable);
myThread.start();
My build.gradle should hold the correct dependencies, those are here, granted it may be a bit of a mess:
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+#aar') { transitive = true }
implementation 'com.amazonaws:aws-android-sdk-core:2.6.18'
implementation 'com.amazonaws:aws-android-sdk-s3:2.6.18'
implementation 'com.amazonaws:aws-android-sdk-ddb:2.6.18'
implementation 'com.amazonaws:aws-android-sdk-ddb-mapper:2.6.18'
compile 'com.amazonaws:aws-android-sdk-core:2.6.18'
compile 'com.amazonaws:aws-android-sdk-ddb:2.6.18'
compile 'com.amazonaws:aws-android-sdk-ddb-document:2.4.4'
// Mobile Client for initializing the SDK
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+#aar') { transitive = true }
// Cognito UserPools for SignIn
implementation 'com.android.support:support-v4:27.1.1'
implementation ('com.amazonaws:aws-android-sdk-auth-userpools:2.6.+#aar') { transitive = true }
// Sign in UI Library
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation ('com.amazonaws:aws-android-sdk-auth-ui:2.6.+#aar') { transitive = true }
As far as I can tell this should work fine, I was helped by another helpful person here to get to the point where it would connect to AWS which it did do at one point but I just can't seem to access the table.
I guess I have two questions, is it possible to do this without a Cognito pool at all and just have it completely unsecure? And if not, how do I get this to work with the Cognito Pool? Should the cognito pool have user names associated with it?
Let me take a crack at answering your questions
1) Can you do this without a Cognito Identity pool? The answer is Yes. This doesn't automatically mean that it is insecure - you can use AWS credentials that you setup for an IAM user. The best practice, however, is to use Cognito Identity pool, which will give you temporary AWS credentials that are valid for a short amount of time.
2) When you create a Cognito Identity pool, two roles (named auth and unauth) are automatically created. The "auth" role is for the cases where you have a signed in user ( for example, signed in using a social login like Facebook and federated to AWS through the Identity pool) and the "unauth" role is for a user who hasn't yet signed in. You can fine-tune the access privileges for these roles using IAM policies to best suit your application's needs.
See this page (https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-nosql-integrate-an-existing-table.html) for specific instructions on how to get this working.

How to get push interactive notification with Urban Airship in Android?

I've integrated Urban Airship SDK to my application on device with Android 4.2 (Jelly Bean). I've received general push-notifications. It's Ok. But I want to get interactive push-notification with button with "Save" label.
My dependencies from build.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.google.android.gms:play-services:+'
compile project (':urbanairship-lib-6.1.1')
compile 'com.android.support:support-v4:22.2.0'
// Recommended for in-app messaging
compile 'com.android.support:cardview-v7:22.2.0'
// Recommended for location services
compile 'com.google.android.gms:play-services-location:7.5.0'
// Required for Android (GCM) push notifications
compile 'com.google.android.gms:play-services-gcm:7.5.0'
compile files('libs/commons-io-2.4.jar')
compile files('libs/FlurryAnalytics-4.1.0.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
}
According to official documentation, I've added the following code in the onCreate() method in MyApplication class:
#Override
public void onCreate() {
AirshipConfigOptions options = new AirshipConfigOptions();
options.developmentAppKey = "sdgsdgsdhsdh";
options.developmentAppSecret = "sdhsdhsdhsdhsh";
options.productionAppKey = "Your Production App Key";
options.productionAppSecret = "Your Production App Secret";
options.inProduction = false;
options.gcmSender = "11111111";
UAirship.takeOff(this, options);
NotificationActionButton hiButtonAction = new NotificationActionButton.Builder("btnSave")
.setLabel(R.string.save)
.setPerformsInForeground(true)
.build();
// Define the group
NotificationActionButtonGroup buttonGroup = new NotificationActionButtonGroup.Builder()
.addNotificationActionButton(hiButtonAction)
.build();
// Add the custom group
UAirship.shared().getPushManager().addNotificationActionButtonGroup("save", buttonGroup);
UAirship.shared().getPushManager().setUserNotificationsEnabled(true);
UAirship.shared().getPushManager().setPushEnabled(true);
}
After that I've tried test push from my Urban Airship account:
EDIT:
I've used Urban Airship API v3. According to official documentation I've sent push with json:
{
"audience": {
"named_user": "2971"
},
"device_types":["android"],
"notification": {
"android": {
"alert": "Hello",
"extra": {
"EEID": "2971",
"DATE": "20150601"
},
"interactive": {
"type": "save"
}
}
}
}
But I've received general push-notification with "Hello" text and without any buttons.
What could be the problem and how to open some activity by click on the button in notification?
Thanks in advance.
The key "category" is not the correct on Android. Its actually looking for "com.urbanairship.interactive_type". However you should be either using the main composer or the push API directly.
curl -v -X POST -u <APP_KEY>:<MASTER_SECRET> -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '{
"audience":"ALL",
"device_types":["android"],
"notification": {
"android": {
"alert": "Hello",
"interactive": {
"type": "save"
}
}
}
}' https://go.urbanairship.com/api/push/
But with your apps credentials for <APP_KEY>:<MASTER_SECRET>
See http://docs.urbanairship.com/api/ua.html#interactive-api for more details.

Categories

Resources