score:5

Accepted answer

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:

  1. generate a random token (in my case it was 64 alphanumeric characters)
  2. 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);
  1. pass the token into the query param on redirect url
res.redirect(`http://example.com/jwt?token=${randomtoken}`);
  1. 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);
});
  1. 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.


Related Query

More Query from same tag