Unity/Firebase How to authenticate using Google? - c#

I'm trying to implement Firebase Authentication system in my Unity Game Project. Everything is setup properly on the console panel on the website. I've read the docs and can't find a way to login into Google using any api within Firebase within Unity. So I bought Prime31's Play GameServices Plugin for Unity.
Here are my questions:
How to authenticate using Google right within Firebase? Do I need to manage the google sign in myself?
In the Firebase docs I did find:
"After a user successfully signs in, exchange the access token for a Firebase credential, and authenticate with Firebase using the Firebase credential:"
Firebase.Auth.Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(googleIdToken, googleAccessToken);
auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
//......//
});
How can I get the googleIdToken, googleAccessToken which are being passed as parameters above?
Please help (with code). I really like Firebase and would like to make it work without any third party plugins like PRIME31.

Here is the entirety of my Google SignIn code w/ Firebase Authentication and GoogleSignIn libraries:
private void SignInWithGoogle(bool linkWithCurrentAnonUser)
{
GoogleSignIn.Configuration = new GoogleSignInConfiguration
{
RequestIdToken = true,
// Copy this value from the google-service.json file.
// oauth_client with type == 3
WebClientId = "[YOUR API CLIENT ID HERE].apps.googleusercontent.com"
};
Task<GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();
TaskCompletionSource<FirebaseUser> signInCompleted = new TaskCompletionSource<FirebaseUser>();
signIn.ContinueWith(task =>
{
if (task.IsCanceled)
{
signInCompleted.SetCanceled();
}
else if (task.IsFaulted)
{
signInCompleted.SetException(task.Exception);
}
else
{
Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(((Task<GoogleSignInUser>)task).Result.IdToken, null);
if (linkWithCurrentAnonUser)
{
mAuth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
}
else
{
SignInWithCredential(credential);
}
}
});
}
The parameter is for signing in with intentions of linking the new google account with an anonymous user that is currently logged on. You can ignore those parts of the method if desired. Also note all of this is called after proper initialization of the Firebase Auth libraries.
I used the following libraries for GoogleSignIn: https://github.com/googlesamples/google-signin-unity
The readme page from that link will take you through step-by-step instructions for getting this setup for your environment. After following those and using the code above, I have this working on both android and iOS.
Here is the SignInWithCredential method used in the code above:
private void SignInWithCredential(Credential credential)
{
if (mAuth != null)
{
mAuth.SignInWithCredentialAsync(credential).ContinueWith(HandleLoginResult);
}
}
mAuth is a reference to FirebaseAuth:
mAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;

The simple answer is that there's no way in the Firebase SDK plugin for Unity to do the entirety of Google's authentication in a Unity app. I would recommend following the instructions for email/password sign on to start out.
https://firebase.google.com/docs/auth/unity/start
If you really want Google sign on (which you probably do for a shipping title), this sample should walk you through it: https://github.com/googlesamples/google-signin-unity
The key is to get the id token from Google (which is a separate step from the Firebase plugin), then pass that in.
I hope that helps (even if it wasn't timely)!

For someone asking for HandleLoginResult from #Mathew Coats, here is the function used to handle after.
private void HandleLoginResult(Task<FirebaseUser> task)
{
if (task.IsCanceled)
{
UnityEngine.Debug.LogError("SignInWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
UnityEngine.Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception.InnerException.Message);
return;
}
else
{
FirebaseUser newUser = task.Result;
UnityEngine.Debug.Log($"User signed in successfully: {newUser.DisplayName} ({newUser.UserId})");
}
}

As first, you need use Google Sign in Unity plugin to login with Google, and then, when you logged, get token and continues with Firebase Auth. Also you can try this asset http://u3d.as/JR6

Here is the code to get access token from firebase after authentication is done
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
#Override
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (dialog != null) {
dialog.dismiss();
}
if (task.isSuccessful()) {
String idToken = task.getResult().getToken();
Log.i(getClass().getName(), "got access token :" + idToken);
} else {
// show logs
}
}
});

Related

Firebase Authentification log in in unity always returns a new user

