Verify that a user can only query his own data/information - database

o/
I'm working on a smaller app, and its going pretty well so far. I talked with a friend about it and he suddenly made me realize something. How do i make sure a user is only able to query his own data from a Database in the cloud?
Its a very simple app, where you can create a user and make some personal shopping lists.
I thought about a couple of options, but I'm not sure what is the right direction to take - or even if any of them is the right one.
The username/id & password is stored locally and appended to the request, and checked against the DB every time.
A token is generated, saved both in the DB & stored locally as a "active" session, and every time a request is send, the token is appended to the request and checked.
...?
I'm sorry if i placed this topic have the wrong tags, since i was not 100% sure where they should be placed.

Well, from your description it seams that you are working on a "no backend" app. If it is the case I suggest you to take a look to Firebase since it will solve all your concerns about authentication and user authorization.
If your would like to use a more custom approach, simply consider that appending the username and a passowrd to a request is always not recommended and since you are using a token is also unnecessary.
Now, returning to the question, i will give you my vision related to contexts where an authentication token is used and thus a backend is needed:
when you log-in a user, you produce a token that is function of the user id
each user request must contain that token
the backend can extract the id of the user that submitted the request from the appended token
a policy or a specific condition will check that data that is going to be retrieved must belong to the user whose id has been extracted.
Hope this could help you

Related

User Roles / Permissions on Frontend - React / GraphQL / Apollo Client

Recently started working with React / Apollo Client / Auth0 / Hasura and have some questions on handling frontend permissions. I'm using Auth0 to handle my authorization on whether a user is logged in and have my backend setup to check as well when handling mutations / queries. My question is now how to handle it on the front end.
A user can create a team that will store the info in my "teams" table and also create a record in my "team_staff" table as either a manager or coach. That was all straight forward. What I'm looking to do now is when a user visits, for example: www.mysite.com/team/update/1 to check if the user exists in the "team_staff" table and if not show them an error message or even a redirect. Also looking to hide certain buttons when viewing a team based on whether they are a staff member or not.
Should I handle this at the login and do a query for all the teams that user is a staff member on and store in a session / cookie or have a query / check inside that component each time it's called? Or am I way off and should do it another way?
Hopefully this question makes sense. Thanks!
This question makes sense, I believe many developers would have some similar problems.
TLDR;
Make API request in componentDidMount to get the right permissions (after signed in of course).
For this question, we have many solutions, and which is the best, depends on your infrastructure, your team and so on. Basically you need to call API to check the permission because your permission stored in the backend. Never store permission on the frontend storage like session, cookie, etc.
I can give some approaches.
First, call API right after signed in to get permission information, for example:
Get list of permitted routes, then, whenever user browse to a specific route, check to make sure that route in list of permitted routes.
Get list of permitted team like array of team ids, then in each route, get team id, check if that that team exist in above list.
But I'm sure you will realize they're almost the same, just different the data you get and how to process them. And two solutions totally depends on you.
All API request should be placed in componentDidMount of page component, because you will want to make sure the permission should be applied correctly as soon as the backend has changes.
Happy coding!

React - several stored accounts in one client

