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
Related
I am trying this official discord bot example https://github.com/discord/discord-example-app. While running the code and setting up the interaction URL in discord developer portal. I am getting "Bad request signature" error in NodeJS.
https://user-images.githubusercontent.com/90953201/216832674-22db23a0-6a9f-4d8d-8bef-7b90d074d11b.png
The bot verification code is as per below
app.js
// Parse request body and verifies incoming requests using discord-interactions package
app.use(express.json({verify: VerifyDiscordRequest(process.env.PUBLIC_KEY) }));
utils.js
export function VerifyDiscordRequest(clientKey) {
return function (req, res, buf, encoding) {
const signature = req.get('X-Signature-Ed25519');
const timestamp = req.get('X-Signature-Timestamp');
const isValidRequest = verifyKey(buf, signature, timestamp, clientKey);
if (!isValidRequest) {
res.status(401).send('Bad request signature');
throw new Error('Bad request signature');
}
};
}
I am assuming express body-parser is causing some issues but not completely sure.
Reference - https://github.com/discord/discord-example-app
I currently have 2 directories in my project, one for backend using express/axios and one for my React frontend. I have a discord authentication page which correctly authenticates and saves a user to my SQL database and express automatically redirects and sends the user information to an html page.
The problem is when I go to redirect the user after authenticating. I want to redirect them back to my React web application and also send the user information to the frontend. I cannot figure out how to do this without using ejs and other third-party applications.
This is my backend code and I want to use res.send(), res.redirect() etc... to be able to give the route which my react page is currently running (localhost:3000) the required data.
const { code } = req.query;
if (code) {
try {
const { data: credentials } = await exchangeAccessCodeForCredentials({
client_id: ID,
client_secret: SECRET,
grant_type: "authorization_code",
code: code.toString(),
redirect_uri: REDIRECT_URL,
});
const { data: user } = await getDiscordUserDetails(credentials.access_token);
const newUser = await createUser(buildUser(user, credentials));
res.setHeader("Auth", newUser.discordId);
res.redirect("http://localhost:3000");
} catch (err) {
console.log(err);
res.sendStatus(400);
}
}
}
I've also tried to retrieve that data from the headers, but the custom headers I set never show up when I log them...
async function trying() {
var req = new XMLHttpRequest();
req.open("GET", document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
}
Please let me know if there is a way to easily send data to the frontend using only express and React. Thank you
What you need to do, is send all the information of the user to your react application, and handle of the redirection there.
So you have two scenarios:
The authentication is succesful, so you return the user information from your backend, and your React app should redirect to the other page.
The authentication failed, so your return an error or a 403 status code, and your React app should show the error there.
Im using the graphql api endpoint to call the endpoint to retrieve a posts information using the function below.
async function getInstagramData(url: string) {
const postHash = '';
const postAPI = `https://www.instagram.com/graphql/query/?query_hash=${postHash}&variables=${encodeURIComponent(
`{"shortcode":"${getShortcode(url)}"}`
)}`;
console.log(postAPI);
try {
const respone = await axios.get(postAPI);
const json = await respone.data;
if (!json.data) return null;
return json.data['shortcode_media'];
} catch (error) {
console.log(error);
return null;
}
}
This works fine locally but doesn't work on the server as I get a 401 unauthorized. After looking into the response I found
data: {
message: 'Please wait a few minutes before you try again.',
require_login: true,
status: 'fail'
}
My question would be how I should log into the API.
From my understanding, I have two solutions (not sure if any of them are possible)
Call the Login API Endpoint store the cookies that are returned and use them when calling the endpoint above.
Is it possible to use a facebook APP ID in my get request to call the request via my application.
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);
}
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);
});
}