How to restrict the access to backend API to be only accessed by the react app? - reactjs

I am creating a public facing SPA web application using React js.
The backend for this application are the endpoints available under Azure APIM. I would like to restrict the access to these APIM endpoints in a way that they are only accessible from my react app.
As the react app will be rendered in the user's browser, I cannot have any IP restriction on my APIM backend inbound policy, as the application could be accessed from anywhere ( public facing). But if anyone gets access to the API url by inspecting the network traffic in the browser , my backend API's become vulnerable.
How can I restrict that APIM endpoints are only accessible from the react app ?
I have tried using CORS policy to allow my domain , but still tools like POSTMAN are able to access the endpoints.

The short answer is you cannot fully prevent people from hitting your public API endpoint on their own.
The longer answer is that you can put protections within your API config so that this isn't a concern. If all requests need a valid user authentication token, for instance, it doesn't matter if that valid request comes from your React UI or an errant user's terminal window. Check out some best practices on protecting your API endpoints, and it will hopefully answer your question.

You can't. At best you can obstruct the user by making it harder to replicate a proper request to your API. Ultimately there's no way to identify whether or not a request came from a browser or some other tool though.
It's up to you to construct the API in such a way that the user can't abuse it by limiting the user to only perform actions that they should be allowed to make. If you are concerned by a user overloading your API you can add a policy to APIM to apply rate limiting (e.g. by IP).

It not be possible to prevent attackers from inspecting HTTP traffic and the vulnerable calling endpoints.
You should implement authentication controls on API. Whenever a user opens a new session on you SPA, the API grants that user a token that is valid for a fixed amount of time (~30 mins). Ensure that the API checks if that token is valid for each request.

Related

AWS Cognito Identity Service Provider appears to store access token in local storage. Is this safe?

We are developing an application that uses a React front end website hosted on AWS using Amplify. This communicates with a .NET Core 3.1 Web API running on EC2 / Elastic Beanstalk. Cognito is used for user authentication with the Web API configured to use JWT tokens.
It works OK, but we have noticed that the Cognito provider stores the JWT access token in the browser local storage. This is what we see using F12 in Chrome and inspecting local storage.
From what we have read, storing access tokens in local storage is not advised as it makes the application susceptible to XSS attacks. Strange then, that the Cognito identity provider chooses to store sensitive information here.
If this approach is not considered safe, can the provider be configured to store this information elsewhere, such as cookies?
Alternatively, as we control both front and back ends, is there an alternative method that can be used to secure the API that does not involve tokens? Obviously the API needs to know which user is logged on to the web application in order to perform authorization checks. [Note authorization in the application is record level and defined in database tables, so it goes beyond simple user profile attributes.]
Many thanks in advance for your advice.
Doug
Security is a spectrum not a feature so it really depends on your appetite for risk vs effort. Amplify is not a particularly nice codebase, it has 500+ issues and if you look at the code you might be fairly shocked at the quality of it.
If you are using Hosted-UI then you can write code to manage the tokens yourself rather than using amplify, although you will need to learn a bit about OAuth grants and OIDC.
Be aware that the Hosted UI lacks a huge amount of features, so if you are going to use it make sure you are happy with it. Off the top of my head
no silent refresh capability in the hosted UI, so no safe way to store the refresh token.
no support for custom auth flow in the hosted UI
no passwordless support in the hosted UI
no ability to pre-populate a field in the hosted UI (e.g. username)
no ability to customise the plethora of obscure error messages in the custom UI
fixed now, but for years the email addresses were case sensitive!
An alternative is also to just use the AWS SDK to get tokens directly using cognito-idp but this also has a bunch of issues:
no code/PKCE/nonce capability so insecure in a mobile authsession
no ability to set oauth scopes, so can't use them
consequently not possible to use for OIDC
the SRP implementation is bananas and so far off spec
if you make device registration mandatory, it will deliver a working access tokens before the device is registered! (allows invisible devices for malicious logins)
We were using auth0 which was leagues ahead but we had to move to Cognito because of SMS OTP cost (min $25k per year at auth0).
I have been using AWS for over a decade now, Cognito is by far the worst service I have used, and I have used a lot! If you can avoid it, do so.
To answer the original question, yeah it's insecure. The best you can probably do is keep them in memory. If you wanted to you could probably put the hosted UI behind a cloudfront and use an lambda#edge to transform the token into a cookie instead. This has now opened you up to CSRF attacks though.
answering the original question: no, it is not safe at all.
Storing refreshtoken in any local storage accessable to any local app/script is not secure. So, the best way would be to store the refreshoten (and also the access token) in an httponly cookie or even better to store a one-time session token in httponly secure cookie could be used to get new access and refresh cookies - similarly as it is made by cognito hosted ui with XSRF-TOKEN.
See below how I would solve (and plan to solve) this issue:
Some background:
Due to GDPR regulations I think I can not use the cognito hosted ui - I have to make sure users read and accept the general terms and conditions (giving clear and auditable consent) and can review and accept cookie policies as well before they type in any user data for sign up. Nevertheless the built in hosted ui design is quite outdated and unflexible. I have an SPA website where I want to manage users, secure endpoints, etc.
So I have the following idea which is still not super secure but I think it is more secure one if you want to use js and ampify sdk and which also might answer your question:
I'll use amplify javascript sdk to let users sign up, change psw and log in (get tokenid, access token and refresh token), will make my own "hosted ui". I'll store the access token in memory only (not in local cookies and not in localstorage for sure). Access token will be used in header (bearer) to access apiGW endpoints. Access tokens will have very short expire dates. (I'd also use httponly secure cookies sent back by the apigw, as well as in the body.., then compare at BE side..)
And here comes the trick: I'd cut the refresh token into two. (Don't forget it is just a string.) I'd store the first part of the string in a local cookie (javascript can read it, if browser is closed and opened again it will be still there) and will send the other half of the refresh token to an apiGW endpoint (accessable without authentication) which will store it in a dynamoDB table (with TTL) and will send back an httponly secure cookie to the browser with a randomly generated "storagetoken" in it (which will be a key in dynamodb). There will be another unauthenticated apigw endpoint which will be called by the client whenever the client needs the full refresh token. Calling this endpoint the browser will send in the httponly secure cookie as well (same domain), so the backend will get it. As it is issued by the BE and available only in the given browser it can not be stolen so the backend will send back the stored half refreshtoken. The other half part of refreshtoken is stored in a simple cookie in the browser.
If the browser is closed and opened again client checks if there is any valid accesstoken and if not it checks if there is a half refeshtoken stored as cookie. Then ask the other part of refreshtoken assuming there is a httponlycookie also stored and it will get back the other part of the refreshtoken from the BE. In case of success the client tries to use the full refreshtoken to renew/get access token from cognito, in case of failure it will pop up the login screen.
Whenever refreshtoken is not in use it is deleted from the memory.
I know this is still not supersecure but might be a better solution than storing refresh token in localstorage.
Alternatively, as we control both front and back ends, is there an alternative method that can be used to secure the API that does not involve tokens?
I don't know anything of Amplify but in AWS Cognito what you describe is the Implicit grant OAuth flow. In AWS Cognito it is possible to use Authorization code grant where you instead of the token get a code which you in the backend can exchange for a user pool token.
https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html

