Firebase 3.x - Token / Session Expiration - session

Does anyone know how long would it take for the token to expire? There no option now to set the token validity on the console.

Since May 2016 Firebase Authentication login sessions don't expire anymore. Instead they use a combination of long-lived account tokens and short-lived, auto-refreshed access/ID tokens to get the best of both worlds.
If you want to end a user's session, you can call signOut().

Its does expire. After one hour logged in the token id expire. If you try to verify sdk returns a error "Error: Firebase ID token has expired. Get a fresh token from your client app and try again. See https://firebase.google.com/docs/auth/server/verify-id-tokens for details on how to retrieve an ID token."
Is There such a way to change expiration time to Firebase token, not custom token.
Anybody that know how this really works.

For anyone that is still confused, it is all explained in great detail here
If your app includes a custom backend server, ID tokens can and should
be used to communicate securely with it. Instead of sending requests
with a user’s raw uid which can be easily spoofed by a malicious
client, send the user's ID token which can be verified via a Firebase
Admin SDK (or even a third-party JWT library if Firebase does not have
an Admin SDK in your language of choice). To facilitate this, the
modern client SDKs provide convenient methods for retrieving ID tokens
for the currently logged-in user. The Admin SDK ensures the ID token
is valid and returns the decoded token, which includes the uid of the
user it belongs to as well as any custom claims added to it.

If the above answer is still confusing to you,
This is what i did:
firebase.auth().onAuthStateChanged(async user => {
if (user) {
const lastSignInTime = new Date(user.metadata.lastSignInTime);
const lastSignInTimeTimeStamp = Math.round(lastSignInTime.getTime() / 1000);
const yesterdayTimeStamp = Math.round(new Date().getTime() / 1000) - (24 * 3600);
if(lastSignInTimeTimeStamp < yesterdayTimeStamp){
await firebase.auth().signOut()
this.setState({
loggedIn: false
});
return false;
}
this.setState({
loggedIn: true,
user
});
}
})

Related

ADAL acquire token with username and password

I am trying to acquire token from azure AD from Xamarin Form application. I am using ADAL 4+ and I don't want user to login every time when app is launch.
Is there anyway to refresh or acquire token programmatically when application relaunch after user already successfully login.
Due to ADAL no longer have userPasswordCredientian(). I couldn't find any alternative solutions for this.
Once ADAL.NET has acquired a token for a user, it caches it, along with a refresh token. Then next time the application wants a token, it should first call AcquireTokenSilentAsync to verify if an acceptable token is in the cache. If there is a token but it has expired, AcquireTokenSilentAsync will use the cached refresh token in order to refresh the access token and if no token is in the cache, then an interactive call might be necessary to have the user sign-in again.
Here's some more information on how this works in ADAL
This is the recommended call pattern, do an AT silent call first, and catch the AdalSilentTokenAcquisitionException (because a token was not found), then do an AT interactive call.
AuthenticationContext ac = new AuthenticationContext(authority);
AuthenticationResult result=null;
try
{
result = await ac.AcquireTokenSilentAsync(resource, clientId);
}
catch (AdalException adalException)
{
if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently
|| adalException.ErrorCode == AdalError.InteractionRequired)
{
result = await ac.AcquireTokenAsync(resource, clientId, redirectUri,
new PlatformParameters(PromptBehavior.Auto));
}
}
I would recommended moving to MSAL...here's documentation on the differences between ADAL and MSAL and specifics on the username/password flow in MSAL and how to migrate from ADAL.NET 4.x to MSAL.NET 2.x and the just released MSAL v3 api.

Auth0 and Google API, access token expired, howto write files to Google Drive

