How to decode token in Vue.js? - 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>

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();

Next JS can not access to the localStorage

I building an application with next JS.
When authenticating the user via login page I can store the access token and refresh token to the local storage normally. But during authorization, when I am trying to get the access token from local storage I am getting an error called localstorage is not defined.
I guess because next JS is rendering the page on the server side, and there is not localstorage on the server.
So, how can I get around this? Any help would be appriciated.
// Set access token and refresh token to localstorage
const setTokens = (accessToken, refreshToken) => {
localStorage.setItem("accessToken", accessToken);
localStorage.setItem("refreshToken", refreshToken);
};
// Get access token from localstorage
const getAccessToken = () => {
return localStorage.getItem("accessToken");
};
// Get refresh token from localstorage
const getRefreshToken = () => {
return localStorage.getItem("refreshToken");
};
// Remove access token and refresh token from localstorage
const removeTokens = () => {
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
};
export { setTokens, getAccessToken, getRefreshToken, removeTokens };
From above code only setToken() function is working.
use your function in useEffect
const [accessToken, setAccessToken] = useState(null)
const [refreshToken, setRefreshToken] = useState(null)
useEffect(() => {
try {
const accToken = getAccessToken();
const refToken = getRefreshToken();
setAccessToken(accToken)
setRefreshToken(refToken)
} catch (e) {
}
}, [])

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)

Get localStorage in NextJs getInitialProps

I working with localStorage token in my next.js application. I tried to get the localStorage on page getInitialProps but, it returns undefined.
Here is an example,
Dashboard.getInitialProps = async () => {
const token = localStorage.getItem('auth');
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { 'Authorization': token }
});
const data = await res.json();
return { page: data };
}
For the initial page load, getInitialProps will run on the server
only. getInitialProps will then run on the client when navigating to a
different route via the next/link component or by using next/router. Docs
This means you will not be able to access localStorage(client-side-only) all the time and will have to handle it:
Dashboard.getInitialProps = async ({ req }) => {
let token;
if (req) {
// server
return { page: {} };
} else {
// client
const token = localStorage.getItem("auth");
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { Authorization: token },
});
const data = await res.json();
return { page: data };
}
};
If you want to get the user's token for the initial page load, you have to store the token in cookies instead of localStorage which #alejandro also mentioned in the comment.