How to keep authentication token safe in js web apps?

I am not sure if I should create it here on StackOverflow or another stackexchange channel, but let's try here.
We have a web api made in asp.net core which uses the basic authentication where another web app post some login data to the api and it respond a token for the next requests. The client app stores this token and the next request to get/post data uses this token key for authentication. It works fine from the api perspective.
The point here is our web app. We are building it using react.js and the point how to keep the authentication token safe. We store the token on the current app (which is executed in a web browser). We have a feeling about store it on the browser because bad users can access the console on devTools and investigate how to to get the token from the global variables on the react app (just a sample). Given this point the questions are: How to deal with it to keep the back-end and front-end safe? How make sure the users cannot get the auth token and use it on another apps?
We were thinking in creating a kind of server-side channel just to store the authentication token like the picture bellow:
The web browser app make requests to server-side channel to get/post some data;
The server-side channel make a new request the API defining the authentication token and repassing the get/post data;
The api process the request and respond;
The server-side channel get a response from api and send it to the browser;
The web browser app get the final response.
It could work and keep it safe, but another question is: How computationally expensive is that?
Is there any possible solutions or suggestions how to deal with it?
Thank you.
Use JWT access tokens against your API and authenticate your SPA with an identity provider using an Open ID Connect flow (OIDC).
https://www.ubisecure.com/single-sign-on/single-page-application-and-openid-connect/
There are lots of examples of this, Identity Server is a common OIDC implementation with examples, http://docs.identityserver.io/en/latest/quickstarts/6_javascript_client.html
Once you've gone through the OIDC flow and acquired an access token for the user, you can store this client side safely, as
The access token has an inbuilt lifetime and once it's expired can no longer be used. Good practice is to keep this lifetime short (thus limiting the attack vector) and provide some sort of token refresh logic to automatically keep the user working against the API, as long as they keep the SPA open.
Your netcore web api has all the libraries it needs to do token validation / lifetime valdiation etc. This has been made very simple at the API layer
NB: I mention safely as there is still an attack vector, someone who acquires the JWT can act as that user for the lifetime of the token against your API, they are the bearer of the token. It's up to you to make sure the lifetimes of your tokens are sane and the the process for acquiring a new token is as secure as possible
There are a lot of examples on how to implement this, and whether or not you want to use your own Identity Server or use a solution such as Auth0.
Don't try and roll your own security solution. Stick to the specs and standards and adhere to all the industry best practices, making use of battle-tested libraries.
store token in local storage in web browser in encrypted form