I try to login into a firebase user account in Unity using authentication, but my problem is that if I use wrong credits or correct login credits(same result), I get a new user(email not verified...) returned. Is there any way I can fix it and get the correct user or none user if the user doesn't exist. The code below is everything I use for the authentification. Just in case someone misunderstands new user, a new user isn't created just the information I get is like the information a new account has.
I hope someone can help me. Thanks in advance.
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
using Firebase.Auth;
.
.
.
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl("this is my database url");
if (app.Options.DatabaseUrl != null)
app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
Firebase.Auth.FirebaseAuth auth = FirebaseAuth.GetAuth(app);
auth.SignOut();//I don't know if this line is required, I just have it since I thought maybe the user is cached
auth.SignInWithEmailAndPasswordAsync("example#gmail.com", "any password").ContinueWith(task => {
if (task.IsCanceled)
{
Debug.LogError("Task was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("Task encountered an error: " + task.Exception);
return;
}
if (task.IsCompleted)
{
//This case is true
Debug.Log("Task Completed");
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
Debug.Log(FirebaseApp.DefaultInstance.GetEditorAuthUserId());//This is always the email adress
Debug.Log(auth.CurrentUser.IsEmailVerified);//This is always false even if I use the correct password and email adress and verified it
});
Make sure that your google-services.json file is in your project. This is the issue that I had and after downloading the json file from my firebase console, the issue is resolved.

Google .NET API fails due to error 403 (forbidden)

My code snippet below is supposed to return the list of beacons. When having Google API Console generate an API Key I have whitelisted my public IP address and associated with the api key. When the code calls ExecuteAsync() method, I keep receiving an exception with error code 403 (forbidden). What may have I done wrong and how to mitigate the issue?
public async void TestApiKey()
{
var apikey = "739479874ABCDEFGH123456"; //it's not the real key I'm using
var beaconServices = new ProximitybeaconService(new Google.Apis.Services.BaseClientService.Initializer
{
ApplicationName = "My Project",
ApiKey = apikey
});
var result = await beaconServices.Beacons.List().ExecuteAsync();
// Display the results.
if (result.Beacons != null)
{
foreach (var api in result.Beacons)
{
Console.WriteLine(api.BeaconName + " - " + api.Status);
}
}
}
You are using a Public API key. Public API keys only work with public data.
beacons.list Authenticate using an OAuth access token from a
signed-in user with viewer, Is owner or Can edit permissions.
Requires the following OAuth scope:
•https://www.googleapis.com/auth/userlocation.beacon.registry
The method you are trying to access is accessing private user data. You need to be authentication before you can use it. Switch to Oauth2 authentication. Setting it to public probably wont work because you cant to my knowledge supply a scope to a public api key.

Post message with Facebook SDK .NET

I have created a facebook page and a facebook application for my website and now I need to post messages onto the facebook page with help of facebook SDK .NET.
This is what I got so far :
public static bool UploadPost(string message)
{
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient("secret access token");
result = client.Get("oauth/access_token", new
{
client_id = "[Client ID number]",
client_secret = "[Client sercret",
grant_type = "client_credentials",
});
result = client.Post("[facebook app Id]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[facebook app Id]");
return false;
}
When running this I get : Additional information: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action on client.Post. If I remove the client.Post row every thing works good, the correct data is fetched.
I have tried follow some helps on facebook SDK .NET website but it is still not working.
The main problem now is that I get permission exception. I was hoping that my facebook app hade enouth permissions to publish post from my website to the facebook page.
Here is a step wise tutorial to register your application with facebook and get an app Id for your application.
Then for permissions ::
private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";
This is a string of permissions. Pass it on further for getting correct permissions to post messages on page. Post using your standard code for posting no FB pages.
Cheers. Hope it helps.
Are you trying to post to [facebook app id]?
I would recomend to post to "me/feed" and test if that works.
Also, to post to Facebook you have to have the publish_stream permission
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
Should work :)
The following should work.
var fb = new FacebookClient("access_token");
fb.PostCompleted += (o, e) => {
if(e.Error == null) {
var result = (IDictionary<string, object>)e.GetResultData();
var newPostId = (string)result.id;
}
};
var parameters = new Dictionary<string, object>();
parameters["message"] = "My first wall post using Facebook SDK for .NET";
fb.PostAsync("me/feed", parameters);
This was taken directly from the documentation.
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.

Google+ API: How can I use RefreshTokens to avoid requesting access every time my app launches?

I'm trying to use the Google+ API to access info for the authenticated user. I've copied some code from one of the samples, which works fine (below), however I'm having trouble making it work in a way I can reuse the token across app-launches.
I tried capturing the "RefreshToken" property and using provider.RefreshToken() (amongst other things) and always get a 400 Bad Request response.
Does anyone know how to make this work, or know where I can find some samples? The Google Code site doesn't seem to cover this :-(
class Program
{
private const string Scope = "https://www.googleapis.com/auth/plus.me";
static void Main(string[] args)
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "BLAH";
provider.ClientSecret = "BLAH";
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);
var plus = new PlusService(auth);
plus.Key = "BLAH";
var me = plus.People.Get("me").Fetch();
Console.WriteLine(me.DisplayName);
}
private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { Scope });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
Here is an example. Make sure you add a string setting called RefreshToken and reference System.Security or find another way to safely store the refresh token.
private static byte[] aditionalEntropy = { 1, 2, 3, 4, 5 };
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { PlusService.Scopes.PlusMe.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
string refreshToken = LoadRefreshToken();
if (!String.IsNullOrWhiteSpace(refreshToken))
{
state.RefreshToken = refreshToken;
if (arg.RefreshToken(state))
return state;
}
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
var result = arg.ProcessUserAuthorization(authCode, state);
StoreRefreshToken(state);
return result;
}
private static string LoadRefreshToken()
{
return Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(Properties.Settings.Default.RefreshToken), aditionalEntropy, DataProtectionScope.CurrentUser));
}
private static void StoreRefreshToken(IAuthorizationState state)
{
Properties.Settings.Default.RefreshToken = Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(state.RefreshToken), aditionalEntropy, DataProtectionScope.CurrentUser));
Properties.Settings.Default.Save();
}
The general idea is as follows:
You redirect the user to Google's Authorization Endpoint.
You obtain a short-lived Authorization Code.
You immediately exchange the Authorization Code for a long-lived Access Token using Google's Token Endpoint. The Access Token comes with an expiry date and a Refresh Token.
You make requests to Google's API using the Access Token.
You can reuse the Access Token for as many requests as you like until it expires. Then you can use the Refresh Token to request a new Access Token (which comes with a new expiry date and a new Refresh Token).
See also:
The OAuth 2.0 Authorization Protocol
Google's OAuth 2.0 documentation
I also had problems with getting "offline" authentication to work (i.e. acquiring authentication with a refresh token), and got HTTP-response 400 Bad request with a code similar to the OP's code. However, I got it to work with the line client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.clientSecret); in the Authenticate-method. This is essential to get a working code -- I think this line forces the clientSecret to be sent as a POST-parameter to the server (instead of as a HTTP Basic Auth-parameter).
This solution assumes that you've already got a client ID, a client secret and a refresh-token. Note that you don't need to enter an access-token in the code. (A short-lived access-code is acquired "under the hood" from the Google server when sending the long-lived refresh-token with the line client.RefreshAuthorization(state);. This access-token is stored as part of the auth-variable, from where it is used to authorize the API-calls "under the hood".)
A code example that works for me with Google API v3 for accessing my Google Calendar:
class SomeClass
{
private string clientID = "XXXXXXXXX.apps.googleusercontent.com";
private string clientSecret = "MY_CLIENT_SECRET";
private string refreshToken = "MY_REFRESH_TOKEN";
private string primaryCal = "MY_GMAIL_ADDRESS";
private void button2_Click_1(object sender, EventArgs e)
{
try
{
NativeApplicationClient client = new NativeApplicationClient(GoogleAuthenticationServer.Description, this.clientID, this.clientSecret);
OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(client, Authenticate);
// Authenticated and ready for API calls...
// EITHER Calendar API calls (tested):
CalendarService cal = new CalendarService(auth);
EventsResource.ListRequest listrequest = cal.Events.List(this.primaryCal);
Google.Apis.Calendar.v3.Data.Events events = listrequest.Fetch();
// iterate the events and show them here.
// OR Plus API calls (not tested) - copied from OP's code:
var plus = new PlusService(auth);
plus.Key = "BLAH"; // don't know what this line does.
var me = plus.People.Get("me").Fetch();
Console.WriteLine(me.DisplayName);
// OR some other API calls...
}
catch (Exception ex)
{
Console.WriteLine("Error while communicating with Google servers. Try again(?). The error was:\r\n" + ex.Message + "\r\n\r\nInner exception:\r\n" + ex.InnerException.Message);
}
}
private IAuthorizationState Authenticate(NativeApplicationClient client)
{
IAuthorizationState state = new AuthorizationState(new string[] { }) { RefreshToken = this.refreshToken };
// IMPORTANT - does not work without:
client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.clientSecret);
client.RefreshAuthorization(state);
return state;
}
}
The OAuth 2.0 spec is not yet finished, and there is a smattering of spec implementations out there across the various clients and services that cause these errors to appear. Mostly likely you're doing everything right, but the DotNetOpenAuth version you're using implements a different draft of OAuth 2.0 than Google is currently implementing. Neither part is "right", since the spec isn't yet finalized, but it makes compatibility something of a nightmare.
You can check that the DotNetOpenAuth version you're using is the latest (in case that helps, which it might), but ultimately you may need to either sit tight until the specs are finalized and everyone implements them correctly, or read the Google docs yourself (which presumably describe their version of OAuth 2.0) and implement one that specifically targets their draft version.
I would recommend looking at the "SampleHelper" project in the Samples solution of the Google .NET Client API:
Samples/SampleHelper/AuthorizationMgr.cs
This file shows both how to use Windows Protected Data to store a Refresh token, and it also shows how to use a Local Loopback Server and different techniques to capture the Access code instead of having the user enter it manually.
One of the samples in the library which use this method of authorization can be found below:
Samples/Tasks.CreateTasks/Program.cs

