I'm using express-jwt for athentication, and the following is my code:
api>routes/index.js:
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth' });
after this inside index.js when i use auth middleware in
router.post('/locations/:locationId/reviews', auth, ctrlReviews.reviewsCreate);
route, when want to post reviews data with post-man, request goes to loading, and no response appear, but if remove auth from route request give response.
I have also checked with
var auth = jwt({
secret: process.env.JWT_SECRET,
userProperty: 'payload'
});
As mentioned in the comments, you're trying to handle valid and invalid tokens. This should be possible with something similar to the below code.
If you use Postman to call this with the following header, then you'll receive 200 OK, with a message of 'OK!'.
Authorization: Bearer validJWT
If you use Postman to call this without a valid JWT then you'll receive 401 Unauthorized with a message of 'invalid token...'.
var jsonwebtoken = require('jsonwebtoken');
var express = require('express');
var app = express();
var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth'});
// Generate valid JWT
console.log(jsonwebtoken.sign({ foo: 'bar' }, 'thisIsSecret'));
app.post('/locations/:locationId/reviews', auth, function(req, res, next) {
// Log user details set in JWT
console.log(req.auth)
res.send('OK!');
});
// Handle invalid JWT
app.use(function(err, req, res, next) {
if (err.constructor.name === 'UnauthorizedError') {
res.status(401).send('invalid token...');
}
});
app.listen(3000, function() {
console.log('Server running on 3000')
})
Related
I am trying to develop an API that allow POST request of file data, but the POST request only functions using curl curl -X POST --data file= mouse.fa "http://localhost:3000/api/data?file=mouse.fa" . When I trying a POST request in the browser, I get a GET error Cannot GET /api/data. Please could you advise me on how to get the POST request to work in the browser in addition to curl.
router.js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
fileParser = require("./fileParser")
router.use('./fileParser', fileParser.parse);
// middleware
router.use(function (req, res, next) {
console.log('Received request');
next();
});
router.post('/data', function (req, res) {
//Check file is valid
if (!req.body.file.toString().endsWith('.fa')) {
res.status(400).json({ message: "Bad Request" });
} else {
fileParser.parse(`./${req.body.file.toString()}`);
res.json({ message: "File parsed and data submitted.", location: "/data/" });
}
});
server.js
const express = require('express');
// create server
const app = express();
const port = 3000;
app.listen(port, function () {
console.log(`Server running at ${port}`)
});
// import router
const router = require('./router');
app.use('/api', router)
I have created a rest api in node js and used keycloak-connect npm packge. I have mapped the nodejs middleware with keycloak middleware.
var express = require('express');
var router = express.Router();
var app = express();
var Keycloak = require('keycloak-connect');
var keycloak =new Keycloak();
app.use( keycloak.middleware( {
logout: '/logout',
admin: '/',
} ));
router.get('/users',function(req, res, next) {
var token=req.headers['authorization']; //Access token received from front end
//Now how to authenticate this token with keycloak???
});
router.get('/shop',keycloak.protect(),function(req, res, next) {
});
I'm making a Rest Api with Node.js, but I have no idea of how to put information on headers and receive it in another endpoint, in this case, I want to send the token signed in headers to get it in another endpoint with a require.headers
So, What's the method I should use? and if you have an explanation is better.
const { Router } = require("express");
const router = Router();
const jwt = require('jsonwebtoken');
const authmiddleware = require('../Middlewares/auth.middleware')
router.get("/kiral/jwt", (req, res) => {
const token = jwt.sign({
data: "informacion importante"
}, 'seed', {expiresIn: '1h' });
res.json({
message: "Hello endpoint jwt",
token
});
});
If you want to send the token information in the response headers you do something like this
const { Router } = require("express");
const router = Router();
const jwt = require('jsonwebtoken');
const authmiddleware = require('../Middlewares/auth.middleware')
router.get("/kiral/jwt", (req, res) => {
const token = jwt.sign({
data: "informacion importante"
}, 'seed', {expiresIn: '1h' });
res.header('token', token); // this will be sent in response headers
res.json({
message: "Hello endpoint jwt",
token
});
});
I am learning JWT with NodeJs. I am stuck at passing the JWT in header actually i do not know how to do this.
index.js file
var express = require('express'),
app = express(),
routes = require('./routes'),
bodyParser = require('body-parser'),
path = require('path'),
ejs = require('ejs'),
jwt = require('jsonwebtoken');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.post('/home',routes.loginUser);
app.get('/', function(req, res) {
res.render('index');
});
app.get('/home',function(req, res) {
jwt.verify(req.token, 'qwertyu6456asdfghj', function(err, data) {
if (err) {
res.sendStatus(403);
}
});
});
app.listen(3000,function(){
console.log("Server running at Port 3000");
});
routes/index.js file
var jwt = require('jsonwebtoken');
exports.home = function(req, res){
res.render('home',{error: false});
};
exports.loginUser = function(req, res) {
var uname = req.body.Username;
var pwd = req.body.Password;
if(uname && pwd === 'admin'){
res.render('home');
var token = jwt.sign({ user: uname }, 'qwertyuiopasdfghj');
console.log('Authentication is done successfully.....');
console.log(token);
}
response.json({
authsuccess: true,
description: 'Sending the Access Token',
token: token
});
};
when i run the application i am getting the token in console.log but
How can I pass token in header and store it in localStorage of browser?
So you want to send the token to frontend but not in the body.
The Recommended way to do so is to use cookies. You can set the token in the cookie and it can be automatically accessed in front-end and in the backend.
res.cookie('tokenKey', 'ajsbjabcjcTOKENajbdcjabdcjdc');
Using authorization headers is also a good approach, but again, in front-end, you have to fetch the token from headers and then save in localStorage or cookie, which you don't have to do in case of cookie.
res.header(field [, value]);
As #ChicoDelaBarrio told you, it depends on the client. Postman is a good place to start checking your backend. But after you have your server working, you have to start working in your client side.
If you want a complete backend example about JWT in Node.js, with Refresh token included, I recomend you this post about it: Refresh token with JWT authentication in Node.js
Probably you can reuse most of the code. In this case the header is not created with BEARER, but with JWT at the beginning, but it works the same
In my app I have a code from official docs, except one difference: I send xsrfToken in response to POST request, not GET.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
var app = express()
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.post('/getCsrfToken', /*csrfProtection,*/ function (req, res) {
// check credentials from request.body
// and then
res.render('send', { csrfToken: req.csrfToken() }) //EXCEPTION: csrfToken is not a function
})
app.post('/process', parseForm, csrfProtection, function (req, res) {
res.send('data is being processed')
})
I'm facing the egg-hen problem: if I enable csrfProtection, I cannot get into the endpoint's code without the token, but if I disable it, req.csrfToken becomes undefined.
I need the gerCsrfToken endpoint to be POST, because I don't want to expose password as url parameter.
Question was answered by csurf maintainer, thanks for a quick response!
https://github.com/expressjs/csurf/issues/133
The (tricky) solution is to ignore POST method for this particular endpoint
app.post('/authenticate', csrf({ cookie: true, ignoreMethods: ['POST'] }), function (req, res) {