I am working on an iOS application which communicates with a nodejs backend server REST API and I am thinking about API authentication.
I want that only the iOS application can communicate with the API.
On iOS application side, users are authenticated through Facebook login. They thus get a fb access_token and a fbid after authentication on the iOS app.
For the API authentication, I plan to make it this way:
When the user logs in into the iOS app, a call to /api/auth with his fb access_token and fbid is done;
If the user is new, I create a random api_token for this user, store it into Users DB, and send it back to the iOS app;
If the user is already in the DB, I refresh the fb access_token in my DB and the api_token and send it back to the iOS app;
For each API call, I give the api_token as a POST parameter and on server side I check if it is valid by fetching in the DB before executing the API call.
Am I missing something to be enough secured?
Any feedback or improvement will be very welcome.
Regards,
EDIT:
Another way would be the following:
On /api/auth I checked on FacebookB API (/me) if the fb access_token is still valid;
If not I refuse the authentication;
If yes I create and manage my api_token with JSON Web Tokens.
If anyone is interested, I finally implemented the second solution. Very simple and do the job!
config.js
module.exports = {
'secret': 'apisupersecrethere',
};
route.js
var config = require('./config');
app.set('api_secret', config.secret);
api = express.Router();
// function that checks the api_token
api.use(function(req, res, next) {
var token = req.headers['x-access-token'];
if (token) {
jwt.verify(token,app.get('api_secret'),function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
// route protected by the authentication
router.use('/users', api);
// authentication route
router.post('/auth', function(req, res) {
verifyFacebookUserAccessToken(req.body.access_token).
then(function(user) {
var token = jwt.sign(user, app.get('api_secret'), {
expiresIn: 1440*60 // expires in 24 hours
});
res.status(200).json({
success: true,
message: "Authentication success!",
token: token
});
}, function(error) {
res.status(401).json({
success: false,
message: error.message
});
}).
catch(function(error){
res.status(500).json({
success: false,
message: error.message
});
});
});
// Call facebook API to verify the token is valid
function verifyFacebookUserAccessToken(token) {
var deferred = Q.defer();
var path = 'https://graph.facebook.com/me?access_token=' + token;
request(path, function (error, response, body) {
var data = JSON.parse(body);
if (!error && response && response.statusCode && response.statusCode == 200) {
var user = {
facebookUserId: data.id,
username: data.username,
firstName: data.first_name,
lastName: data.last_name,
email: data.email
};
deferred.resolve(user);
}
else {
deferred.reject({
code: response.statusCode,
message: data.error.message
});
}
});
return deferred.promise;
}
Any feedback welcomed.
Regards
Related
I'm trying to configure a token refresh method in my express middleware in wich the token is validate at every request to the api. I will check if the token expired and if so, I will sign a new token with new exp date. The problem is that I have to send the token again, but doing thatI lose the original request to send the token with the response and the api not continue to the destination endpoint.
How I can send back the new refreshed token and continue with the request?
My express middleware to check the token:
apiRouter.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
//Here I can check if the received token in the request expired
if(err.name == "TokenExpiredError"){
var refreshedToken = jwt.sign({
success: true,
}, app.get('superSecret'), {
expiresIn: '5m'
});
//Here need to send the new token back to the client and continue with the request
//but if I use return res.... the request don't continue to next()
next();
}else if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
} else {
//If no error with the token, continue
next();
};
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
I dont' know if its the best aproach to this.
Thanks you.
You can not send a response to the client two times for single request, so better way will be sent an access token with the actual API response.
apiRouter.use(function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
//Here I can check if the received token in the request expired
if(err.name == "TokenExpiredError"){
var refreshedToken = jwt.sign({
success: true,
}, app.get('superSecret'), {
expiresIn: '5m'
});
request.apiToken = refreshedToken;
next();
}else if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
} else {
//If no error with the token, continue
request.apiToken = token;
next();
};
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
then when you send a response then send a response with the token, that you can get with request.apiToken.
but a better strategy is to provide a client refresh token and let the client make a request to get refreshed token.
You can read more about that here
I am using JWT-simple for authenticating my express routes.
server side:
var jwt = require('jwt-simple');
var bcrypt = require('bcrypt');
var passport = require('passport');
require('../passport')(passport);
/* Create an Account */
router.post('/signup', function (req, res, next) {
var verifyCode = Math.random().toString(36).slice(-8);
var userData = {
name: req.body.name,
email: req.body.email,
phone: req.body.contact,
password: req.body.password,
verify_code: verifyCode,
status: 0
};
loginService.createUser(userData, function (err, data) {
if (err) {
res.status(500).json({error: true, data: {message: err.message}});
} else {
var token = jwt.encode(data, "secret");
res.json({success: true, data: {token: 'JWT ' + token}});
}
});
});
/* GET the info of an API using the jwt token data */
router.get('/info', passport.authenticate('jwt', {session: false}), function (req, res, next) {
var token = tokenRetrive.getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, configVar.config.secret);
UserService.getContentUserById(decoded.id, function (err, user) {
if (err) {
res.status(500).json({error: true, data: {message: err.message}});
} else {
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, data: user.toJSON()});
}
}
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
client side
var signup = function(user) {
return $q(function(resolve, reject) {
$http.post(API_ENDPOINT.url + '/signup', user).then(function(result) {
if (result.data.success) {
storeUserCredentials(result.data.data.token);
resolve(result.data);
} else {
reject(result.data.msg);
}
});
});
};
function storeUserCredentials(token) {
window.localStorage.setItem(TOKEN_KEY, token);
var loggedIn_user_Data = jwt_decode(token);
$http.defaults.headers.common.Authorization = token;
}
Using REST client (POSTMAN) when I pass the header info to the API I use
API : localhost:8080/info
Key
Authorization
Content-Type
Value
JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYXR1bCIsImVtYWlsIjoidHJlZUB0cmVlLmNvbSIsInBob25lIjpudWxsLCJwYXNzZHJlc3MiOm51bGwsImNvdW50cnkiOm51bGwsInN0YXRlIjpudWxsLCJwaW5jb2RlIjpudWxsLCJvcmdfaWQiOjAsInJvbGVzIjpudWxsLCJjcmVhdGVfZGF0ZSI6IjIwMTctMDUtMThUMTk6NTE6MDYuMDAwWiIsImxhc3RfbG9naW4iOiIyMDE3LTA1LTE4VDE5OjUxOjA2LjAwMFoiLCJhdmF0YXJfdXJsIjpudWxsfQ.umxBRd2sazaADSDOW0e8rO5mKDpQYIK1hsaQMZriZFE
application/json
The above API gives me the data only if the correct token is passed and seems working fine.
However in client side I can get the token retrieve using jwt-decode, without the use of any secret in client side, what if the token is caught by middle man, How can the security be enhanced?
Is there something I am missing to have correct use of JWT for my node api routes?
Some places I see the Authorisation is passed as bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYXR1bCIsImVtYWlsIjoidHJlZUB0cmVlLmNvbSIsInBob25lIjpudWxsLCJwYXNzd29yZCI6IiQyYSQxMCRIQVJPTy5PUEdYWFBvVktXOVhmYnZldk
When I try to use bearer I get error to get the info after authenticating.
What is this bearer and JWT being passed in value to header?
I am using passport-jwt
var JwtStrategy = require('passport-jwt').Strategy;
To use JWT tokens, you have to use SSL (https). Without it, you won't have protection at all.
JWT tokens are signed (check the site). So if someone (middle man) try to change it, it will be invalidated.
JWT and Bearer are basic the same thing. They are just the auth scheme for the authorization header.
The 'JWT' auth scheme is the default of the passport-jwt.
If you want to change it, you can use a different jwtFromRequest value.
See:
new Strategy({ ... jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer') ... }, verifyFunction)
Hope its clear.
My server has a registration api that provides a token after registration, and a middleware that authenticates a user's token. I need to register an account to get the token to do something else with my server. However, the middleware blocks my network request because I don't have a token yet.
So how can I create my account and token in this case? Get pass the middleware with some tricks?
Middleware:
// Middleware to verify token, it will be called everytime a request is sent to API
api.use((req, res, next)=> {
var token = req.headers.token
if (token) {
jwt.verify(token, secret, (err, decoded)=> {
if (err) {
res.status(403).send({ success: false, message: "Failed to authenticate user." })
} else {
req.decoded = decoded
next()
}
})
} else {
res.status(403).send({ success: false, message: "No Token Provided." })
}
})
Signin:
// Sign In with email API
api.post('/signInWithEmail', (req, res)=> {
User.findOne({
email: req.body.email
}).select(userFields).exec((err, user)=> {
if(err) {
throw err
}
if (!user) {
res.send({ message: "User doesn't exist"});
} else if (user) {
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.send({ message: "Invalid Password"});
} else {
var token = createToken(user);
res.json({
success: true,
message: "Login Successfully!",
token: token
})
}
}
})
})
Make a function to check tokens and expose your routes such that whenever you need to call an authenticated route then you'll be checking the token first and then you'll expose the route.
Sample Code
Let's say this is my check token function
function checkToken(req, res, next) {
var x = req.token; //This is just an example, please send token via header
if (x === token)
{
next();
}
else
{
res.redirect(/unauthorized); //here do whatever you want to do
}
}
Now let's use the function for routes.
app.post('/protectedroute', checkToken, routename.functionname);
app.post('/notprotected', routename.functionname);
It's your call if you'd like to have separate routes for different codes or else you can just call specific code block via keeping them in function etc. on the main file i.e. app.js or server.js, whatever you have chosen.
What actually we are doing here is - we are making a middleware of our own to expose our routes through a channel of code blocks or functions.
I want to ignore some API URL of being checked against token authentication
I want to protect post and put methods but not get of this url
localhost:3000/api/events/
router.use(function(request, response) {
var token = request.body.token || request.query.token || request.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get(superSecret), function(err, decoded) {
if (err)
return response.json({
sucess: false,
message: "Failed token Authentication"
});
else {
request.decoded = decoded;
next();
}
});
} else {
return response.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
How can I do this using jsonwebtoken in node,express
I want this to apply to only post,put,delete requests but not on get requests.
You can move your anonymous middleware to normal declared function and then pass it to all protected routes (you decide which route you want to protect!)
Your code could look like:
function tokenProtection(request, response, next) {
var token = request.body.token || request.query.token || request.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get(superSecret), function(err, decoded) {
if (err)
return response.json({
sucess: false,
message: "Failed token Authentication"
});
else {
request.decoded = decoded;
next();
}
});
} else {
return response.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
and now your routes could look like (your decision what you want to protect):
router.get('/item', function(req, res) { ... }); // not protected
router.get('/item/:id', function(req, res) { ... }); // not protected
router.post(tokenProtection,'/item', function(req, res) { ... });//protected
router.put(tokenProtection,'/item', function(req, res) { ... });//protected
router.get('/book', function(req, res) { ... });// not protected
router.get('/book/:id', function(req, res) { ... });// not protected
router.post(tokenProtection,'/book', function(req, res) { ... });//protected
router.put(tokenProtection,'/book', function(req, res) { ... });//protected
Put the routes you want to protect below your authentication route and the ones you do not want to protect can above the authentication route. Something like this,
// Require what will be needed
var express = require('express'),
User = require('../models/user'),
usersRouter = express.Router();
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var secret = {superSecret: config.secret}; // secret variable,
// Create a new user and return as json for POST to '/api/users'
usersRouter.post('/', function (req, res) {
var user = new User(req.body);
user.save(function(){ //pre-save hook will be run before user gets saved. See user model.
res.json({user : user, message: "Thank You for Signing Up"});
});
});
usersRouter.post('/authentication_token', function(req, res){
var password = req.body.password;
// find the user
User.findOne({
email: req.body.email
}, function(err, user) {
//If error in finding the user throw the error
if (err) throw err;
//If there is no error and the user is not found.
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
//if the user is found
} else if (user) {
// check if password matches
user.authenticate(password, function(isMatch){
if(isMatch){
// if user is found and password is right
// create a token with full user object. This is fine because password is hashed. JWT are not encrypted only encoded.
var token = jwt.sign({email: user.email}, secret.superSecret, {
expiresIn: 144000
});
// set the user token in the database
user.token = token;
user.save(function(){
// return the information including token as JSON
res.json({
success: true,
id: user._id,
message: 'Enjoy your token!',
token: token
});
});
} else {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
}
});
}
});
});
//***********************AUTHENTICATED ROUTES FOR USERS******************************
// Return ALL the users as json to GET to '/api/users'
usersRouter.get('/', function (req, res) {
User.find({}, function (err, users) {
res.json(users);
});
});
// Export the controller
module.exports = usersRouter;
I actually explained this yesterday itself on my blog because I was struggling to figure it out. If you are still not clear, you can check it out here, Node API Authentication with JSON Web Tokens - the right way.
If there are other resources like in my case it was plans. Below is the code I put above all the routes for plans I wanted to authenticate.
// route middleware to verify a token. This code will be put in routes before the route code is executed.
PlansController.use(function(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// If token is there, then decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, secret.superSecret, function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to incoming request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
//***********************AUTHENTICATED ROUTES FOR PLAN BELOW******************************
PlansController.get('/', function(req, res){
Plan.find({}, function(err, plans){
res.json(plans);
});
});
I am using Node with Express.js and trying to make an authentication with JWT, after the user logs in generate a token, and save it to localstorage, but then I don't know how to get the token for authentication.
This is the code I am using:
Login view:
$.ajax({
type: 'POST',
url: base_url + "login",
data: postData,
dataType: 'json',
success: function(data){
// console.log(data1);
// alert(data);
_(data);
if(data.success === false){
showError(data.msg);
}else{
showError(data.msg);
window.localStorage.setItem("authToken", data.token);
var token = window.localStorage.getItem('authToken');
if (token) {
$.ajaxSetup({
headers: {
'x-access-token': token
}
});
}
}
}
});
And this is the route authentication I am using to check before any of the routes is accessed:
router.use(function(req, res, next){
var token = req.headers['x-access-token'];
console.log(token);
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}else{
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
In console.log(token) I get an Undefined variable , it seems like I don't know how to access the token from route.
Thanks a lot.
"x-access-token" must be registered as an allowed header
response.setHeader("Access-Control-Allow-Headers", "x-access-token, mytoken");
Check this post :
How do CORS and Access-Control-Allow-Headers work?