Home > Software engineering >  How to add "Bearer" another route headers after user logged in?
How to add "Bearer" another route headers after user logged in?

Time:10-16

I'm new to programming and I'm currently working on a small project.

I'm trying to implement some authorization using JWT. I've watched a few videos online and found that most people have the "Bearer" access token in their headers.

I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.

Can I please get some help?

Here are some of my code

Login

 if(response){
            if(await bcrypt.compare(loginPW, response.password)){
                const accessToken = jwt.sign({
                    email: response.email
                },jwtSecret)
                res.json({status: 'ok', accessToken: accessToken})
            }else{
                return res.json({status: 'error', error:'Invalid Credentials'})
            }
        }

Post request

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json());

CodePudding user response:

just add Authorization header with your token to request

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
            'Authorization': `Bearer ${accessToken}`
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json());

CodePudding user response:

one possible way is ....on your Post requst result you can store the accessToken in localStorage

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json()).then(({accessToken})=>{
 
localStorage.setItem('accessToken', accessToken)

});

then retrieve it in all of your requests

const anotherRequst = await fetch('/anything',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`  // get it from localStorage
        },
        body: ... /// anything 
    }).then((res) => res.json());

that's the simplest way

... for more advanced techniques, try to use Axios

and you can simply set the default authorization header in all your requsts

axios.defaults.authorization = localStorage.getItem('accessToken')

then any request you make will have the accessToken in its header

Axios.post(....)
Axios.get(...)
....

CodePudding user response:

You can add 'Authorization' headers within your request just like this

const result = await fetch('/',{
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
        loginEmail, loginPassword, reqType
    })
}).then((res) => res.json());

Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line

axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

Docs: https://www.npmjs.com/package/axios

  • Related