express-jwt icon indicating copy to clipboard operation
express-jwt copied to clipboard

Node 7 error

Open Cirych opened this issue 7 years ago • 26 comments

Error
at middleware (xxxxx\node_modules\express-jwt\lib\index.js:69:21)
at Layer.handle [as handle_request] (xxxxx\node_modules\express\lib\router
layer.js:95:5)
at next (xxxxx\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (xxxxx\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (xxxxx\node_modules\express\lib\router
layer.js:95:5)
at xxxxx\node_modules\express\lib\router\index.js:277:22
at Function.process_params (xxxxx\node_modules\express\lib\router\index.js: 330:12)
at next (xxxxx\node_modules\express\lib\router\index.js:271:10)
at cors (xxxxx\node_modules\cors\lib\index.js:179:7)
at xxxxx\node_modules\cors\lib\index.js:229:17

Cirych avatar Nov 12 '16 19:11 Cirych

line 69: return next(new UnauthorizedError('credentials_bad_format', { message: 'Format is Authorization: Bearer [token]' })); check your code..

mkopa avatar Nov 17 '16 09:11 mkopa

My code from this repo example and it works on Node 6 well.

Cirych avatar Nov 17 '16 18:11 Cirych

+1

druti avatar Nov 28 '16 03:11 druti

Hey @Cirych, So the problem is that you have credentialsRequired: true (either by default or in the config options passed in). This means that if the token isn't valid it triggers an error (it's being used for auth not just to parse the token automatically). If you used the error catching middleware as described in the README.md then you need to make sure that this is added AFTER you configure your routes, otherwise it will not be in the right order (the order that middleware is added in express matters as it forms a chain, you may have encoutered this with passport and sessions before).

Hope this helps. 👍 If not let me know and I can take a look at it 🤓🕵

jdrew1303 avatar Dec 16 '16 17:12 jdrew1303

Thank you, James!

@jdrew1303

Cirych avatar Dec 18 '16 11:12 Cirych

Thanks @jdrew1303. Would be really helpful to have a more descriptive error such as Error: absent or invalid token instead of juste Error

christophemarois avatar Mar 06 '17 19:03 christophemarois

@christophemarois @Cirych No problem. I wasted a day or two on this. :grimacing:

jdrew1303 avatar Mar 10 '17 18:03 jdrew1303

I have the same error and don't know what to do Format is Authorization: Bearer [token]

How to turn off this Bearer checking?

hackuun avatar Jul 22 '17 23:07 hackuun

Sorry, guys, I fixed it on client side!

hackuun avatar Jul 22 '17 23:07 hackuun

Hello, I have the same error Format is Authorization: Bearer [token]. I need your help

ricardomb94 avatar May 13 '20 08:05 ricardomb94

Hey @ricardomb94 👋

Your first check is to make sure that the token is being sent correctly. You need to make sure a valid token is set in the Authorization http header. It should be formatted like so:

Authorization: Bearer AbCdEf123456

If the token is not stored in the auth header then you need to tell express-jwt where to find it. The docs for this are here: https://github.com/auth0/express-jwt#retrieving-the-decoded-payload

Your second check is to make sure it is a valid token. One issue that can happen is that the keys/secret used to sign the token may not match (it can happen if you rotate keys in app or sometimes Ill have one app hand out the keys and another using them to validate access in separate services and forget to check the secrets match).

The last is to make sure that the token is still valid. If you expire tokes (using the expiration exp option) then it will be checked. https://tools.ietf.org/html/rfc7519#section-4.1.4 Again Ive had the same issue as with the secret. I just didnt check I was passing a valid token.

Last if the token is actually invalid (and you know it is) then its working correctly. This is the error thats thrown when the token doesnt pass validation. You'll need to handle this in your code as described here: https://github.com/auth0/express-jwt#error-handling

If you're still having issues then give a little more context and I can take a look. If you can included:

  • the full error
  • a sample of the code you're using (remove any hard coded secrets or key names and replace them with dummies)
  • then if you can send a copy of the http call you tried it with. If you use chrome you can do something like the following: https://lornajane.net/posts/2013/chrome-feature-copy-as-curl

I hope this helps. If not let me know. Im a bit rusty with this lib but Im not bad at debugging 🙈

regards, James

jdrew1303 avatar May 14 '20 00:05 jdrew1303

Hey @ricardomb94 👋

Your first check is to make sure that the token is being sent correctly. You need to make sure a valid token is set in the Authorization http header. It should be formatted like so:

Authorization: Bearer AbCdEf123456

If the token is not stored in the auth header then you need to tell express-jwt where to find it. The docs for this are here: https://github.com/auth0/express-jwt#retrieving-the-decoded-payload

Your second check is to make sure it is a valid token. One issue that can happen is that the keys/secret used to sign the token may not match (it can happen if you rotate keys in app or sometimes Ill have one app hand out the keys and another using them to validate access in separate services and forget to check the secrets match).

The last is to make sure that the token is still valid. If you expire tokes (using the expiration exp option) then it will be checked. https://tools.ietf.org/html/rfc7519#section-4.1.4 Again Ive had the same issue as with the secret. I just didnt check I was passing a valid token.

Last if the token is actually invalid (and you know it is) then its working correctly. This is the error thats thrown when the token doesnt pass validation. You'll need to handle this in your code as described here: https://github.com/auth0/express-jwt#error-handling

If you're still having issues then give a little more context and I can take a look. If you can included:

  • the full error
  • a sample of the code you're using (remove any hard coded secrets or key names and replace them with dummies)
  • then if you can send a copy of the http call you tried it with. If you use chrome you can do something like the following: https://lornajane.net/posts/2013/chrome-feature-copy-as-curl

I hope this helps. If not let me know. Im a bit rusty with this lib but Im not bad at debugging 🙈

regards, James

Hey James Drew, Thank you for your quick response I tried to follow your recommandations. It seems like my token is correct. When I sign up a user I can sign in and update all users informations. But as admin, when I try to create a category I get the error. Maybe my token is expired but every thing works via postman.

regards, Ricardo

ricardomb94 avatar May 20 '20 05:05 ricardomb94

I made some changes in my code and I got another error: userId is undefined. You are right, I definitly have an authentication problem. This my code to create an add category

import axios from "axios";

const CreateCategory = (userId, token, category) => { return (

            axios({
                method: 'POST',
                url: `${process.env.REACT_APP_API}/category/create/${userId}`,
                headers: {
                  Accept: "application/json",
                  Authorization:`Bearer  ${token}`
                },data:{category},
            })
            .then(response => {
                console.log('ADD CATEGORY RESP.', response);
            })
            .catch(error => {
                console.log('ADD CATEGORY ERROR', error) 
            })
    )}
    

export default CreateCategory

ricardomb94 avatar May 20 '20 06:05 ricardomb94

import React, {useState} from 'react'; import Layout from '../core/Layout'; import {isAuth, getCookie} from '../auth/helpers' import Zoom from 'react-reveal/Zoom'; import Pulse from 'react-reveal/Pulse'; import CreateCategory from './CreateCategory';

const AddCategory = () => {

const [name, setName] = useState('')
const [error, setError] = useState(false)
const [success, setSuccess] = useState(false)

//On destruture user à partir du localstorage const {userId} = isAuth(); console.log(userId) const token = getCookie('token') console.log(token)

const handleChange =  (e) => {
    e.preventDefault()
    setError('')
    setName(e.target.value)
}
const clickSubmit = (e) => {
   e.preventDefault()
   setError('')
   setSuccess(false)
   
   //Reaquette API pour créer les catégories
 CreateCategory(userId,token, {name})
    .then(data => {
        if(error) {
            setError(true)
        }else {
            setError('')
            setSuccess(true)
        }
   });  
};

const newCategoryForm = () => (

    <form  onSubmit={clickSubmit}>
        <div className="form-control">
            <div className="jumbotron catego text-center text-uppercase text-black font-x-small">
                <Zoom right cascade><h4>La création c'est l'intelligence qui s'amuse</h4></Zoom>
                    <Pulse><hr className="bg-danger underline"/></Pulse></div>
                        <label className="text-muted">Nom</label>
                            <input 
                                type="text" 
                                className="form-control" 
                                onChange={handleChange} 
                                value={name}
                                autoFocus
                                />
                                <br/>
                            <button className="btn btn-outline-danger">Créer une catégorie
                            </button>    
            </div>
    </form>
);

const showSuccess = () => {
    if(success){
        return <h4 className="text-success">{name} viens d'être créer</h4>;
    }
}

const showError = () => {
    if(error){
        return <h4 className="text-danger">{name} Le nom doit être unique</h4>;
    }
}

return(
    <Layout title="Ajouter une nouvelle categorie" className="container">
        <div className="row">
            <div className="col-md-8 offset-md-2">
                {showSuccess()}
                {showError()}
                {newCategoryForm()}
            </div>
        </div>
    </Layout>
    
    
);

};

export default AddCategory

ricardomb94 avatar May 20 '20 06:05 ricardomb94

This is my Routes:

router.post('/category/create/:userId', requireSignin, adminMiddleware, create);

ricardomb94 avatar May 20 '20 06:05 ricardomb94

James thank you for help.

ricardomb94 avatar May 20 '20 06:05 ricardomb94

@ricardomb94 No probs. 👍 Sometimes its better to be looking at someone else's code problems than your own. 🙈

So this might be a long shot but I took a look at your code. One thing that might be causing your issue is in the axios call the Bearer token string has 2 spaces in it. Could you try changing it to 1 space and give it a go?

Here they split the incoming string based on spaces: https://github.com/auth0/express-jwt/blob/5766a24aeb7db15b8a183c59b4a9145552702f0e/lib/index.js#L55

Then they check if it was separated in 2 parts: https://github.com/auth0/express-jwt/blob/5766a24aeb7db15b8a183c59b4a9145552702f0e/lib/index.js#L56

If not it throws an error. When I test your string manually:

var parts = "Bearer  ${token}".split(' ')
console.log(parts)

It's giving me ["Bearer", "", "${token}"]. If I change it to one space Im getting ["Bearer", "${token}"].

If this isn't just a copy and paste thing then this is probably your issue. I'd tag your code with a note and maybe extract it into a function if you're using it around the codebase. This way theres only one place this error can happen.

Hopefully this has you back on the right track 👍 If it's still not working let me know and I can dig deeper. 👷‍♂️

jdrew1303 avatar May 22 '20 11:05 jdrew1303

Thank you James, let me give it a try. I will get back to you in a short while.

Le ven. 22 mai 2020 à 13:13, James Drew [email protected] a écrit :

No probs. 👍 Sometimes its better to be looking at someone else's code problems than your own. 🙈

So this might be a long shot but I took a look at your code. One thing that might be causing your issue is in the axios call the Bearer token string has 2 spaces in it. Could you try changing it to 1 space and give it a go?

Here they split the incoming string based on spaces:

https://github.com/auth0/express-jwt/blob/5766a24aeb7db15b8a183c59b4a9145552702f0e/lib/index.js#L55

Then they check if it was separated in 2 parts:

https://github.com/auth0/express-jwt/blob/5766a24aeb7db15b8a183c59b4a9145552702f0e/lib/index.js#L56

If not it throws an error. When I test your string manually:

var parts = "Bearer ${token}".split(' ')

console.log(parts)

It's giving me ["Bearer", "", "${token}"]. If I change it to one space Im getting ["Bearer", "${token}"].

If this isn't just a copy and paste thing then this is probably your issue. I'd tag your code with a note and maybe extract it into a function if you're using it around the codebase. This way theres only one place this error can happen.

Hopefully this has you back on the right track 👍 If it's still not working let me know and I can dig deeper. 👷‍♂️

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/auth0/express-jwt/issues/146#issuecomment-632637400, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJ4KYXIXH65NJVTQF2ILCALRSZM4VANCNFSM4CWCBPTA .

ricardomb94 avatar May 22 '20 12:05 ricardomb94

Hey @ricardomb94

Just wondering if you managed to fix your issue?

regards, James

jdrew1303 avatar May 26 '20 18:05 jdrew1303

I am still stuck at the same point. I Changed the space just like you told me but nothing works. I added more elments to my requireSignin to get the token like this:

ricardomb94 avatar May 27 '20 01:05 ricardomb94

exports.requireSignin = expressJwt({ secret: process.env.JWT_SECRET, credentialsRequired:false, getToken: (req)=> { if( req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer' ){ console.log('REQ HEADERS',req.headers.authorization.split(' ')[1]) return req.headers.authorization.split(' ')[1]; } return null; }, });

ricardomb94 avatar May 27 '20 01:05 ricardomb94

Regards, Ricardo

ricardomb94 avatar May 27 '20 01:05 ricardomb94

Hey @ricardomb94

I should have some time this evening. Ill dig a bit deeper and see. 👍

jdrew1303 avatar May 27 '20 16:05 jdrew1303

Hey James thank you so much for your help

ricardomb94 avatar May 27 '20 22:05 ricardomb94

Hello James I finally solved my problem. Category was created from the front side of my app without token's or user's issue. I did this:
- const category = new Category(req.body.category) instead of - const category = new Category(req.body) Thank you so much for your support and advises. For a biginner like me, your help was something very important.

Regards, Ricardo

ricardomb94 avatar May 28 '20 20:05 ricardomb94

Hey guys,

I am facing a similar issue, weird thing is, the exact same codebase is working fine on my Windows laptop, it just does not seem to work on my macOS for some reason!

note: I noticed the Authorization header is not being set, it defaults to some string, although the token is being generated correctly!!

Would appreciate any help on this issue, thanks!

return await axios.get(config.API_BASE_URL + 'account', { headers: { Authorization:Bearer ${token}, }, });

ibouelezz avatar Feb 10 '22 00:02 ibouelezz