I stored jwt in a http only cookie. I can access it automatically in java controller classes as it gets included in the request. However, I can't find a way to get the token for JavaScript ajax in order to post a request to the APIs. Those APIs require the token in authorization header. Am I doing it the wrong way?
The whole point to set a cookie as http-only so that it can not be assessed by client-side javascript. If you want the token to be included in the header from the client-side request
you can set the header Authorization: Bearer 'your token goes here'
Related
I have one basic question while porting my tool running in one environment (env1) to another one (env2). We used csrf token for authorization in env1, but as long as I know, it doesn't be used in env2. I fixed it by adding bearer token in the header every request in env2. Because we use oAuth and bearer token and add it also in mod header in chrome. So I just tried to add this bearer in the request header, and it worked.
What I'd like to know is that what is the advantages to use bearer token and add it in mod header?
I think it is quite complex.
Thanks
That is the JWT standar, you need to send Bearer Token in http header
in other case the endpoint won't find the token
about advantages:
you have many data in token, you can decode here: https://jwt.io/
is the most common way to create authentications
JWT can be secure, that depend How you configure in frontend and backend, there are many variants
I'm a bit frustrated with managing my JWT token during login, submits and redirects. Before I get started here's my technology stack just in case:
JQuery/Html -> Node.Js -> Java Restful Services -> MySQL.
My java Restful services manages creating the JWT Token returning it to the Node.js layer which decides what to do with it and pass it on the the client. This all works wonderfully.
To get the JWT token I'm making an ajax based authentication request to the Node middle tier, which authenticates and returns the token which is summarily crammed into localstorage on the client.
Now I have no desire what so ever to make the entire site load off a single page through ajax, it's a complex site and doing that is just dumb! I need to forward and navigate to sub pages while carrying along the JWT token.
Here's the question (finally)... How do send along the JWT token to the middle tier (node.js) without attaching it as a request or post parameter because that's a big no no? I can't seem to find a way to stuff it in the header associated with Bearer.
You need to store the token at client side using for example a cookie or localStorage
Ajax requests
Cookies: A cookie is sent automatically when making a request to the server, so you do not need to add a specific header
LocalStorage:It is needed to provide the token in each request using an HTTP header.
For example
POST /authenticatedService
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
This is an example code to show how to execute an ajax POST request using jquery
$.ajax({
type: "POST", //GET, POST, PUT
url: '/authenticatedService' //the url to call
data: yourData, //Data sent to server
contentType: contentType,
beforeSend: function (xhr) { //Include the bearer token in header
xhr.setRequestHeader("Authorization", 'Bearer '+ jwt);
}
}).done(function (response) {
//Response ok. process reuslt
}).fail(function (err) {
//Error during request
});
Form submit
With a form submission you can not control the headers set by browser, so it is not possible to set the Authorization header with a Bearer token. In this case you can
Cookie: store the JWT in a cookie that will be sent with the form data. You will need to add extra security to avoid CSRF attachs
Form param: The JWT is stored in a hidden field of the form.
Use always POST (not GET) to avoid cache of JWT
Link
A link executes a GET request. You could build the link adding the JWT as a query param url?jwt=...
But, consider in this case the security risks. Browser can cache the url and it will be present in logs. An attacker could potentially obtain them if he has access. Also the user could copy the link and use it outside your web application (e.g send it by email...)
If you use cookies, the token will be automatically sent to the server by clicking on the link, but this will only work if the user is authenticated. In this case be aware of CSRF vulnerabilities
Your only option is to store the token in a cookie if you don't want to do anything suggested above. You can't set http headers in links.
I have just learned about JWT for authentification. Storing the JWT token in localStorage/sessionStorage is exposed to XSS. Storing it in a cookie is vulnerable to CSRF. I have been researching this and I thought of this solution, but I'm not sure how secure is this and if I should be using it in production.
The soulution is to get the JWT token from server, store it in cookie. Generate a CSRF token (that will be stored in JWT) that will be sent with each HTML page, either in a hidden HTML field of as a global JS variable (). That CSRF token will be sent with every request using JS/AJAX. This way we can rule out CSRF first then verify the JWT token.
I'm not sure whether a new token should be sent with each loaded page, or a single token should be held per session. The 1st case would mean that only the last loaded page/form would be able to submit (which could be problematic if the user is having multiple tabs of other pages open).
Is this a secure solution that might be used in production ?
Also, what other solutions would be viable to reach the same goal ?
Here is my understanding of the issue.
JWT Token - stored in httponly/secure cookie - this ensures any Javascript does not have access to it
CSRF Token - stored by JS - on login, attach the claims as a header (including your CSRF value)
When the JS gets the header, it can store the claim in a cookie, localstorage, or session storage. Because no JS has access to the JWT token in the cookie, by attaching the CSRF with every request and making sure it matches what's in the JWT, you're ensuring that it's your JS sending the request and that it was your backend that issued the token.
A hidden field isn't a great solution because you'll have to add it to each request. Depending on what framework you're using, you should be able to load the CSRF token into whatever is responsible for sending the token as a header on each request when the page is refreshed. The benefit to having all the claims in local storage or a cookie is you can preserve the users front end state. Having the exp claim means you can tell when the user no longer has a valid token in the secure jwt token cookie and you can redirect to a login page.
sessionstorage - is specific to the tab only
localstorage - is specific to the domain across tabs
cookie - is specific to the domain across tabs
Add CSFR to AJAX request:
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("CSRF-TOKEN", csrfToken);
},
url: "entities",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
Even though you're not using Angular, this still applies. You should attach the token as a header with the JS and it's fine to get that value from a cookie.
From the Angular JS Documentation
When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.
I am working on a simple website using jwt. (node.js, koa.js)
Most example codes including expressjs, I cannot find the client-side example
about how to deal with jwt sent from a server.
Only one example (https://github.com/auth0-blog/cookie-jwt-auth) showed me that
[index.html]
... script src="app.js...
[app.js]
$.ajax({
type: 'POST',
url: 'http://localhost:3001/secured/authorize-cookie',
data: {
token: token
},
headers: {
'Authorization' : 'Bearer ' + token
}
After I read this example, I felt that I should have some scripts for users to send an authorization header with jwt. Is it right?
Or are there some front-end frameworks that deal with authorization header?
Thank you for reading newbie'q question.
Yes, you will need to define a mechanism for sending the user's JWT back to the server. It's up to you to decide where the JWT will live in the request -- the most common places are in the Authorization header, or by setting a cookie on the browser (which will be sent along with every HTTP request). You should also consider whether you want the JWT to persist across sessions / page reloads (using for example document.cookie or localStorage).
If you choose not to use the cookie approach, you can configure all $.ajax requests to set your Authorization header "pre-flight" using $.ajaxSetup({...}) (but this is a bit of a sledge-hammer approach). Manually setting the Authorization header on each individual $.ajax request, as you've demonstrated above, is a good option too.
If you want to skip headers all together, you can send the JWT inside the body of your request (as JSON, for example).
I have an Angular.js application and I am trying to implement authentication to my PHP backend using a JWT.
I have the app setup to set the token on login and send the token with every request if it exits. I was following the information here, though it is for Node.js not PHP: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/.
The information there was extremely helpful, but I do not understand why the token should be in the Authorization header with the text 'Bearer ' before the token. Could I just put the token there without 'Bearer '? Is there a recommended method for where the token should go in the request?
My other issue is where to store the token on the front end. The website recommended using $window.sessionStorage which doesn't seem to work well for my case because it seems to prevent someone from using multiple tabs which isn't very intuitive.
My question really comes down to:
Where do I put the token in the request header?
How should I store the token on the front end?
The use of the Bearer keyword is recommended in the RFC6750 - section Authorization Request Header Field:
Clients SHOULD make authenticated requests with a bearer token using
the "Authorization" request header field with the "Bearer" HTTP
authorization scheme. Resource servers MUST support this method
The libraries I've been working with always require it before the token itself. So the request header should be as follows:
Authorization: Bearer your_token
Regarding the storage I have seen it in $window.sessionStorage too