How to provide frontend with JSON web token after server authentication?

前端 未结 4 599
南旧
南旧 2021-02-04 04:57

So far I have only dealt with server-rendered apps, where after a user logs in via username/password or using an OAuth provider (Facebook etc.), the server just sets a session c

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 05:38

    here is a login request from the server side. it's storing the token in the header:

    router.post('/api/users/login', function (req, res) {
      var body = _.pick(req.body, 'username', 'password');
      var userInfo;
    
    models.User.authenticate(body).then(function (user) {
          var token = user.generateToken('authentication');
          userInfo = user;
    
          return models.Token.create({
            token: token
          });
        }).then(function (tokenInstance) {
          res.header('Auth', tokenInstance.get('token')).json(userInfo.toPublicJSON());
        }).catch(function () {
          res.status(401).send();
        });
    });
    

    here is the login request on the react side, where I am grabbing the token from the header and setting the token in local storage once the username and password pass authentication:

    handleNewData (creds) {
        const { authenticated } = this.state;
        const loginUser = {
            username: creds.username,
            password: creds.password
        }
        fetch('/api/users/login', {
            method: 'post',
            body: JSON.stringify(loginUser),
            headers: {
                'Authorization': 'Basic'+btoa('username:password'),
                'content-type': 'application/json',
                'accept': 'application/json'
            },
            credentials: 'include'
        }).then((response) => {
            if (response.statusText === "OK"){
                localStorage.setItem('token', response.headers.get('Auth'));
                browserHistory.push('route');
                response.json();
            } else {
                alert ('Incorrect Login Credentials');
            }
        })
    }
    

提交回复
热议问题