如何从回调发送JWT到React客户端? [英] How to send JWT to React client from a callback?

查看:57
本文介绍了如何从回调发送JWT到React客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有无密码身份验证的应用程序,该应用程序具有Facebook等社交媒体和邮件的功能.

I am trying to create an application with passwordless authentication, with social medias like Facebook and by mail.

我愚蠢地坚持了一点,也许我不明白.

I'm stupidly stuck a one point, maybe I have not understand something.

让我将项目命名为MyApp:

Lets name my project MyApp:

如果用户尝试从myapp.com/登录到Facebook,他将被重定向到facebook.com/login,然后Facebook将其重定向到myapp.com/callback.

If a user try to log to facebook from myapp.com/, he will be redirected to facebook.com/login, then facebook redirect him to myapp.com/callback.

因此,在我的服务器上,路由//callback完全相同:它们只是将我的React应用发送给用户,但/callback会生成JWT令牌.

So, on my server, the route / and /callback are quite the same: they just send my React app to he user, but /callback generate a JWT token.

这是我的问题:如何在React应用程序的同时将JWT令牌发送给客户端?

也许我错过了其他提供商的某些东西,但是通过邮件进行的无密码原则是一回事:只是用于验证用户身份的链接,只是重定向到/callback,没有外部提供商.

Maybe I have missed something from another provider, but the passwordless principle by mail is the same thing : just a link to authenticate the user, and just a redirection to the /callback, no external provider.

我完全迷路了:(

谢谢!

推荐答案

您可以将JWT放入要将用户重定向到的URL的查询字符串中.然后,您可以通过访问查询字符串在客户端中获取JWT,并将其保存到本地存储中.我本人最近已完成此操作,请在此处的服务器中查看我的存储库,此处的客户端

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

我将回调路由的代码发布到服务器中,并在客户端中获取令牌以获取更多详细信息,请查看上方指向我的存储库的链接

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

回叫路由

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

客户端中的令牌检索

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

这篇关于如何从回调发送JWT到React客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