score:5
you can put the jwt into the query string of the url you want to redirect the user to. then you get the jwt in the client from accessing the query string, and save it to local storage. i've done it myself recently check out my repo server here, client here
edit: i post the code of the callback route in the server and getting the token in the client for more details check the links to my repo above
callback route
app.get('/auth/github/callback', (req,res) => {
githubauth.code.gettoken(req.originalurl)
.then(user => {
console.log(user.data);
return fetch('https://api.github.com/user?access_token=' + user.accesstoken);
})
.then(result => {
return result.json();
})
.then(json => {
//console.log(json);
//res.send(json);
return user.findone({githubid: json.id})
.then(currentuser => {
if(currentuser){ // user already exists
console.log('user exists with github login: ' + currentuser);
return currentuser;
}
else{ // user doesn't exist
// saved automatically using mongoose, returns promise
return new user({
username: json.login,
githubid: json.id
}).save()
.then(newuser => {
console.log('new user created with github login: ' + newuser);
return newuser;
});
}
});
})
.then(user => {
// now use user data to create a jwt
const token = jwt.sign({id: user._id}, process.env.jwt_encryption_key, {
expiresin: 86400 // expires in 24 hours
});
const encodedtoken = encodeuricomponent(token);
res.status(200);
res.redirect('/profile?token=' + encodedtoken);
})
.catch(err => console.log(err));
});
token retrieval in client
class userprofile extends react.component{
constructor(props){
super(props);
this.state = {username: ''};
}
componentdidmount(){
const query = new urlsearchparams(this.props.location.search)
// when the url is /the-path?some-key=a-value ...
let token = query.get('token')
console.log(token)
if(token){ // it's the first time we receive the token
// we save it
console.log('saving token');
localstorage.setitem('userjwt', token);
}
else{
// if qrstring is empty we load the token from storage
token = localstorage.userjwt;
console.log('loading token: ' + token);
}
if(token){
const headers = new headers({
'x-access-token': token
});
const reqoptions = {
method: 'get',
headers: headers
};
fetch('/user', reqoptions)
.then(res => res.json())
.then(user => {
console.log(user);
console.log(user.username);
this.setstate({username: user.username});
})
}
}
render(){
if(this.state.username === ''){
return(
<div classname="social-profile">
<h2>login first</h2>
</div>
);
}
else{
return(
<div classname="social-profile">
<h2>user: {this.state.username}</h2>
</div>
);
}
}
}
score:2
this is how i do it in my app, note that this is a slight improvement from dimitris's answer because of the security concern mentioned by thomas linked to here, and requires redis (or database if you prefer it).
instead of passing the jwt directly on the query parameter, what i did was:
- generate a random token (in my case it was 64 alphanumeric characters)
- store to your redis with the random token as the key, and jwt as the value with short ttl (i set mine to 1 minute)
redisclient.set(randomtoken, jwttoken, "ex", 60);
- pass the token into the query param on redirect url
res.redirect(`http://example.com/jwt?token=${randomtoken}`);
- on your client, get the token from query param, and send a http request to your express route to get jwt from redis with the token
router.get("/getjwt/:token", (req, res, next) => {
const jwt = redisclient.get(token);
// delete the jwt from redis
redisclient.del(token);
// you can return 401 if jwt doesnt exists on the redis server
res.json(jwt);
});
- store jwt in client's local storage
this requires more work, resource and one extra http request to get the jwt, but i think it's worth it considering the risk of passing jwt directly on the query param. it's not like the user will do authentication every minute anyway.
Source: stackoverflow.com
Related Query
- How to send JWT to React client from a callback?
- How to send jwt token from expressjs to react application?
- How to send FormData attribute with an array of strings from React Client to Django + Django Rest Framework API
- I do not know how to store json data from an api call within a nodejs express server, and send it to a react native client
- How can I send image from client to server node js react
- How to send data in csv format from web api controller to react client side for creating visualisations
- How do I store JWT and send them with every request using react
- How to send cookies to socket.io client from server?
- How to send form data from React to express
- How to return a React memoized callback from factory function
- How to send email from my react web application
- How do I use firebase storage from a client side React app?
- How to send CSRF Cookie from React to Django Rest Framework with Axios
- How do I send React Application context from non react class?
- React / Sentry for Error Reporting - How to not send errors from dev / localhost
- How to send file from React/Next.js client UI to Node server and next to Flask service
- Get Message From Kafka, send to Rsocket and Receive it from React client
- How to load JWT token on to React during initial download after authentication from Multi Page Application?
- How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script?
- How to prevent a route from registering before jwt verifies react
- How to send requests from nginx & react container to a spring boot container?
- How to update parent state from child component in React + send a paramater
- How is an argument for a callback in React being passed from the child component to the parent component?
- How to send url params from react to express api call
- How to access component method in React from a WebSocket callback
- How to send a fetch post request from react component to backend
- How to send data from express server to client on Next js?
- How to send data from react and use the request body in express, using Axios?
- How can I make a request to an API based on the response from another request? React Hook "useSwr" cannot be called inside a callback
- How to send a file/image from React to node.js server
More Query from same tag
- Not able to render pdf by passing Uint8Array in the viewer.html file parameter while using pdfjs
- Why does this approach to drawing a line in an SVG element in react not work?
- Openweather api call failure in react.js
- Random shuffling of tags in react
- React passed data from child to parent not logging in parent
- React and real DOM cooperation in LeafletJS
- check if two arrays contain identical objects - react componentDidUpdate
- How can I run code when event is scheduled in embedded Calendly widget?
- How to set a Modal popup with an image in React
- fix label width to use properly the outlined input
- Change not able to update on commentsRef.on("child_changed", (data) => {
- React: Validate that no extra props has been passed
- How can i use for-loop in styled-components?
- React not routing on button click
- React not rendering props but can see in console.log
- ReactJS: Get multiple checkboxes value with material-ui
- url-loader configuration in webpack is loading the images from different path in React JS project
- Dynamically updating index.html file in production build of a create react app
- How to use dynamic image path in next js
- Calculate new state by old state and result of a promise
- Combinations of specific elements in array
- dynamic flexbox layout controlled by javascript
- React Router | Component not getting rendered
- browserify - exclude code blocks?
- Adding multiple conditions within a Link in React
- addEventListeners and React not working as planned
- .env returning data unfeind in react
- "wheel" event is being fired infinitly and crashing my website
- React Babel polyfill for Object.values()
- Unexpected token error for react fixed-data-table