I'm looking for some information about a problem that I never thought about, and that I can't find much on the internet (or I'm looking wrong).
Here it is, for a dashboard project in my company, I need to be able to set up a system to store one account per client, or I just have to click on the account in question to connect, like twitter, google or instagram for example.
After the person has added his account, it appears in a list that can switch whenever he wants. Only I don't really see how to set this up, storing the login information in the localStorage? or the jwt token? I confess that I can't find a correct and secure solution as it should be, that's why I'd like to know if some people would have already done that, or if I can be oriented on an interesting solution?
Thanks a lot!
(Sorry for my english, i'm french and it's not perfect ^^)
Do not use localStorage. LocalStorage is not secure at all and can easily be hijacked through any js code running. If you need to store sensitive information, you should always use a server side session.
When a user logs into your website, create a session identifier for them and store it in a cryptographically signed cookie. If you're using a web framework, look up “how to create a user session using cookies” and follow that guide.
Make sure that whatever cookie library your web framework uses is setting the httpOnly cookie flag. This flag makes it impossible for a browser to read any cookies, which is required in order to safely use server-side sessions with cookies. Read Jeff Atwood's article for more information. He's the man.
Make sure that your cookie library also sets the SameSite=strict cookie flag (to prevent CSRF attacks), as well as the secure=true flag (to ensure cookies can only be set over an encrypted connection).
Each time a user makes a request to your site, use their session ID (extracted from the cookie they send to you) to retrieve their account details from either a database or a cache (depending on how large your website is)
Once you have the user's account info pulled up and verified, feel free to pull any associated sensitive data along with it

Does authentication differ at all when creating an app with angular?

In a regular web app, when someone logs into the system they simply save an encrypted cookie that gets send on each request and the backend decrypts the cookie and uses the e.g. user_id/guid to lookup the user.
How do things differ when authenticating with a angular app?
Is there anything else to consider or it is basically the same process?
We use more or less the same mechanism.
Access to the application as a whole requires authentication - that is unless you're logged in, you don't get any of the javascript experience at all. This could make the login / login failure much less wizzy for the user, but in our authentication provider it's fine.
Part of our auth mechanism means the list of roles that the user has is a data object available within the browser. The javascript code uses this to decide which buttons / menus etc. are displayed. I checked with our security guy and he said something like "Well, it's a kind of direct object reference issue, but as long as each action is authorised properly, you're probably ok." So it's possible that a user could hack data values and change what they can see, but because of the next bit, they can't break our data (or see stuff that they shouldn't).
Each service call our javascript makes is authenticated and authorised. That is, the javascript call will fail if the auth token is missing or bad, but also, we internally match the auth token with a user and a set of permissions, and only execute that if the user is authorised to do so. (Note that this is good practice whether you're using Angular or not). Also note that this applies to GETs as well as POSTs - we don't want to give them data they should not see.
It gets much trickier if your API is hosted separately from your Angular site.

What is the best approach to work with data while using token based authentication

I am building an sample application that lets user store comments.
I've created the registration and login process. When the user registers, his details are stored in a MySQL database and a token is returned to the browser. Now he can access the Profile page.
When an existing user logs in he is redirected to the profile page. The profile page is accessible only when a user registers or logs in.
After logging in, I want to show all his comments if he has already added them.
My frontend is in Angular and backend use Laravel. For authentication I use Satellizer.
I want to know, what is the best approach while playing with data, considering the fact that the user will add, edit his comments. Should I use localstorage and store data in a key value pair or should I create a json file which gets updated everytime the user adds a comment or makes a change.
I wanted to know what is the most efficient way to deal with data from server so that the application is fast even when it scales to a 10000 users and lot of data for each user.
Thanks
You should be updating it on the server when changes are made rather than only relying on localstorage. You can use localstorage to cache, but it should only be for immutable data, it shouldn't really be used for data that is going to change.
So in this case you'll be adding and updating new comments via your API (ideally a RESTful one!). Once you've made a change, you could store the comments locally and only update them when the user makes a new comment, however you'll quickly run into issues where the data is invalid on different clients. (i.e. if you update the comments on a different computer, the other computer won't be aware).
Alternatively, you could cache the comments and then simply ping the server to find out if new comments have been added. This could be using a HEAD request for example to check the last modified date on your comments resource.
You can store comments data locally on user browser, but you should properly manage it.
I don't how much load your server will have and if the time invested now worths it.
You can fetch comments and store them locally
User adds a comment, then you update locally and send a request to the server
You need to track the request response, if requests fail so notify user and remove comments from local.
if request was successful so you can continue on your way.
** facebook uses this "success first" approach
user does an action, and he see it happens instantly, in the background it could take few seconds, only if it fails they will notify you.
** look at their commenting process, when you comment, it appears instantly, no loading... but in the BG the load happens.

Securing Angular Application

I am creating an Angular application, and I am having trouble wrapping my head around the proper way to ensure my application and its users is secure.
I've been reading around many stack discussions, but I believe I am missing some core understanding of what is happening, please correct any errors you see written below.
So far I have a Sinatra server with many (currently mostly hypothetical) resource routes. A user can create an account using an email address and password that is stored in a database after being hashed with BCrypt. When a user logs in, the record is retrieved from the database by email and the password checked for authentication. It is from this point I am not sure how to proceed.
Prior to this I have simply set a session variable and had the server check that the variable exists in order to correctly route logged in users. Now my application is (currently) a single HTML page that uses Angular and ui-router to display different content, so most of the requests are simply returning JSON content.
It is my understanding that Restful applications should generally not use sessions, or rather that the server should respond identically to identical requests and not have its own data that shapes a response. But if I do not store something in a session variable, how could the server know that the client making the request has the correct permissions? And are sessions not stored in the browser anyway, thus not part of the server?
I believe from what I have read, it is possible to create a token which is essentially a large random string, return that string to the client and also store it in a database with a timestamp. The client then provides this token when making requests and the server hits the database to verify it exists and valid. But would the client not also have to store that string in a cookie? I suppose the angular application could store the token in a variable, which would persist while using the ui-router but not if the users navigates using the address bar.
I also do not understand how Basic Auth may or may not fit into this picture. Any help would be greatly appreciated, as well as a pointer to some good resources where I may find a better understanding of these concepts in general.
You want to read up on JWT. There are JWT libraries for Ruby and Angular.
I know you aren't using Node for your backend but a very easy way to see all the pieces working together is to run the angular-fullstack Yeoman generator. It uses JWT and the code is easy to follow.
As far as I can see, whatever you are doing with your sessions can work just fine.
This can be a sample JSON response from the server in case the user is not loged in :
{
"errorCode": 1,
"error": "User not logged in",
"data": {}
}
You can set your own error codes and handle what you want to do. You will send any data only if the user is logged in. For all the pages which don't require authentication, you can set data to whatever you want.
On the angularJS side, you can handle based on error codes, you can redirect the user to the login page and so forth.
The alternate way to support the same on multiple platforms is to use token based approach. The token based approach in simple words work this way.
The user logs in for the first time with his / her credentials.
The server verifies these information and creates a token from which the server is able to decode the user id.
Whenever the client makes the requests, it passes its token with every request.
As the server can decode the user information from the token, it sends or doesn't send the data based on whether that's a right token or not.
The token depends on a secret value. It can be same for all the users or differnet for each based on how you want to implement.
This is all done and you can look at
http://jwt.io/
As #andy-gaskell mentioned, you can look at
http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/
I'm very bad at explaining. Please let me know if any of this doesn't make sense.
you are missing the point of the REST concept. One of the main concepts in the REST apis is that the server should be stateless - this means that you should not store sessions or other "state" in your web server. Every HTTP request happens in complete isolation. Every request should include all data needed by the server to fulfill the request.
But if I do not store something in a session variable, how could the
server know that the client making the request has the correct
permissions?
You can store request scoped variables. This means that they should be only active during the same request. You can store the current logged in user in the request scoped variable. In that way you can get the current user in your invocation of the business method. I'm not familiar with Sinatra but here is the doc: http://www.sinatrarb.com/intro.html#Request/Instance%20Scope
But would the client not also have to store that string in a cookie?
of course you should store your access token in the client side
https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
as #Andy Gaskell suggest take a look at JWT and fullstack application code generators and forget about the basic auth because it's really "basic".
more useful links:
If REST applications are supposed to be stateless, how do you manage sessions?
http://www.sitepoint.com/php-authorization-jwt-json-web-tokens/

Resources