Extend the Expiry Time and Date in Firebase OAuth2 access JWT Token - node.js

I want To set the maximum Expiry Date and Time for Firebase OAuth2 JWT Access Token - https://firebase.google.com/docs/database/rest/auth
I tried some methods Not working. Here is the Google's Code to generate an Access Token for Firebase Real-time Database
Google APIs Node.js Client
var {google} = require("googleapis");
// Load the service account key JSON file.
var serviceAccount = require("./myfileauth.json");
// Define the required scopes.
var scopes = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
console.log(accessToken);
}
});
but it's working for a Short time only I want to Increase its Expiry date and time...

If you want to have longer-lived session tokens, I recommend looking into session cookies. These can be created from the Firebase Admin SDK, and list this as one advantage:
Ability to create session cookies with custom expiration times ranging from 5 minutes to 2 weeks.
It works by taking the ID token (from the client) that is part of the normal Firebase authentication flow, and exchanging that for a session cookie (on the server) with:
// Set session expiration to 5 days.
const expiresIn = 60 * 60 * 24 * 5 * 1000;
// Create the session cookie. This will also verify the ID token in the process.
// The session cookie will have the same claims as the ID token.
// To only allow session cookie setting on recent sign-in, auth_time in ID token
// can be checked to ensure user was recently signed in before creating a session cookie.
admin.auth().createSessionCookie(idToken, {expiresIn}).then((sessionCookie) => { ...

Related

Azure ADAL - How to get refresh token / how to refresh access token for nodejs backend server to server connection?

I'm using adal-node module for my Node JS backend to write file to Azure Storage. The authentication works fine, but the access token I got only valid for 1 hour. And so far I couldn't find anyway to refresh my access token. Can someone advise?
I've tried to get refresh token. But the auth function I'm using below don't send refresh token back. I've also try to just create a new token after a while using the same auth function, but it turns out the token is always the same.
Here's the code I use to get the access token.
var AuthenticationContext = require('adal-node').AuthenticationContext;
var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant.onmicrosoft.com'; // AAD Tenant name.
var authorityUrl = authorityHostUrl + '/' + tenant;
var applicationId = 'yourApplicationIdHere'; // Application Id of app registered under AAD.
var clientSecret = 'yourAADIssuedClientSecretHere'; // Secret generated for app. Read this environment variable.
var resource = '00000002-0000-0000-c000-000000000000'; // URI that identifies the resource for which the token is valid.
var context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
} else {
console.log(tokenResponse);
}
});
Need some way to refresh my access token so that my long running job wouldn't stop.
Just get a new access token.
In the Client Credentials flow, a refresh token is not returned. (See Section 4.4.3 of the OAuth 2.0 spec.)

How to manually expire the token of login cognito -user in Nodejs

I am using aws-cognito for authentication.
In my application, user admin can remove the role of other user. In that case if user is already login to the application/react,he still can access the page until token expire. and token can only expire if he logout.
Can we manually expire the session of any cognito user?
You will only need UserPoolId and ClientId. You can store these values to use it when you want to log out your user. It shouldn't matter whether the role is removed by admin since your paramaters is not dependent on the user's role.
var poolData = {
UserPoolId: '_', // Userpool id
ClientId: '_' // Client app id you can find in your userpool "General settings" -> "App clients"
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.signOut();
}
https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html#using-amazon-cognito-user-identity-pools-javascript-examples-signout-user

Access Token vs Refresh Token NodeJS

I'm new to JWT which stands for Json Web Token. I've confused with couple of its terms: Access Token and Refresh Token.
purpose: I wanna implement a user authorization which logs the user out after two hours of being idle (don't request the site or exit from the browser).
To reach that goal I'm trying to follow the below items:
After the user registers/logs-in in the site, I create Access Token and Refresh Token.
Save the refresh token in the DB or cookie.
After 15 minutes the users token the access token expired.
In case of a user being idle for 2 hours, I remove the refresh token from the cookie or DB, else I renew the access token using refresh token.
Is there any optimized way to reach that purpose?
First of all u need to understand the principle of JWT's and how they are passed between server and client and matched server-side against a secret - here's the doc
The payload can be any arbitrary user data - i.E.: just a usrname or id
Basically you need a service that generates a token on successful authentication (when the user logs in with the proper credentials, i.E.: usr & pwd) and create an additional header with the token to be used in further requests to the server.
// INFO: Function to create headers, add token, to be used in HTTP requests
createAuthenticationHeaders() {
this.loadToken(); // INFO: Get token so it can be attached to headers
// INFO: Headers configuration options
this.options = new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json', // INFO: Format set to JSON
'authorization': this.authToken // INFO: Attach token
})
});
}
// INFO: Function to get token from client local storage
loadToken() {
this.authToken = localStorage.getItem('token');; // Get token and asssign to
variable to be used elsewhere
}
and some functionality to store the user-status i.E.:
// INFO: Function to store user's data in client local storage
storeUserData(token, user) {
localStorage.setItem('token', token); // INFO: Set token in local storage
localStorage.setItem('user', JSON.stringify(user)); // INFO: Set user in local
storage as string
this.authToken = token; // INFO: Assign token to be used elsewhere
this.user = user; // INFO: Set user to be used elsewhere
}
and a logout function to destroy the token in the local storage, i.E.:
// INFO: Function for logging out
logout() {
this.authToken = null; // INFO: Set token to null
this.user = null; // INFO: Set user to null
localStorage.clear(); // INFO: Clear local storage
}
In case you use npm's jsonwebtoken, you can set the ttl of the token when generating it:
const token = jwt.sign({ id: idDB }, "secret", { expiresIn: '24h' });
or whatever ttl you desire, the string "secret" refers to the secret that's matched against the server.
btw: If I understand you correctly, your points number 3 and 4 contradict each other..
After 15 minutes the users token the access token expired.
In case of a user being idle for 2 hours, I remove the refresh token from the cookie or DB, else I renew the access token using refresh token.
in case 4 it will be destroyed anyways in 15 mins if you implemented the logic of number 3 correctly

