I am implementing google oauth2 using googleapisinto my react native mobile app along with a nodejs api for generating user Id's and other information. When I run npm start in my api from vscode I get this error:
const {tokens} = await url.getToken(code)
^^^^^
SyntaxError: Unexpected token 'const'
I am not sure what the issue is as the code is straight from the library and I have tried putting it in a function with no luck either. I am pretty new to react native and would love some help. Code:
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
async function refreshToken() {
oauth2Client.on("tokens", (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
}
Related
I am trying to put Google signin in place for a react native app in iOS along with the NodeJS backend.
The FE uses this library to configure and get auth code from Google.
https://github.com/react-native-google-signin/google-signin
In the backend I am verifying the auth code by sending a API to google endpoint with the following params:-
Backend code sample:-
const GOOGLE_IOS_CLIENT_ID = '123456789-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com';
const GOOGLE_IOS_CLIENT_SECRET = 'REDACTED';
// const GOOGLE_IOS_REDIRECT_URI = 'com.smartappstechnology.kravein';
const GOOGLE_IOS_REDIRECT_URI = 'com.googleusercontent.apps.123456789-abcdefghijklmnopqrstuvwxyz';
export async function get_google_tokens(logging_key, { code }) {
const GRANT_TYPE = 'authorization_code';
try {
const endpoint = `https://oauth2.googleapis.com/token?client_id=${GOOGLE_IOS_CLIENT_ID}&client_secret=${GOOGLE_IOS_CLIENT_SECRET}&code=${code}&grant_type=${GRANT_TYPE}&redirect_uri=${GOOGLE_IOS_REDIRECT_URI}`;
const response = await post_to_API(logging_key, endpoint, {});
return response.body;
} catch (error) {
throw error;
}
};
I am getting a error like this from post_to_api response from Google:-
{
"error": "invalid_request",
"error_description": "Invalid parameter value for redirect_uri: Missing scheme in the URI"
}
I tried changing the redirect_uri values, but still the same issue.
I doubt whether the process I am doing itself is not correct. I experimented most of the ideas from google docs. Nothing works.
Would be helpful if anyone can refer the links of exact documentation of how this is done for react native apps in iOS with nodejs backend.
Thanks in advance
I'm using flutter for my mobile app. I try to add sign in with google. Everything is okay for Flutter side. I'm gettin idToken from mobile app and send to my backend, nodejs.
Now, I want to use this idToken to authenticate user's requests on nodejs backend side with google-auth-library package.
let token = "token"
const CLIENT_ID = "client_id"
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
});
const payload = ticket.getPayload();
const userid = payload['sub'];
console.log(payload)
} catch (error) {
console.log(error)
}
}
verify()
But this code always returns this error => Error: Invalid token signature:
at OAuth2Client.verifySignedJwtWithCertsAsync (\node_modules\google-auth-library\build\src\auth\oauth2client.js:566:19)
What should I do for to verify this idToken on nodejs backend side?
Thanks.
If the idToken that you are passing to the function is from the log of your flutter app, it is likely that you are not getting the entire idToken printed in the log due to the limitations of print().
I used the below code snippet to print out the idToken and used that in the API which gave me a success response.
print('ID TOKEN');
String token = googleAuth.idToken;
while (token.length > 0) {
int initLength = (token.length >= 500 ? 500 : token.length);
print(token.substring(0, initLength));
int endLength = token.length;
token = token.substring(initLength, endLength);
}
Console Error: TypeError: jwt.sign is not a function
Trying out the latest Node version 13 using "type": "module" in my package.json. All is going well so far until I tried to add token authentication with 'jsonwebtoken'. Not sure if it's my code or maybe a compatibility issue? Using their ES Module has some differences from those I use in React.
create new token helper function
import * as jwt from 'jsonwebtoken'
export const newToken = user => {
return jwt.sign({id: user.id}, JWT_SECRET, {
expiresIn: '1d'
})
}
signup function
export const signup = async (req, res, next) => {
// ...
try {
//.. create user code ..
const user = new User({email, password})
user.save()
const token = newToken(user)
return res.json({token, user})
} catch (error) {
console.error(error)
res.status(500).send('Server Error')
}
and everytime I hit the signup route, I get the 500 Error, and a user still gets registered to my database. Hitting a wall a bit..
Thanks and happy holidays guys!
Edit: I just changed my import/export statements to common modules, and I was able to get tokens. Still don't know how to fix this to work with ESModules, or even what the issue is
jsonwebtoken uses default exports to expose its functions (https://github.com/auth0/node-jsonwebtoken/blob/master/index.js).
Therefore, you can load the module using import like this:
import jsonwebtoken from 'jsonwebtoken';
const token = jsonwebtoken.sign({ foo: 'bar' }, 'shhhhh');
What's the difference between using
admin.auth().verifyIdToken() and admin.auth().createSessionCookie() + admin.auth().verifySessionCookie() for authentication purposes and which one should I use in my Express REST API?
Also, doesn't the verifyIdToken already create a session itself that can be refreshed everytime it is called? And does verifying the session cookie do the same?
You create the session to get a token on the client device and use the verify token on the server/cloud.
I get the token from the current user then send it to firebase cloud functions endpoint to verify it.
Endpoint
import * as admin from 'firebase-admin'
const DEPLOYED = false;
admin.initializeApp()
const ValidateToken = (request: any, response: any) => {
const params = {
a: request.body.token, // Client Validation
}
const ValidateToken = admin.auth().verifyIdToken(params.a).catch((error) => { throw { Message:error }});
return Promise.all([ValidateToken]).then((res: any) => {
return DEPLOYED ? res : response.status(200).json(res);
}).catch(error => {
return DEPLOYED ? error : response.status(400).json(error);
});
}
export default ValidateToken;
I'm trying to create JWT tokens in node.js for use with the REST api in firebase, but when I try to use them, I get the error "Error: Invalid claim 'kid' in auth header."
This is my code
http.createServer(function (req, res) {
var payload = {
uid: "bruh"
};
var token = jwt.sign(payload, sact["private_key"], {
algorithm: 'RS256',
issuer: sact["client_email"],
subject: sact["client_email"],
audience: 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
expiresIn: '3600s',
jwtid: sact["private_key_id"],
header: {
"kid": sact["private_key_id"]
}
});
res.writeHead(200);
res.end("It worked. (" + token + ")");
}).listen(port);
These are my requires
var http = require('http');
var jwt = require('jsonwebtoken');
Please use returnSecureToken: true, with correct Spellings
I hope it will solve the problem of Invalid claim 'kid' in the auth header.
This is an issue because you're generating a Firebase ID token, not an access token for the Firebase REST API.
To generate a REST API token I would use the legacy Firebase Token Generator library which still works perfectly well (but only generates REST tokens, not general purpose access tokens).
Note that your Firebase Database secret is now located under the gear icon in the top left of the console.
So I had this error and I've fixed it. Now here is the solution:
You'll need to retrieve the ID-token using an additional function. Here is the function you can use:
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
I implemented it somewhat like this:
//google OAuth login handler
const googleLoginHandler = () => {
const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth()
.signInWithPopup(provider)
.then((result) => {
/** #type {firebase.auth.OAuthCredential} */
setgoogleAuthStatus(true)
// The signed-in user info.
const userId = result.user.uid;
const displayName = result.user.displayName;
const email = result.user.email;
//This is the function for getting the ID-Token
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then((idToken) => {
// Send token to your backend via HTTPS
console.log(idToken)
}).catch((error) => {
// Handle error
console.log(error.message)
alert(error.message)
});
console.log(result)
}).catch((error) => {
console.log(error)
// Handle Errors here.
alert(error.message)
})
}
The id token you get by this method can be used to access the firebase real-time database and other firebase services.
check out these links for more details:
https://firebase.google.com/docs/auth/admin/verify-id-tokens#retrieve_id_tokens_on_clients
https://firebase.google.com/docs/database/rest/auth#firebase_id_tokens