I've written an online converter and integrated Auth0 to my website. What I'm trying to achieve is to auto-upload the converted file to the Google Drive of a logged in user. I set up Google oauth in Auth0 and everything seemed to work fine.
The problem is, Google's access_token expires after 60min and I don't have a refresh_token. Therefore, the user needs to log in via the Google Login-page again. That is not, what I want, because the user is in fact logged in way longer than just 60min on my site, but Google refuses API-calls (because the Google token expired).
I know I can request a refresh_token by setting access_type=offline but this will add the permission Have offline access. I don't want that, I just want to upload data to the user's Drive, if he clicked the convert button on my page. I don't want to ask the users for permissions I don't need. If I (as a user) would link my Google account on a similar page and the tool asks for offline access I wouldn't approve, to be honest - the permission sounds like the tool creator can do whatever he wants with your account whenever he wants... There are many tools out there that have write access to a user's Drive without asking for offline access and with one single login until the user revokes the permission. How is that done?
Is there a way to make Google API calls without asking for offline access and without forcing the user to approve the app (that is already approved by him) again and again every 60min?
Thanks in advance,
phlo
Is there a way to make Google API calls without asking for offline access and without forcing the user to approve the app (that is already approved by him) again and again every 60min?
Yes there are ways, but it depends on the specifics of your use case. For example, is your code in Java/php/etc running on a server, or is it JavaScript running in the browser?
Running your auth in the browser is probably the simplest solution as the Google library (https://developers.google.com/api-client-library/javascript/features/authentication) does all the work for you.
By asking for offline access you are requesting a refresh token. Google is going to tell the user that you are requesting offline access. You can request something without telling the user what they are authorizing.
No there is no way to request a refresh token without displaying that message. Nor is there a way for you to change the message it's a standard Google thing.
I found the solution!
Prerequirements
Enable Use Auth0 instead of the IdP to do Single Sign On in your client's Dashboard
Create a new Angular-route to handle the silent login callback (e.g. /sso)
Add
$rootScope.$on("$locationChangeStart", function() {
if ($location.path().indexOf("sso") == -1) {
authService.relogin(); //this is your own service
}
});
to your run-function and set the callbackURL in angularAuth0Provider.init() to your new Angular-route (<YOUR_DOMAIN>/sso). Add this URL to your accepted callbacks in the Auth0 dashboard - this won't end in an infinite loop, because the locationChangeStart-event won't call authService.relogin() for this route
Add $window.close(); to the controller of the Angular-route (/sso) to auto-close the popup
Authenticate the user via Auth0 and save the timestamp and the Auth0-access_token somewhere
On reload:
Check, if the Auth0-token is still valid in authService.relogin(). If not, the user has to login again either way. If the token is valid and the Google token is about to expire (check this with the saved timestamp to prevent unnecessary API calls) check for SSO-data and login silently, if present
/* ... */
if (validToken && googleExpired) {
angularAuth0.getSSOData(function (err, data) {
var lastUsedConnection = data.lastUsedConnection;
var connectionName = (_.isUndefined(lastUsedConnection) ? undefined : lastUsedConnection.name);
var isGoogle = (_.isUndefined(connectionName) ? false : connectionName == "google-oauth2");
if (!err && data.sso && isGoogle) {
authManager.authenticate();
localStorage.setItem("last-relogin", new Date().getTime());
angularAuth0.signin({
popup: true,
connection: data.lastUsedConnection.name
});
}
});
}
Now you will find a fresh Google access_token for this user (without asking for offline access)
Resources:
https://auth0.com/docs/quickstart/spa/angularjs/03-session-handling
https://auth0.com/docs/quickstart/spa/angularjs/11-sso

Gmail API suddenly stopped working with [Error: unauthorized_client]

Where I work we use Google Apps for Work. For the last 9 months we've been using the Gmail API (~2,000 requests per day) to pull in new emails for our support email accounts.
This is how we originally set it up:
Go to https://console.developers.google.com/project/
Click on the project (or create a new one)
Click on API's & Auth
Click on Credentials
Click on Create new Client ID
Click on Service account
Download a JWT (json) for the account.
Follow the node.js quickstart guide with an installed/native type token for the same account, and authorize it through the console. The JWT tokens did not work unless we did this step, once for each account.
We did this for each of our individual support email accounts to avoid having to turn on domain wide delegation for any of them in the admin console. We were then able to authenticate with the tokens using the officially supported npm library googleapis, similar to this:
var google = require('googleapis');
var jwtClient = new google.auth.JWT(
token.client_email,
null,
token.private_key,
['https://www.googleapis.com/auth/gmail.readonly'],
'supportemail#mycompany.com'
);
jwtClient.authorize(function(err, tokens) {
if (err) {
return cb(err);
}
var gmail = google.gmail('v1');
var requestOptions = {
auth: jwtClient,
userId: 'me',
id: messageId,
format: 'raw'
};
gmail.users.messages.get(requestOptions, function(err, response) {
if (err) {
return cb(err);
}
// do stuff with the response
});
});
Like I said, we used this for a long time and never had any issues. Yesterday around 10am MST every one of the accounts stopped being able to authenticate at the same time, with jwtClient.authorize() suddenly returning the error [Error: unauthorized_client].
I tried doing the same thing with a new token on a new service account (the web interface to get the token has changed quite a bit in the last 9 months), and it returns the same error.
The version of googleapis that we were using was 0.9.7, but we can't get JWT authentication to work on the newest version either.
We opened a ticket with the Google APIs support team, but the support person we spoke with had never read the Gmail API specs before and was ultimately unable to help us, so he redirected us here in order to get in touch with the API engineering support team.
We have noticed that authentication works if we enable the scope for domain wide delegation in the admin console, but we would prefer not to do that. We don't need to impersonate the accounts and would prefer to use an individual JWT for each account.
It turns out that the auth flow we were using was never supported, and probably was broken due to a bugfix on Google's part.
In the question comments #Brandon Jewett-Hall and #Steve Bazyl recommended that we use the installed app auth flow instead, as it allows for indefinite refreshing of access tokens and is supported.
More information about the different auth flows can be found in the Google API docs.

How to reset google oauth 2.0 authorization?

I'm using Google APIs Client Library for JavaScript (Beta) to authorize user google account on web application (for youtube manipulations). Everything works fine, but i have no idea how to "logout" user from my application, i.e. reset access tokens.
For example, following code checks user authorization and if not, shows popup window for user to log into account and permit web-application access to user data:
gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false}, handleAuth);
But client library doesn't have methods to reset authorization.
There is workaround to redirect user to "accounts.google.com/logout", but this
approach is not that i need: thus we logging user off from google account not only from my application, but also anywhere.
Google faq and client library description neither helpful.
Try revoking an access token, that should revoke the actual grant so auto-approvals will stop working. I assume this will solve your issue.
https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke
Its very simple. Just revoke the access.
void RevokeAcess()
{
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
org.apache.http.HttpResponse response = client.execute(post);
}
catch(IOException e)
{
}
}
But it should be in asyncTask
It depends what you mean by resetting authorization. I could think of a three ways of doing this:
Remove authorization on the server
Go to myaccount.google.com/permissions, find your app and remove it. The next time you try to sign in you have to complete full authorization flow with account chooser and consent screen.
Sign out on the client
gapi.auth2.getAuthInstance().signOut();
In this way Google authorization server still remembers your app and the authorization token remains in browser storage.
Sign out and disconnect
gapi.auth2.getAuthInstance().signOut();
gapi.auth2.getAuthInstance().disconnect();
This is equivalent to (1) but on the client.
Simply use: gapi.auth.setToken(null);
Solution for dotnet, call below API and pass the access token, doc - https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke
string url = "https://accounts.google.com/o/oauth2/revoke?token=" + profileToken.ProfileAccessToken;
RestClient client = new RestClient(url);
var req = new RestRequest(Method.POST);
IRestResponse resp = client.Execute(req);

node.js Express/socket.io hybrid application with facebook

I am using express/socket.io combination in my node.js app. So far it's working fine.
Now, I need to store facebook user id and email id (after user being authorized) into session scope. I see there are lot of options and a bit lost here.. in my app, most of the communications happen through socket.io.. ultimately what i want is to access user id and email id anytime in the client side...
var express = require("express"),
fs = require("fs"),
app = express.createServer(
form({ keepExtensions: true })
),
io = require("socket.io");
socket = io.listen(app);
After being authorized, I suggest using the accessToken which is already in the cookies and then sending it through the socket.io and fetching the email and the id using graph.facebook or your own DB. The problem with storing user ID and Email is that it could insecure, since session hijacking could happen.
Facebook has its own experts on security to make sure it wouldn't be hijacked. Use it!
This might help:
http://criso.github.com/fbgraph/
After being authorized you can store the data in your session via express
http://expressjs.com/guide.html#session-support
On a very basic level:
// Get data from facebok and store it on a var `userData`
// server
socket.on('getUserData', function (callback) {
callback(facebookUserData);
});
// client
socekt.emit('getUserData', function(userData) {
console.log(userData);
});

Resources