Accessing GData Calender from Google Apps account?

I'm building a simple app too that needs to access a calendar that's in my Google Apps account. But I'm having problems with authentication. I've tried the following code but it doesn't work:
Service service = new Service("<appname>");
service.setUserCredentials("<email>", "<password>");
CalendarEntry entry = (CalendarEntry)service.Get("<eventUrl>");
How do you get this to work with Google Apps? Is there any other type of authentication that I have to use for Google apps?
Update:
Unlocking the captcha solved my problem with getting the feed. Now I've hit the next wall: updating an event.
entry.Title.Text = "Foo";
entry.Update();
Gives me the GDataRequestException exception: "Can not update a read-only entry".
Im using the private calendar xml address that I got under kalendarsettings:
https://www.google.com/calendar/feeds/_%40group.calendar.google.com/private-/basic
I would recommend using Fiddler to see what http response you are getting back from Google. When I ran your code against my google apps account, I was getting back an "Error=CaptchaRequired" response. This required that I go to https://www.google.com/a/yourgoogleappdomain.com/UnlockCaptcha (replacing with your domain obviously). After I did that I was able to properly connect. You may be getting a different error code too so check for that and post it here. You could have an invalid password or invalid url or this functionality is disabled by your google apps administrator. Here is my sample code:
var calendarService = new CalendarService("company-app-version");
calendarService.setUserCredentials("<email>", "<password>");
var eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");
var eventFeed = calendarService.Query(eventQuery);
foreach (var atomEntry in eventFeed.Entries)
{
Console.WriteLine(atomEntry.Title.Text);
}
Make sure to replace the email, password, and email inside of the URL (url encode the # sign too).
using Google.GData.Client;
public bool ValidateGoogleAccount(string login, string password)
{
try
{
Service bloggerService = new Service("blogger", "App-Name");
bloggerService.Credentials = new GDataCredentials(login, password);
string token = bloggerService.QueryAuthenticationToken();
if (token != null)
return true;
else
return false;
}
catch (Google.GData.Client.InvalidCredentialsException)
{
return false;
}
}
Yet another solution Austin from google provides (it worked for me):
http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/400104713435a4b4?pli=1

Categories