ValidateAntiForgeryToken in windows authentication

Our application uses AngularJS and consumed Web API in the backend. This is only internal application and authentication used is 'Windows' mode only. We are using custom authorization(role-base) to limit the access/execution of the application web api methods.
My question is do we need to add ValidateAntiForgeryToken attribute for those web api action with HttpPost and HttpPut attribute? I never use this ValidateAntiForgeryToken before as I was only involved in internal web application (local intranet only). Please guide me when/how to use ValidateAntiForgeryToken.
ValidateAntiForgeryToken protects your users from malicious web apps that send a POST request to your web app unbeknownst to your user, known as CSRF. Still the request would succeed since it's coming from your user who actually has permission to do so.
This is irrespective of the actual authentication mechanism, and is in fact a higher risk for automatic single-sing on that you have with Windows authentication.
If your internal web app is worth the effort, a targeted attack could trick your users to visit the attacker's web site that in turn sends the POST request to your web app.
My take is that you should use ValidateAntiForgeryToken even in this situation as a defense-in-depth measure.

Utilize, but don't expose API (AngularJs/NodeJs)

I have an AngularJs application that consumes an API. I made this API with StrongLoop
What I want:
Be able to consume the API via AngularJs Controllers.
Not Expose the API endpoints to the user.
Now I was thinking I would somehow be able to do this with Node, where I query a local site URL with AngularJS and have Node process the routing and authentication token, but what stops the user from just using my local URL to get the results?
I want my website to consume the API, but not provide results to the user if they navigate to it themselves
That's the thing, on a HTTP level, there is no difference between the two.
Now you may implement an authentication and authorization system in place. Authentication identifies the client/user, and authorization decides whether a given user can perform a given action or not.
To implement the above, please refer to StrongLoop's Authentication, authorization, and permissions
Public APIs
If the API accessible to a AngularJS controller (a web client), just assume that it is accessible by the user by "putting the API URL in the browser". There's no way around this, both are valid clients to your API.
If you need to manage permissions, don't rely on the client side to prevent the user from doing it, but rely on the server side.
Permissions on the client side are just for good UX (User Experience, e.g. hide buttons to actions the user isn't allowed to perform).
The API itself doesn't trust any client.
Internal APIs
Once you have secured your public APIs, you may have internal APIs that only listen to requests from your node.js app to provide a specific service e.g.
public clients (ng-app, web browser) ---> public API (node.js) ----> internal API
Here you may have the internal API completely trust requests coming your node.js app, because the public API already deals with permissions and only calls the internal API with safe operations.
I think we need a bit more information on what exactly you're trying to restrict access to.
If you just want to limit the data exposed at the API to what's needed in the application the MVVM pattern might be a good candidate (I'm not familiar enough with StrongLoop to know if that's an option.)
Otherwise if you need to strictly restrict access to the StrongLoop API so only your server can access it, the Repository Pattern would be a good candidate for this.

Google Cloud Pub/Sub Publishing from Browser - How does Auth work?

I have a requirement to use Google Cloud Pub/Sub API directly from Browser ( similar to GA script). I was wondering how can in handle Auth without requiring going through a back-end server.
I want to invoke the Cloud Pub/Sub API directly from the browser. I tried and it says i need to authenticate first , my issue is how to secure the Auth Token.
Is there any javascript library that is available which i can use in Browser ( not backend) to invoke the Google Pub/Sub API.
Thanks in advance
The general approach in Javascript for authorizing and making authorized requests to Google APIs is shown at https://developers.google.com/api-client-library/javascript/samples/samples#AuthorizingandMakingAuthorizedRequests -- it's not specific to the Cloud Pubsub API, but it should work for all Google APIs. Similarly, https://developers.google.com/api-client-library/javascript/start/start-js for general Javascript access to Google APIs.
This is quite an old topic, but I've been recently assessing if it's possible. The simple answer is - yes, it is possible to send messages into PubSub topics directly from a browser application. The solution is as follows:
You need to post a message via REST API using fetch()
You need to send the Authorization header
Authorization header has to contain oAuth2.0 token identifying the user; it can be an anonymous authenticated user or fully authenticated, using firebase authentication library for example.
To have all three above working perfectly, you'd have to write a lot of code. It is not practical at all and architecturally not nice. Unless you absolutely need to do it that way, not another (I can't see why though), the simplified but involving a bit more components solution is as follows:
Authenticate user in-browser via firebase - can be either anonymous or full user
Do simple GET or POST to your cloud/firebase function with the required payload
In function validate the incoming request which will have authenticated user token
If validation is good then publish message into the topic
This way it's still secure, much more maintainable and clearly separated into functional components. Less code, a bit more infrastructure.

Resources