How to attach Json Web Tokens to an http header? - json

Most JWT tutorials I've seen say that you can attach it to the headers with AJAX. How do you attach the token on the initial page load?
For example, if a user goes to the base URL '/' and they don't have a token then show them the page. If they do have a token, redirect them to their profile page.
Edit:
I'm returning the generated token with a jquery ajax success function then redirecting the user. When the user gets to the home page ('/'), I'd like the access token to be sent via http headers to my server. Then the server can handle the request. However, anytime the user returns (if they close the browser and go to "mywebsite.com" or any other page), I'd like the server to be able to access the token. Are http headers the best way to do this?
success: function(token){
localStorage.setItem("token", token);
window.location.href('/');
}
If my application was a Single Page App (SPA), I could just use ajax all of the time, but it's not.

You cannot achieve what you want with HTTP headers. HTTP headers are something which are sent when a request is made to the server. In your case, you want to remember something about the client even if they close their website and come back later. The easiest to do that is through cookies.
Basically generate the JWT token for the client and send it to the client as a cookie. This logic will be written on the server side and there are many libraries available to do this depending on the technology you have chosen for server side. Then everytime the client makes a request to your server, browsers make sure that the stored cookies are sent.

Related

Security To Implement On Persist Cookie REST Api Website / Mobile Apps

So my current state is I have a REST API web server (ASP.Net Web API), a website in plain Html which communicates with the server via ajax / angular post and get, also I have a mobile application which communicates via ajax / angular post and get.
I use Basic Auth header to secure the request, the web server will decrypt the content of the auth header and do the verification after.
What kind of attacks would the system be vulnerable to? Also what kind of security should I implement.
I read about the CSRF attacks and I think my system have no protection against it, but I have no idea how to implement it on REST API.
Also what about the cookie stealing attacks. Because my system uses persist cookies to store the auth token, how to deal with this kind of attack?
To prevent CSRF attacks, both your backend (ASP.NET Web API) and frontend (Angular) must be configured to prevent such an attack.
Taken from https://angular.io/guide/security#xsrf:
To prevent XSRF, the application must ensure that a user request originates from the real application, not from a different site. The server and client must cooperate to thwart this attack.
In a common anti-XSRF technique, the application server [backend] sends a randomly generated authentication token in a cookie. The client code reads the cookie and adds a custom request header with the token in all subsequent requests. The server compares the received cookie value to the request header value and rejects the request if the values are missing or don't match.
This technique is effective because all browsers implement the same origin policy. Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site. That means only your application can read this cookie token and set the custom header. The malicious code on evil.com can't.
With that in mind, here's another quote from Angular HttpClient Docs which explains how you can implement it.
Taken from https://angular.io/guide/http#security-xsrf-protection:
When performing HTTP requests, an interceptor reads a token from a cookie, by default XSRF-TOKEN, and sets it as an HTTP header, X-XSRF-TOKEN. Since only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
By default, an interceptor sends this header on all mutating requests (POST, etc.) to relative URLs but not on GET/HEAD requests or on requests with an absolute URL.
your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the X-XSRF-TOKEN HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security.
Key points to take note would be:
When the angular app is loaded, it should make an API call first to your backend to retrieve an authentication token that is saved as a cookie that with the name "XSRF-TOKEN". Probably somewhere on root component (app.component.ts) ngOnInit() sounds like a good place.
By default, the authentication token will be automatically injected in the http header on all mutating requests such as POST. (Take note of this though, it is undocumented: Angular 6 does not add X-XSRF-TOKEN header to http request). Unless you return a custom-named cookie, then you have to use Angular's HttpClientXsrfModule.
With that in mind, your ASP.NET Web API should also be validating the XSRF-TOKEN as it receives requests.
With regards to your second question, cookie hijacking is done via XSS.
XSS vulnerabilities generally occur when an application takes user input and outputs it to a page without validating, encoding or escaping it.
Angular by default sanitizes inputs for tags. However, this is provided you do things "the angular way". If you use third-party libs, such as jQuery, to manipulate the DOM instead of using Angular's renderer2 module, you might lose this protections.
Taken from: https://angular.io/guide/security#xss:
In the same way, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations. Avoid directly interacting with the DOM and instead use Angular templates where possible.
For cases where this is unavoidable, use the built-in Angular sanitization functions. Sanitize untrusted values with the DomSanitizer.sanitize method and the appropriate SecurityContext.
To increase security, you should also sanitize any mutating requests (such as PUT or POST) in your backend.
It is difficult to provide you with code examples because your question seem to be a more theory-based question.
I hope you will take a read on those links that I have hyperlinked above. They are definitely more detailed and well-explained. I hope it will at least point you in the right direction of what to get started on.

