How to reject http/https request if not coming from allowed website or source - rest

I have an api service: my-api.com/getData
My api expects an api-key from customer to authenticate the request.
My customer's front-end hosted on: customer.com
My customer's back-end hosted on: customer-backend.com
There is no Log-in option in customer's website
Scenario
In customer's website, a button sends request to customer-backend.com/use-my-api
This request executes post('my-api.com/getData', api-key) in backend
So visitor gets data and visitor is not able to see api-key of my customer.
Problem
When a smart third guy uses post('customer-backend.com/use-my-api')
in his own website or back-end. He gets data without providing api-key
This is a very unwanted situation for my customer
Question
How can we reject all requests from outside of the allowed website or source. Changing the architecture of service is not a problem for me and my customer.
As far as i know checking request headers for host is not a reliable. Since it can be changed by sender easily.

An HTTP request does not come "from a website", but it comes from an HTTP client, for example, a browser that is visiting the website. In order to prevent unauthorized requests, your customer's backend must issue a "secret" to the HTTP client, which the client must then include in the request.
A common technique to achieve this is the following:
Visitors must log-in to your customer's website.
After successful logon, your customer's backend sends a session cookie to the visitor's browser (this cookie is the "secret", because it is visible only to the visitor and cannot be guessed by "smart third guys").
The request which the visitor makes by pressing a button includes the session cookie.
When your customer's backend (customer-backend.com/use-my-api) receives a request, it validates the session cookie before making the post('my-api.com/getData', api-key).
Without a log-in mechanism or something equivalent, your customer's website is public and can be (mis-)used by anyone, even if that leads to (paid) API requests made with the customer's API key.

Related

CSRF Tokens with separate API and Web Server

I am learning about CSRF Tokens and how they help secure your web application. I understand the basics of it, but I am confused as to how it works in practice when the web server and api are separate. In practice how is the token generated, added to the HTML and known by the API?
For example, if I host my web app on something like Nginx or S3 and serve APIs via Spring Boot, how does the HTML with the embedded token get generated and passed to the client? Would the Sprint Boot API need to generate the token and HTML and return that to the client? Is there a different flow that am I missing? If this is the case, what is the point of it being embedded in HTML at all?
All of the documentation I have read assumes you are using something like MVC or skips over this entirely.
CSRF protection is only necessary for requests made by a client (for example, a browser) that silently adds credentials for the current user, by sending a session cookie, resending username and password that were previously typed in ("Basic Authentication") or by including a client certificate. This is because users may be tricked into making unwanted such requests by visiting a malicious web page, and these unwanted requests are then made with their credentials, that is, on their behalf.
For requests made by your web server to an API endpoint, this does not apply, therefore the API endpoint need not offer CSRF protection. A web server cannot be tricked into making unwanted requests.
Or can it? Imagine that the web server offers a "proxy" endpoint that converts incoming requests into requests to the API endpoint, and that sends the API response back to the client:
Client --request--> web server --converted request--> API endpoint
Client <--converted response-- web server <--response-- API endpoint
Further imagine that, as part of the request conversion, credentials from the client are forwarded to the API. For example, a session cookie coming from the browser is converted into an Authorization: Bearer <jwt> header that is sent to the API endpoint. Then an unwanted request to the web server endpoint with credentials effectively becomes a request to the API, and a new CSRF vulnerability has appeared: this time on the web server.
The web server must then protect its own "proxy" endpoint against CSRF by issuing and validating a CSRF token.

RESTful registration with activation email

