Reputation: 117
I am working in Xamarin android app in c# with google firebase authentication. The code is working fine with firebase. it is authenticating the user while login and returning the name and email address. But I need the access token after authentication in firebase , to work further with REST API. but I am unable to get the access token , can I get the access token?
Code is as follows:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Gms.Auth.Api.SignIn;
using Android.Gms.Common.Apis;
using Android.Gms.Auth.Api;
using Firebase.Auth;
using Firebase;
using Android.Content;
using System;
using Android.Gms.Tasks;
using Java.Lang;
namespace loginGoogle
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity, IOnSuccessListener, IOnFailureListener, IOnCompleteListener
{
GoogleSignInOptions gso;
GoogleApiClient googleApiClient;
FirebaseAuth firebaseAuth;
Button signinButton;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
signinButton = (Button)FindViewById(Resource.Id.signInButton);
signinButton.Click += SigninButton_Click;
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestIdToken("759281956917-ib3rko81uvs4bvdf3g3p76f0dl7q8k64.apps.googleusercontent.com")
.RequestEmail()
.Build();
googleApiClient = new GoogleApiClient.Builder(this)
.AddApi(Auth.GOOGLE_SIGN_IN_API, gso).Build();
googleApiClient.Connect();
firebaseAuth = GetFirebaseAuth();
UpdateUI();
}
private FirebaseAuth GetFirebaseAuth()
{
var app = FirebaseApp.InitializeApp(this);
FirebaseAuth mAuth;
if (app == null)
{
var options = new FirebaseOptions.Builder()
.SetProjectId("login-bde5d")
.SetApplicationId("login-bde5d")
.SetApiKey("AIzaSyCql6njOSplLxy6Nd2tpNHNSeBxyOm6TQM")
.SetDatabaseUrl("https://login-bde5d.firebaseio.com")
.SetStorageBucket("login-bde5d.appspot.com")
.Build();
app = FirebaseApp.InitializeApp(this, options);
mAuth = FirebaseAuth.Instance;
}
else
{
mAuth = FirebaseAuth.Instance;
}
return mAuth;
}
private void SigninButton_Click(object sender, System.EventArgs e)
{
UpdateUI();
if (firebaseAuth.CurrentUser == null)
{
var intent = Auth.GoogleSignInApi.GetSignInIntent(googleApiClient);
StartActivityForResult(intent, 1);
}
else
{
firebaseAuth.SignOut();
UpdateUI();
}
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
GoogleSignInResult result = Auth.GoogleSignInApi.GetSignInResultFromIntent(data);
if (result.IsSuccess)
{
GoogleSignInAccount account = result.SignInAccount;
LoginWithFirebase(account);
}
}
}
private void LoginWithFirebase(GoogleSignInAccount account)
{
var credentials = GoogleAuthProvider.GetCredential(account.IdToken, null);
firebaseAuth.SignInWithCredential(credentials).AddOnSuccessListener(this)
.AddOnFailureListener(this).AddOnCompleteListener(this, this);
}
public void OnSuccess(Java.Lang.Object result)
{
TextView displayNameText = (TextView)FindViewById(Resource.Id.displaynameText);
TextView emailText = (TextView)FindViewById(Resource.Id.emailText);
displayNameText.Text = "Display Name: " + firebaseAuth.CurrentUser.DisplayName;
emailText.Text = "Email: " + firebaseAuth.CurrentUser.Email;
Toast.MakeText(this, "Login successful", ToastLength.Short).Show();
UpdateUI();
}
public void OnFailure(Java.Lang.Exception e)
{
Toast.MakeText(this, "Login Failed", ToastLength.Short).Show();
UpdateUI();
}
void UpdateUI()
{
if (firebaseAuth.CurrentUser != null)
{
signinButton.Text = "Sign Out";
}
else
{
signinButton.Text = "Sign In With Google";
}
}
public void OnComplete(Task task)
{
//throw new NotImplementedException();
if (task.IsSuccessful)
{
TextView photourlText = (TextView)FindViewById(Resource.Id.photoURLText);
photourlText.Text = "User successfully login with Photo URL: " + firebaseAuth.CurrentUser.PhotoUrl.Path;
}
else
{
TextView photourlText = (TextView)FindViewById(Resource.Id.photoURLText);
photourlText.Text = "problem in user login";
}
}
}
}
I have followed the following link: https://www.youtube.com/watch?v=NYMCrD9klA0
Upvotes: 0
Views: 3274
Reputation: 477
The other answer is referring to a token which is used for Firebase Cloud Messaging / Push notifications not the token which is used for Firebase Auth which is what OP needs.
Once you have logged the user in, this populates FirebaseAuth.Instance.CurrentUser
. You can then get the token from the logged in user.
if (FirebaseAuth.Instance.CurrentUser != null)
{
var tokenRequest = await FirebaseAuth.Instance.CurrentUser.GetIdTokenAsync(true);
string token = tokenRequest.Token;
// Do whatever with token
}
Note. There appears to be a bug with current Xamarin Firebase Auth which causes a null reference exception to be raised when calling the GetIdTokenAsync()
method on a FirebaseUser
object.
'Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.zza(com.google.firebase.auth.FirebaseUser, boolean)' on a null object reference'
The resolution is documented here - https://github.com/xamarin/GooglePlayServicesComponents/issues/223
Which is to install an additional Nuget package - https://www.nuget.org/packages/Xamarin.Android.ManifestMerger/1.0.0-preview03
Upvotes: 1
Reputation: 10938
You could use the code below to get the token. It would output in output window, or you could get it directly from the code: FirebaseInstanceId.Instance.Token
.
Log.Debug(TAG, "InstanceID token: " + FirebaseInstanceId.Instance.Token)
You could refer to the MS docs about Remote Notifications with Firebase Cloud Messaging
.
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows
And download the source file from the link below. https://learn.microsoft.com/zh-cn/samples/xamarin/monodroid-samples/firebase-fcmnotifications/
Upvotes: 0