How to add a JWT to header after successful login


How to add a JWT to header after successful login



I am building a web app using Symfony 4 and I am trying to implement the back end as a REST API.



As part of the login process I have created an end point that returns a jwt upon receiving a valid username and password. I then save the jwt to local storage in the browser as so:


$(document).ready(function() {

$('.js-login-form').submit(function (e) {
e.preventDefault();

let username = $('#_username').val();
let password = $('#_password').val();
let data = JSON.stringify({_username: username, _password: password});

$.ajax({
method: 'POST',
url: '/api/tokens',
contentType: "application/json",
dataType: 'json',
data: data,
success: function(data) {
localStorage.setItem('token', data.token);
// Add Header to the request Authorization: "Bearer " . data.token
window.location='/app';
},
error: function(jqXHR) {
var errorData = JSON.parse(jqXHR.responseText);
console.log(errorData);
}
});
});
});



My question is how I can add the jwt to the header so I can redirect the user to the password protected area. My guard authenticator will then validate the token accordingly.



Many thanks









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?