I'm working on creating a REST API and one feature is to allow users to register. The general flow is the following:
The user specifies his email and password using the client application (SPA application) and presses the submit button.
A request to the API is made. The API adds the user to the database, generates a verification token and sends an email to the user.
The user verifies his email and clicks a confirmation link.
The API marks the user account as verified.
My question is regarding the confirmation link.
Should the link point to the client SPA application? In this case, the client application will make a POST request to the API with the verification token and the user email.
Also, how should the API know the link to the client application (the link needs to be added in the email and this is done by the API). Should the API store this link, or should the SPA client send the verification link to the API when sending the request to register the user?
Another approach would be for the link to go to an endpoint defined by the API. In this case a GET request will be made with the user email and verification token and the API will set the account as verified and inform the user that his account is now active.
I have read that this approach doesn't conform to the REST principles because a GET request should never change the state of a resource. In this case, the user resource will be modified.
I'm not sure which of the 2 solutions is better or if there is a better solution, so my question is what is the best approach?
Thanks!
Should the link point to the client SPA application?
If your 'Client SPA application' is the sole frontend for end-users, then yes: it should point there. Some people deploy a separate oauth2 / authentication server but that doesn't sound like it's the case here.
The client application will make a POST request to the API with the verification token and the user email.
The token should be enough. I'd avoid sending email addresses through urls.
Also, how should the API know the link to the client application (the link needs to be added in the email and this is done by the API). Should the API store this link, or should the SPA client send the verification link to the API when sending the request to register the user?
Both seem like really valid designs. If you want the API to be completely unaware of the front-end and support a multitude of frontends, it would make sense to me that the client sends their own endpoints. There is a security concern though, you don't want arbitrary clients to register arbitrary urls.
If you're just building a single frontend, I don't see a problem with the API knowing the activation url. It also sounds like it would be easy to change if your requirements change later.
I'm not sure which of the 2 solutions is better or if there is a better solution, so my question is what is the best approach?
Ultimately it doesn't really matter that much. Neither approach sounds like you're really painting yourself into a corner. Either you have a standard endpoint that uses a javascript HTTP request to activate a user, or you have a separate endpoint that redirects a user after activation. Both will work.

What is the correct workflow for auth to a web site which uses a REST api

I have a web site written in Angular that uses a REST api in order to provide functionality.
I would like to know the proper workflow for authentication to the website.
Let's go back to 1999 - I write a website and all the logic is in the web code. There is no REST API. If someone wants to log in to the website they enter their email and password and I store a cookie on their machine and they now have a 'logged-in' session on my website. By having this cookie they are authorized to do certain things such as write a comment.
All good.
Fast-forward to my new website. This website is written in Angular and all content is provided via a REST API. Some of the REST calls just display data like a bunch of comments. Any anonymous user can make these calls just by browsing the page. However, there the user can log in to the website using their email and password. Again, I store a cookie on the user's machine and they are logged in to the website. Now, because they are logged in to the website they can post comments. These posts are done via a REST API call. However, Google and the Interweb have told me that my REST API should be stateless and i should be using oauth2 for this request.
My question is, what is the workflow for this very common auth pattern?
I thought maybe something like:
User logs in with username and password
One request is sent to my web auth server and a session cookie is created
A second request is sent to my api auth server which issues a valid token for further requests
The two systems are quite separate and do not depend on each other.
If i was to add social login to the mix then (2) above would just be authentication to the required social auth server and (3) would be unchanged.
Yes, your REST API should be stateless.
This is a typical workflow for authentication for a REST API.
User logs in with username and password.
A JSON web token is issued upon login from the backend and sent to the browser.
The JWT(JSON web token) can be stored in a cookie in the Web Storage(local/Session Storage) on the browser.
Subsequent requests to the REST API will have the token embedded in the header or query string for authorization. With that form of authorization, your REST API understands who is making the request and what kind of resource to return based on the level of authorization
A practical example of this can be found in this blog post. Angular 2 was used for the sample app implementation.
I hope this helps!

Why Having a CSRF protection in a REST context doesn't make sense?