Send authorization header when accessing URL

I want to send the authorization header when I view the webpage of a local IoT device (http://deviceip). The device uses an authorization header encoded in basic.
I have created a web server using Node.js and Express.js with a URL link to the device, but I have not been able to set the authorization header properly and end up with a login prompt.
I have been able to get it working by using a separate proxy server which sends the header upon request and changing the webserver's links to the proxy which sends the authorisation header.
proxy.on('proxyReq', function(proxyReq, req, res, options) { // allows you to alter the proxyreq request object to send authentication before connection
proxyReq.setHeader('Authorization', auth); // sends Authorazition header auth
});
Is it possible to send the authorization header using a function in the web server when the URL is clicked as opposed to using the proxy?
"Is it possible to send the Authorization header using a function in the web server when the URL is clicked as opposed to using the proxy?"
No, it's not possible. The reason is:
The only way to add headers to a request from inside a browser ("the URL is clicked") is using the XmlHttpRequest (Ajax).[source]
If it is an Ajax request, you can't fetch the html response and then re-render the whole page. Otherwise, it would bring huge security problem -- any JavaScript code in browser can send an Ajax request and show user a completely new page, which is perfect for phishing attack.

HTTP request and response messages

If a user requests a HTML web page that consists of some text and three images. For this page, will the client send one HTTP request message and receive four HTTP response messages from the server? or will client have to send separate HTTP request message for each of the three images?
The client requests one resource at a time. It first gets the HTML response. It then parses that response and finds references to images in there. It then goes to fetch those images in separate requests; or perhaps gets them from a local cache if it already has them.
Note that in HTTP/2, the server can proactively send the images together with the initial HTML response if it anticipates that the client will ask for them anyway. That shortens the roundtrip time considerably, but also means the client will receive a large response whether it has already cached the images or not.
The client sends the connection request, and then when the server accepts the request, the server sends the web page to the client in small packages, when the client receives the response from the server the web page is displayed.
I hope this resolves the doubt.

Are JSON transfers automatically encrypted when the server is on Heroku?

I was thinking that I needed more secure ways to transfer data between my app and my server on Heroku. I'm worried about MITM attacks. Then I noticed that the web server uses an https address. Does this mean that the JSON I'm sending to the server is automatically encrypted? What about when the server sends JSON back to the client?
If the link the JSON request goes to starts with https then yes. JSON is just content sent over http/https and responses are sent over the same method as the query.
However, if you are on a webpage and there is an ajax call made in the background, then maybe not.
In all cases, it depends on where the http get request goes to: if it starts with https then you are fine.
It sounds like your saying the request for json data is made over https, in wich case you are fine.

How to handle cross domain iframe file upload json response?

I'm building an files upload API.
Basically, the user will have to POST the files with his/her api_key + signature to my web service. Then my web service replies back with a JSON response. I'm wondering how can this process work asynchronously?
Assuming that the user POST the request in a form setting the target to an iframe. The JSON response will be sent back to the user on his/her iframe with content type set as "text/html". It is set as "text/html" instead of "application/json" because I want to avoid having a "pre" tag injected by the browser around the JSON response. Anyway, how does the user read that JSON response if the iframe and the parent window have different domain? There is going to be a cross domain policy issue.
Dynamically create "script" tag plus JSONP won't work in this case because I need to POST in order to upload. JSONP only works with GET requests.
Take a look at the 'Upload' example here. It uses Cross Domain messaging to pass the message back to the uploading page, and uses easyXDM to support all browsers.
This post explains how it all works!
Because of Same Origin Policy, browsers wont allow JavaScript in the main frame reading/accessing whatever content in iframe from another domain. In this case, the users will have to use easyXDM or create their own proxy -- by proxy here i mean users will have to write some code on their backend that can communicate with your API such that a post request will go directly to your server, and a get response will get from their own proxy.