Firebase acces and id tokens

I'd like to know how to get both access and id tokens in Node.js SDK Firebase.
When I print user object after signUpWithEmailAndPassword, I see that accessToken is one the properties there, but then when i use method on user object called getIdToken, I get the same token I saw in users object. Why then it is not called getAccessToken???
What I want is return to the client object containing access, id, refresh tokens and expiration time.
P.S. I can't just say user.stsTokenManager.accessToken as it tells me that there is no already such property.
This is only an internal name. This "accessToken" is really the Firebase ID token. You should rely on the officially supported getIdToken to get that Firebase ID token. Firebase also recently added getIdTokenResult which provides the ID token and additional information like expiration time and other token related information without you having to parse it from the ID token. You can also get the refreshToken from the user via firebase.auth().currentUser.refreshToken.
const result = await getRedirectResult(auth);
if (result) {
const provider = new FacebookAuthProvider();
// This is the signed-in user
const user = result.user;
// This gives you a Access Token.
const credential = provider.credentialFromResult(auth, result);
const accessToken = credential.accessToken;
// this gives you the id token
const idToken = user.getIdToken();
}

What is the difference between Bearer Token and Refresh Token?

In ServiceStack, I am using JwtAuthProvider, where I got Bearer Token and Refresh token so how do I verify the token and authorize the web api service?
Code:
var client = new JsvServiceClient(ListeningOn) { UserName = "tuser", Password = "password" };
client.Send<AssignRolesResponse>(new AssignRoles
{
UserName = "tuser",
Roles = new ArrayOfString("TestRole"),
Permissions = new ArrayOfString("GetStatus")
});
var jwtToken = client.Send(new Authenticate()).BearerToken;
Here, What is the use of 'jwtToken' value? user is already authorized and authenticated so I don't get the idea why the token needed here?
Could anyone suggest me how do I take advantage of that token?
JWT Config:
this.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[]
{
new JwtAuthProvider(AppSettings) {
RequireSecureConnection = false,
AuthKey = AesUtils.CreateKey(),
//CreatePayloadFilter = (payload,session) =>
// payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString(),
CreatePayloadFilter = (jwtPayload, session) =>
jwtPayload["exp"] = DateTime.UtcNow.AddSeconds(-1).ToUnixTime().ToString()
},
new CredentialsAuthProvider(AppSettings),
new BasicAuthProvider()
}));
Please see this article on the purpose of JWT Refresh Tokens.
In summary, the BearerToken the actual JWT and what used to authenticate via JWT. It's contains a stateless snapshot of the Users Session and is typically a short-lived token, which after it expires needs to contact the Auth Server to fetch a new JWT Token.
The RefreshToken is a longer-lived token which can be used to request new JWT Tokens transparently (i.e without forcing the User to manually re-authenticate) and will be populated with the latest snapshot of the Users Session.
The shorter the lifetime of JWT BearerTokens the less stale the stateless Session information that's stored in the JWT but the more often the RefreshToken will need to be used to fetch an updated BearerToken. Only after a new BearerToken is requested will session information like the Roles and Permissions has or whether they're locked out.
The lifetime of each Token is configurable with the ExpireTokensIn and ExpireRefreshTokensIn JwtAuthProvider properties.
ServiceStack Clients built-in support for JWT and Refresh Tokens
ServiceStack's Service Clients automatically take care of transparently fetching new JWT Tokens using RefreshTokens. You would typically populate both the BearerToken and RefreshToken when initializing your Service Client, e.g:
var authResponse = authClient.Send(new Authenticate());
var client = new JsonServiceClient(baseUrl) {
BearerToken = authResponse.BearerToken,
RefreshToken = authResponse.RefreshToken,
};
The BearerToken is needed to make the request although since the Service Client automatically fetches new JWT Tokens with the configured RefreshToken you only need to populate the RefreshToken:
var client = new JsonServiceClient(baseUrl) {
RefreshToken = authResponse.RefreshToken,
};
As ServiceStack will automatically fetch a new JWT Token on first use, but you can save a round-trip by populating both.

Resources