Someone to explain please (hopefully with simple words for newbies) why a web application built upon a RESTful API can be CSRF exempt?
I received such assertion after asking: Serializing FormView data in JSON, but honnestly I can't figure out why?
Thanks in advance
CSRF or Cross Site Request Forgery, in layman terms, is meant to allow only selected sources(your own website) to submit data to particular url. It prevents misuse of your functionality by other websites or robots.
Say, I have an url for registration, /registration/, but I don't want to allow external submission of POST data to /registration/. So, I would provide a crsf cookie(depending on host and other stuff) when GET request is issued for /registration/, and ensure that same cookie is provided with POST request. This will ensure that users who have requested the registration form(i.e. genuine web users, not robots), would be able to register. It is not completely full-proof, but ensures some level of security.
Now, We don't use CSRF in API's due to following:-
Technically, CSRF is stored as cookie, since browser is not the intended client of API's, it is of no use.
Secondly, API's are supposed to use specialized client and user authentication, thereby eliminating the need for using any CSRF protection.
Thirdly, Restful api's are supposed to be stateless, therefore the order of API calls should not matter, which is essential for working of CSRF.
Note:-
If you have frontend framework like Angular or intend to use api's on browser too, then it is perfectly ok to use CSRF. In that case you are suppose to write two types of authentication for your apis.
Token Based Authentication - for non-browser clients
Session Authentication - for browser based clients (With csrf)
In this case, any request to api must authenticate with atleast one of the authentication.
According to owasp.org:
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, email, blog, instant message, or program causes a user's Web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.
This is not an issue for REST Web services because either:
1) you usually want your service to be accessible from multiple applications (Mobile app, browser, etc.)
2) you have to provide a direct authentication for each request, so this kind of attack is not applicable for REST services. The authentication is done by your application (let's say javascript) and no directly by your browser (sending the session id), so even if a malicious application redirect the user to your webpage, it cannot automatically trigger your javascript function to perform the request (and the authentication).

Questions regarding authentication workflow with REST, and Backbone

I am currently working on a website built with Backbone.js. The site has a RESTful API built in Symfony with FOSRestBundle. Developing was going fine, until I stumbled in to some user-related tickets.
From what I understand, the best way to handle this type of problem is with a token based system, where the user gets an access token after an approved login. I will describe my current perception of the workflow, and ask questions along the way. More importantly, please correct me if I have misunderstood.
First, the user the accesses the login form, then the user types in credentials, and an AJAX request is send to the server. From what I understand this should all be handled with SSL, but with Backbonejs, you can't simply say that the login page should be accessed with HTTPS, as Backbone is a one-page framework. So will this force me to use HTTPS through out the application?
In the next step, the REST server validates the credentials, and they are approved, then the REST server sends an access token to the client. Is this token saved (on the client-side) in local storage or a cookie?
Also is the login stored at the server, so that the REST server can log the user out after a certain amount of time?
Now, the client sends this access token along with other request, so that the server can identify the client, and approve the request or not. So the access token is also stored on the REST server?
Lastly is this what the smart people call "oauth", or does it relate to it?
Thank you.
Let's take your questions one at a time.
From what I understand this should all be handled with SSL, but with Backbonejs, you can't
simply say that the login page should be accessed with HTTPS, as Backbone is a one-page
framework. So will this force me to use HTTPS through out the application?
Ok, there's a lot to unpack there. Let's start with SSL/HTTPS. HTTPS is a protocol; in other words it defines how you send packets to/from the server. It has nothing whatsoever to do with whether your application is single or multi-page; either type of site can use either HTTP or HTTPS.
Now, that being said, sending login info (or anything else containing passwords) over HTTP is a very bad idea, because it makes it very easy for "bad people" to steal your users' passwords. Thus, whether you're doing a single-page or a multi-page app, you should always use HTTPS when you are sending login info. Since it's a pain to have to support both HTTP and HTTPS, and since other, non-login data can be sensitive too, many people choose to just do all of their requests through HTTPS (but you don't have to).
So, to answer your actual question, Backbone isn't forcing you to use HTTPS for your login at all; protecting your users' passwords is forcing you.
In the next step, the REST server validates the credentials, and they are approved, then
the REST server sends an access token to the client. Is this token saved (on the
client-side) in local storage or a cookie?
While any given framework might do it differently, the vast majority use cookies to save the token locally. For a variety of reasons, they're the best tool for that sort of thing.
Also is the login stored at the server, so that the REST server can log the user out
after a certain amount of time?
You've got the basic right idea, but the server doesn't exactly store the login ... it's more like the server logs the user in and creates a "session". It gives that session an ID, and then whenever the user makes a new request that session ID comes with the request (because that's how cookies work). The server is then able to say "oh this is Bob's session" and serve the appropriate content for Bob.
Now, the client sends this access token along with other request, so that the server can
identify the client, and approve the request or not. So the access token is also stored
on the REST server?
If you're running two separate servers they're not going to magically communicate; you have to make them talk to each other. For this reason your life will be easier if you can just have one (probably REST-ful) server for your whole app. If you can't, then your REST server is going to have to ask your other server "hey tell me about session SESSION ID" every time it gets a request.
Lastly is this what the smart people call "oauth", or does it relate to it?
Kind of, sort of, not really. OAuth is an authorization standard, so it's sort of tangentially related, but unless your login system involves a whole separate server you have no reason to use it. You could use OAuth to solve your "two servers, one REST-ful one not" problem, but that would probably be overkill (and regardless it's outside the scope of what I can explain in this one Stack Overflow post).
Hope that helps.