Using a firebase idToken from a mobile native layer in a webview - firebase-authentication

I'm using Firebase in a native application (Game Center auth) and I'd also like to have the same identity persist to web views in the application via the Firebase JS sdk.
I can get the idToken at the native layer using the following snippet:
let currentUser = Auth.auth().currentUser;
currentUser?.getIDTokenForcingRefresh(true) { idToken, error in
if let error = error {
call.reject("Error: \(error.localizedDescription).")
return
}
if let idToken = idToken {
var res = JSObject();
res["idToken"] = idToken;
call.resolve(res);
} else {
call.reject("Id token not present", "NO_ID_TOKEN")
}
}
But I'm not sure how to use this idToken in the JS layer to sign in. I tried the OAuthProvider with gc.apple.com using the returned ID token but it didn't work.
// this is the id token from the native layer
const { idToken } = await getIDToken();
const provider = new OAuthProvider('gc.apple.com');
const credential = provider.credential({
idToken
});
const auth = getAuth();
await signInWithCredential(auth, credential);
return result;
Thanks in advance for any suggestions!

Related

OAuth 2Client: Invalid token signature

I wanted to handle my user auth by google.
async verify(token) {
try {
const ticket = await client.verifyIdToken({
idToken:token,
audience: '245409008225-isc00em81fk0vs423pm4jmgc2hcma5jj.apps.googleusercontent.com',
});
const payload = ticket.getPayload();
return payload
} catch (error) {
console.log(error)
}
this code works fine, only for first time to create user in DB. And i save this token to localstorage and retrieve it every time to validate that user is authentificated. Here is my code:
async isAuth(token) {
if (!token) {
false
}
const userData = tokenService.verify(token);
const tokenFromDb = await tokenService.findToken(token);
if (!userData || !tokenFromDb) {
throw ApiError.UnAuthorizedError();
}
const user = await User.findOne({where: {email: userData.email}});
await tokenService.saveToken(token);
return true;
}
I did google, and i supposed to define jwk key for google auth api? But I can't find real solution. So, hope you guys can help me. I never used before google auth. For now I have this solution by making request to this api https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=token and getting from there my user email

Google email offline access using react native expo app

I am creating one app using react native expo, which allow end user to login by their google account , and then applicaton try to save the access_token so that server based applicatin can use this to send the email on their behalf ,
But when using google sing in , i am not getting refresh token and not able to send the email ,
Here is code example which i am using
I tried below method to get the access request
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: "XXXXXXX",
androidClientId:"XXXXXXX",
iosClientId:"XXXXXXX"
});
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
const sendNotification=useNotification()
//console.log(sendNotification)
useEffect(() => {
if (response?.type === "success") {
const { id_token } = response.params;
const auth = getAuth();
const credential = GoogleAuthProvider.credential(id_token);
signInWithCredential(auth, credential);
let decoded = jwt_decode(id_token);
socialLogin(decoded)
}
}, [response]);
And on server using this code to sending email
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
// Replace with the code you received from Google
const code = 'XXXXXXX';
//const code="XXXXXXX"
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.getToken(code).then(({ tokens }) => {
console.log('first')
const tokenPath = path.join(__dirname, 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(tokens));
console.log('Access token and refresh token stored to token.json');
}).catch(err=>console.log(err));
async function signInWithGoogleAsync() {
try {
const result = await Google.logInAsync({
androidClientId: YOUR_CLIENT_ID_HERE,
scopes: ["profile", "email"],
});
if (result.type === "success") {
onSignIn(result);
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
}
Well, I tried to create an application with Google login. To use the Google Sign-In method in a React Native Expo app, you will need to perform the following steps:
Set up a project in the Google Cloud Console and obtain a configuration file for your app.
Install the expo-google-sign-in package in your React Native app.
Import the GoogleSignIn object from the expo-google-sign-in package and use the initAsync method to initialize the Google Sign-In process.
Use the GoogleSignIn.askForPlayServicesAsync method to check if the device has the required Google Play Services installed.
Use the GoogleSignIn.signInAsync method to prompt the user to sign in with their Google account.
Once the user has signed in, you can use the accessToken and refreshToken properties of the returned object to make authorized requests to the Google APIs.
The code lines for the above steps are:
import { GoogleSignIn } from 'expo-google-sign-in';
// Initialize the Google Sign-In process
await GoogleSignIn.initAsync({
// Your config. values
});
// Check if the device has the required Google Play Services installed
const isPlayServicesAvailable = await GoogleSignIn.askForPlayServicesAsync();
if (!isPlayServicesAvailable) {
console.error('Google Play services are not available on this device.');
return;
}
// Prompt the user to sign in with their Google account
const { accessToken, refreshToken } = await GoogleSignIn.signInAsync();

How to decode token in Vue.js?

I got a token after I successfully logged in. I need to be able to parse + decode/descrypt it to see the permission information inside that. How would I do that?
I tried
// token is accessible
var decoded = jwt_decode(token)
console.log('decoded', decoded)
I kept getting
Here is my token
"e2kEd...LIPH0="
I'm using Vue.js v2.
"InvalidTokenError"
How do I know if my token is compatible with jwt_decode() ?
Try #2
Paste my token here :
https://jwt.io/
Try #3
If I base64_decode() it, I see this
{iversI�iuser{inameSibheng#test.comiapplSiVCiserv[$U#i0-�8rDaiperm[{inameSiEIDiparm[{inameSiAPPidataSiVC}]idataSi COLM,DFQL}{inameSiEIDiparm[{inameSiAPPidataSi*}]idataSiECNVF,CNVZ,DFQL,DJ1L,FV8Z,HY0B,N94X,RD8L,W3XV,X3CY,XPH4,YX4N,ZR10,COLM}{inameSi
VC_GET_EIDiparm[{inameSiBRANDidataSiBROO}]idataT}]}irelm[$U#i'$}s,9ialgoSi
SHA256-RSAisign[$U#I�ZϏpRV,lYt
>Ni_h{,*wE&!?`h±VmSr,n>쏝?L+7_d]JIVl1s:Gɳ<}`
The core piece of info that I really really need is BROO
It's there, but I can't seem to parse it.
This decoded works for nuxt js and vue js. Just install vue-jwt-decode and follow this code. Good luck
Node js Login Controller
static async loginUser(req, res){
req.body.password = await hashPassword(req.body.password);
const user = req.body;
await UserServiceClass.loginUser(user).
then((respond)=>{
const user = {id:respond._id,username:respond.username};
const access_token = generateToken(user);
const refresh_token = refreshToken(user);
res.status(200).json({access_token:access_token, refresh_token:refresh_token});
}).
catch((err)=>{
res.status(500).json({login_error:err})
})
}
Vue js Login Page
<script setup>
import VueJwtDecode from 'vue-jwt-decode';
let current_user = reactive({})
const login = async () => {
console.log(user);
await useFetch('http://localhost:4000/user/login',{
method:'POST',
body:user
}).then((respond)=>{
//Keep Token inside of window localstorage
localStorage.setItem('user', respond.data.value.access_token);
}).catch((err)=>{
console.log('err : ', err);
})
}
const decode = () => {
//Take token from window local storage
let token = localStorage.getItem('user');
try{
let decoded = VueJwtDecode.decode(token)
current_user = decoded;
}
catch(err){
console.log('token is null: ',err);
}
}
</script>

OctoKit with Auth0 (Github Login) in NextJS

I am building a Next JS app that has Github Login through Auth0 and uses the Octokit to fetch user info / repos.
In order to get the IDP I had to setup a management api in auth0. https://community.auth0.com/t/can-i-get-the-github-access-token/47237 which I have setup in my NodeJs server to hide the management api token as : GET /getaccesstoken endpoint
On the client side : /chooserepo page, I have the following code :
const chooserepo = (props) => {
const octokit = new Octokit({
auth: props.accessToken,
});
async function run() {
const res = await octokit.request("GET /user");
console.log("authenticated as ", res.data);
}
run();
And
export const getServerSideProps = withPageAuthRequired({
async getServerSideProps({ req, params }) {
let { user } = getSession(req);
console.log("user from get session ", user);
let url = "http://localhost:4000/getaccesstoken/" + user.sub;
let data = await fetch(url);
let resData = await data.text();
return {
props: { accessToken: resData }, // will be passed to the page component as props
};
},
});
However, I keep getting Bad credentials error. If I directly put the access token in the Octokit it seems to work well, but doesn't work when it's fetching the access token from the server.
It seems like Octokit instance is created before server side props are sent. How do I fix it ?
I figured out the error by comparing the difference between the request headers when hardcoding and fetching access token from server. Turns out quotes and backslashes need to be replaced (and aren't visible when just console logging)

React native firebase google login access Token returns Undefined

My app has a Firebase based Google login. I am trying to get access Token but getting undefined.I am getting the idToken but I need AccessToken and refresh Tokens.I need help
Here is my code :
GoogleSignin.configure({
scopes: ['profile', 'email','https://www.googleapis.com/auth/calendar'], //adding calender scope
webClientId: '863338747777-9bshdpj951ga8nik9tbtua52ji0h06k4.apps.googleusercontent.com',
offlineAccess: true,
forceCodeForRefreshToken: true,
});
const onGoogleButtonPress = async()=> {
try
{
await GoogleSignin.hasPlayServices();
const {accessToken, idToken} = await GoogleSignin.signIn();
const credential = auth.GoogleAuthProvider.credential(
idToken,
accessToken,
);
await auth().signInWithCredential(credential);
console.log('IDToken: ',idToken,accessToken)
console.log('AccessToken: ',accessToken)
}
catch(error)
{
console.log(error)
}
finally{
setLoggedIn(true)
}
}`
I found a solution for my own problem. I am using a older library of React native google sign in. The new one is react native login google. The new package is returning the accessToken as well. So to get the refresh token we need to use a api
This is the Link for that .
We need several headers
Take a look at them
You will get the serverAuthCode from the googleSignin function while signing in .
const UserInfo = await GoogleSignin.signIn();
Console log the UserInfo to get the serverAuthCode ,AccessToken and Refresh Token
This is the Package I am using for googlesignIn
Prabhakar I hope this link helpful for him.
https://www.freecodecamp.org/news/google-login-with-react-native-and-firebase/
Thank You