I am trying to find a way to send a JSON Web Token created on the server side to the client, so that the client can store it in the HTML5 local storage.
Specifically, my application, which is built with NodeJS/ExpressJS, using Passport for authentication, has two kinds of users: local users and facebook users.
When a local user fills the login form with their username and password, the client asks for authentication from the server and the server sends to the client the JWT, which is then stored in local storage.
$.ajax({
url: "/authenticate",
type: 'POST',
data: user,
dataType: "json",
success: function(auth){
localStorage.setItem("token", auth.token);
window.location.href = '/welcome.html';
},
failure: function(errMsg) {
alert("falure");
window.location.href = '/login.html';
}
});
Then, the user is redirected to a Welcome page, which looks in local storage to find the token, in order to ask for some data from the database.
$.ajax({
url: "/protectedEndpoint",
type: 'GET',
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', localStorage.token);
},
success: function (data) {
...
},
error: function (e) {
alert(e.status + " " + e.statusText + " - " + e.responseText);
}
However, when a facebook user logs in, everything happens on the server side, so I don't know how I can store the JWT in local storage.
Here is the server side code for facebook-passport authentication:
app.get('/auth/facebook', passport.authenticate('facebook', {scope: ['email']}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {session: false, failureRedirect: '/login.html' }),
function (req, res) {
res.redirect('/welcome.html');
});
Thanks a lot in advance!
Combining the OAuth with JWT isn't the main use case as you already found out. As one of possible ways is to transfer the token with the redirect URL in OAuth callback.
passport.authenticate('facebook', {session: false, failureRedirect: '/login.html' }),
function (req, res) {
// Create JWT token here are pass it back to front application
res.redirect(`/token/${JWT}`);
});
In frontend application setup the route that could handle the token save it to local/session storage.