I'm trying to verify/decode JWTs in my application but am running into an issue, and I have no idea why. Here is the function which is supposed to achieve this, but is creating a 500 server error:
exports.index = (req, res, next) => {
let token = req.headers.authorization;
let decoded = jsonwebtoken.verify(token, process.env.SECRET);
console.log(decoded);
res.send(decoded);
}
req.headers.authorization is correctly storing and delivering the Bearer token, and process.env.SECRET is the same key that was used to sign the token. I am importing the jsonwebtoken library. I'm stumped. Any help is appreciated.
EDIT: Just wrapped the function in a try/catch and the error that is raised is:
JsonWebTokenError: invalid token
at Object.module.exports [as verify] (/Users/-------/repos/sosh/node_modules/jsonwebtoken/verify.js:75:17)
at exports.index (/Users/-------/repos/sosh/controllers/soshController.js:15:32)
at Layer.handle [as handle_request] (/Users/--------/repos/sosh/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/-------/repos/sosh/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/--------/repos/sosh/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/-------/repos/sosh/node_modules/express/lib/router/layer.js:95:5)
at /Users/-------/repos/sosh/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/------/repos/sosh/node_modules/express/lib/router/index.js:335:12)
at next (/Users/-------/repos/sosh/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/------/repos/sosh/node_modules/express/lib/router/index.js:174:3)
I'm wondering why it says invalid token - I use this same token in my JWT authentication strategy and it works fine. Its formatted as "Bearer j5asdj........".
Related
I am using Axios library to retrieve Auth0 access tokens.
const { data, status, statusText } = await axios.post( https:auth0.url,
body,
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
`
The issue i have is when i am using Axios 1.1.3 to retrieve access-tokens from Auth0 its giving me a proper response.
But when i update the library to 1.2.0 and higher everything breaks. I am getting a response for the same code as raw data
/#����W�{��bhu�E
:U�ȦG>SQ��6�y:90��w>B��� f�4:cA�P��V/����)��v%�_P�ɳ���ꑄ=lb���-F��zh�^X
��N�ˠ��G�
o����W(�Žx>�͔{�5*�������I������`�
���fA\��x~KS[
j��p�Ӌ<���u�qog�.)0G�FI/��R��OԽ�sm�ԝ{X�vV��s$i���2p`� �h�x_Ц��Z�u�9�X�d���B+P���l �m�h�Y��2���ԙ2
��Wx0K
� �Y2IX�d�����P�֎NЂu�qo���f".AJ��+���K枖0�
The stranger part is when i try to use the same code to get the result of an open source api.
const results = await axios.post("www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json",
{ headers: { "content-type": "application/x-www-form-urlencoded" } });
I am getting a correct response.
I believe i am only getting this response when i am receiving a token from Auth0. Atleast in my use case
The error i am receiving when i call Auth0 to get tokens is
cause: Error: unexpected end of file
at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -5,
code: 'Z_BUF_ERROR'
}
Is anyone else facing the same issue?
bench-vue Thank you for your sample code. I had to add 'Accept-Encoding' in the request header to receive the tokens. Thank you for your help
im trying to refresh users jwt token in vue.js.So my solution would be when the user send a request with expired token got rejected with status code 401 and then in axios intereceptors I try to refresh the token with sending a token refresh request to my backend. The problem is when the token refresh happens it didn't repeat the original request
axios.interceptors.response.use(function (response) {
return response
}, async function (error) {
if(error.response.status===401){
let newtokens= await axios.post('RefreshToken',{
oldtoken:store.state.user.token,
refreshtoken:store.state.user.refreshtoken
})
let user=store.state.user
console.log(user)
user.token=newtokens.data.token
user.refreshtoken=newtokens.data.refreshtoken
axios.defaults.headers.common['Authorization']='Bearer '+ user.token
console.log(newtokens)
store.dispatch("user",user)
console.log(store.state.user)
return axios(error.config)
}
return Promise.reject(error)
})
I tried to console log what happens in the axios interceptors and it looks like it has been successfully send the request to the backend and refresh the user token. The only problem is it didn't repeat the original request
if your axios version is between (1.1.0) to (1.1.3) then such issue occured but on downgrade to version (0.27.2) works well.
Github issue:https://github.com/axios/axios/issues/5143
And it seems still issue hasn't been solved for higher version
An error - “jwksError: Not Found” is thrown when I make a get request with the correct bearer token in the request header to my protected API. I’ve followed the start up guide to create the jwtCheck helper function that I pass to all my routes to protect them. I need help clarifying what this error actually means thanks!
Here I define the helper function jwtCheck which will be used to secure all routes.
var jwtCheck = jwt({
secret: jwksClient.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: https://${auth0Domain}/.well-known/jwks.json,
}),
algorithms: ['RS256'],
issuer: https://${auth0Domain}/,
audience: auth0ApiIdentifier,
});
Then I protect my api using jwtCheck defined above like so. After which the api will throw an Unauthorized Error if one tries to send http requests to it without a header in the request with the auth bearer token.
const app = express();
...
app.use(jwtCheck);
...
I get new Bearer tokens by sending a POST request to auth0apiIdentifier/oauth/token and putting the following in the req body:
{
"client_id":id,
"client_secret":secret,
"audience":auth0apiIdentifier,
"grant_type":"client_credentials"
}
After sending the get request via postman with the appropriate bearer token in place, rwks-rsa module throws the subsequent error:
JwksError: Not found.
at ../server/node_modules/jwks-rsa/lib/JwksClient.js:119:23
at ../server/node_modules/jwks-rsa/lib/wrappers/request.js:36:12
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Img 1 - POST request to get new auth Bearer token from Auth0
Img 2 - GET request sent with postman and corresponding error thrown by jwks-rsa module.
I've fixed it! The error was way too ambiguous but after desperation set in, I checked my configs again and I found that I included a "/" at the end of my auth0apiIdentifier, this allowed a "//" in the jwksUri which caused the issue. Solving this typo was my fix.
Check your code guys! Peace!
I want to send a request to this server via Apollo and get a query :
const client = new ApolloClient({
link: new HttpLink({
uri:'http://mfapat.com/graphql/mfaapp/'}),
cache: new InMemoryCache()
})
const FeedQuery = gql
query{
allFmr{
fmrId,
name,
studio,
bedRm1,
bedRm2,
bedRm3,
bedRm4
}
}
`
But I'm facing this error message:
Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1
at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)
....
But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?
Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.
To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:
As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.
Reading the specific error sent enables you to fix the bug.
To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.
EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.
Base on #eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors.
// On Apollo server
// Error handler
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
const { status } = err;
res.status(status).json(err);
};
app.use(errorHandler);
I am using loopback in backend. I am getting this error
Unhandled error for request POST /api/meetups/auth: Error: Value is not an object.
at errorNotAnObject (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:80:13)
at Object.validate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:51:14)
at Object.fromTypedValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:14:22)
at Object.fromSloppyValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:41:17)
at HttpContext.buildArgs (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:193:22)
at new HttpContext (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:59:20)
at restStaticMethodHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/rest-adapter.js:457:15)
at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
at /Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:335:12)
at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:275:10)
at Function.handle
(/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:174:3)
at router (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:47:12)
I have already searched stackoverflow, but I didnt find answer. Basically, i was trying to use body-parser . I went through one of the stackoverflow thread and implemented its solution. I was able to use body-parser successfully. So, that error has been solved. But, now this error is giving me tough time.
server.js file
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = module.exports = loopback();
//code for body parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//app.use(multer()); // for parsing multipart/form-data
//code for body parsing ends
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
In middleware.json, I have updated parse property as well
"parse": {"body-parser#json": {},
"body-parser#urlencoded": {"params": { "extended": true }}},
For some reason, that error has gone. Not sure, may be it will come again. But now, this is the error, I am seeing
Unhandled error for request POST /api/meetups/auth: TypeError: cb is not a function
at Function.Meetups.auth (/Users/ankursharma/Documents/projects/meetupz/common/models/meetups.js:117:3)
at SharedMethod.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/shared-method.js:270:25)
at HttpContext.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:297:12)
at phaseInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:677:9)
at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
at Object.async.eachSeries (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:162:9)
at runHandlers (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:144:13)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:157:25
at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:154:25
at execStack (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:522:7)
at RemoteObjects.execHooks (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:526:10)
at phaseBeforeInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:673:10)
at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
check if your filters or your URL has black spaces i.e. %20, or anything wrong with the filter or url.
Loopback 3 makes a difference between array and object. You have to check your data type. See https://github.com/strongloop/strong-remoting/issues/360 for more information.
I was facing the same error but in my case it was due to a model property data length.The property was type object and a small dataLength which caused faulty record in my sql Model table.I have to Manually delete those faulty records and increase the dataLength of that property too.
Restart the app