Send jwt in header by GET

Asked

Viewed 377 times

1

Hello I would like to know how I could send a jwt in my header to consume in my API, a route get to catch users ( need auth )

my api to catch users:

   app.route('/users')
        .all(app.auth.authenticate())
        .get((req,res)=>{
            usersController
                .getAll()
                .then(data => {
                    res.json(data);
                })
                .catch(error=>{
                    console.log(error);
                    res.status(400);
                });
    })

and my jwt auth ( . all(app.auth.authenticate()) ) :

     authenticate: () => passport.authenticate('jwt', jwtConfig.session)

on my front end I don’t know how I’m going to make this request:

getDate = () => {
        console.log(JSON.parse(sessionStorage.getItem('token')));
        const data = {token: sessionStorage.getItem('token')};
        const requestInfo = {
            method:'GET',
            body: JSON.stringify({data}),
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
        };
        console.log('chegouaq');
        fetch('http://localhost:9000/users', requestInfo)
        .then(response => {
            console.log('chegouaq2');
            if(response.ok){
                return response.json();
            }
            throw new Error("Token Invalido..")
        })
        .then(data => {
            console.log(JSON.stringify(data));
            return;
        })
        .catch(e => {
            this.setState({message: e.message})
            console.error(e);
        });
    }

I know get doesn’t accept the body, but I have no idea how to send my jwt in the header.

///

My way of generating jwt when logging in:

app.route('/login')
        .post(async (req,res)=>{

            try {
                const response = await usersControllers.signin(req.body);
                const login = response.login;
                console.log(login);
                if(login.id && login.isValid){
                    const payload = {id: login.id};
                    res.json({
                        token: jwt.sign({data:payload}, app.config.jwt.secret,{expiresIn: '60'}),
                        response
                    });
                }else{
                    console.log('entrou here');
                    res.sendStatus(HttpStatus.UNAUTHORIZED);
                } 
            } catch (error) {
                console.log('entrou here');
                console.error(error.message);
                res.sendStatus(HttpStatus.UNAUTHORIZED);
            }
        })

and my Strategy:

const strategy = new Strategy(options,(payload, done) => {

        Users
        .findOne({where: payload.id})
        .then(user => {

            if(user){
                return done(null,{
                    id: user.id,
                    login: user.login
                });
            }
            return done(null,false);
        })
        .catch(error => done(error,null));

    });

    passport.use(strategy);
    return {
        initialize: () => passport.initialize(),
        authenticate: () => passport.authenticate('jwt', jwtConfig.session)
    };
}
  • 1

    It would be the same way you’re going through the 'Content-Type': 'application/json'. In place of Content-type would be the header name your API expects to receive from JWT and instead of application/json will your JWT. Would this be your question?

  • Yes it would be, could you answer for me to give the positive vote? In Case: I have this route: app.route('/users') I would have to add a parameter to my auth: . all(app.auth.authenticate()), authenticate: () => Passport.authenticate('jwt', jwtConfig.Session)

  • I don’t know if I’m doing jwt auth correctly, can I edit the question with the method I use my jwt? If you can give me some hint to improve on the code.

1 answer

1


In the same way you indicate the Content-type it is possible to indicate a Authorization (for example):

// (...)
headers: new Headers({
    'Content-Type': 'application/json',
    'minha_chave': sessionStorage.getItem('token')
})
// (...)

Already on the server side I don’t know how it is implemented but taking as a basis that the header name that will save JWT will be minha_chave you could create a middleware with the following format:

const jwt = require('jsonwebtoken');

module.exports = function(req, res, next) {
    var token = req.header('minha_chave');
    jwt.verify(token, CHAVE_PRIVADA, function(err, decoded) {
        if(err) {
            res.json({ erro: true });
            return next(false);
        }

        req.session = {};
        req.session = decoded.data;
        return next();
    });
}

In the example I used the jsonwebtoken to validate the JWT.

To use this middleware on a specific route: app.get('/users', meu_middleware, (req, res) => /* ...seu código... */).

In this link has another example of using JWT with passport.

  • vlw mano, in case this mdidle will contain the information if the user has a valid jwt or not, ai in my app.get('/users') I can use the value of that middleware for if it is true to show all users or false to generate an error? I got a little confused on how to use this middleware, I posted my Strategy on the Passport and my method. get, you could take a look how I would improve this?

  • @Open in the case of this example the middleware is executed before. If JWT is invalid the code for right there and send a { erro: true } (example). If JWT is valid, we create a Session (example also, it could have another name) req.session = decoded.data; and then your code will actually run. Already in your code it will be possible to read the JWT payload through the req.session who was fed in the middleware.

  • @I didn’t get to use the passport :( but from what I read in the documentation LocalStrategy it is necessary to pass a function with the following signature function(username, password, done). In your case is giving some other error than sending JWT?

  • I understood now bro you could take me just a doubt, looking for my route / users after adding middleware, and how it will contain the JWT payload, on my route users I call my Strategy . all(app.auth.authenticate()), which will call my const Strategy, looking at the code I realize I won’t be passing that payload by parameter on my app.auth.authenticate() would I have to change that? You could take a look at these 2 classes I put in question: const Tratgy and my route (/users)

  • Not only gave the route error, so in addition to passing my jwt I have to pass the login/password? ( out of curiosity, what do you use for this part to validate and auth the jwt?)

  • From what I read if all goes well you can access the user data through the req.user. This req.user is indicated in done(err, dadosUsuario)) within the LocalStrategy. Take a look at this example: https://github.com/jaredhanson/passport-local From what I understand your authentication is local, meaning it doesn’t involve a third party with oauth. Then traffic in your JWT something that identifies your user, such as an ID for example. Inside your LocalStrategy consult the user data in the DB and pass this object through the done(null, dadosUsuario). It will now be possible to use the req.user

  • @Gabriel I believe this is my last comment. If you still have difficulties we continue trying to stay 100%

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.