Salutare,
In ultimele 2 saptamani am inceput sa invat nodejs.
Ma chinui cu o chestie de vreo 3 zile si ce am gasit pe google nu m-a luminat deloc.
Incerc sa fac un sistem de autentificare cu JWT si nu stiu cum sa trimit headerul ‘Authorization’ impreuna cu jwt cand fac requestul catre pagina restrictionata (/dashboard)
Ce am facut pana acum:
Login front(ajax), salvez JWT in local storage:
// process the form
$('form#form_login').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=loginUsername]').val(),
'password' : $('input[name=loginPassword]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/api/authenticate', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
.done(function(data) {
// here we will handle the json response
if(data.success === false){
console.log('ERROR');
console.log(data.msg);
$('.isk_messages').html(
'<div class="col-md-6 col-md-offset-3"><div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>Warning!</strong> '+data.msg+'</div></div>'
);
}
else if(data.success === true){
console.log('GO');
var success_message = '<div class="col-md-6 col-md-offset-3"><div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>Success!</strong> Welcome '+data.user_logged+' You will be redirected to your Dashboard in 3 seconds..</div></div>';
$('.isk_messages').html(success_message);
var form = document.getElementById("form_login");
form.reset();
localStorage.removeItem('Authorization');
localStorage.setItem('Authorization', data.token);
// setTimeout(function(){ window.location.replace(data.home_url+'/login'); }, 3000);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Login back:
router.post('/api/authenticate', function(req, res) {
User.findOne({
username: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
var token = jwt.encode({nume:user.username}, config.secret);
res.json({success: true, token: 'JWT '+token, user_logged: req.body.name});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
Routarea path-ului protejat catre passport-jwt:
router.get('/dashboard', passport.authenticate('jwt', { session: false}), function(req, res) {
res.json({success: true, msg: 'Welcome in the member area ' + req.user.username + '!'});
});
Passport-ul cu strategia jwt:
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({username: jwt_payload.nume}, function(err, user) {
console.log(jwt_payload);
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
Daca fac requestul din Postman cu headerul key: Authorization value: jwt-ul stocat in local storage, primesc jsonul asteptat.
Cum as putea sa trimit acelasi header atunci cand accesez din browser adresa protejata (/dasboard)?