简体   繁体   中英

REST API - How to implement user specific authorisation?

So I'm currently learning/building a REST API backend server for my web application using NodeJS, ExpressJS, and MySQL as the database. My question is in regards to the best way to implement authorisation to ensure User A does not access or edit the data belonging to another User. Please note that I understand there are a lot of examples for implementation of role based authorisation (ie user groups vs admin groups, etc) but this is not what I'm asking. Instead, how do I authorise a user against the data they are accessing?

It is possible that I'm overthinking this and this is not even necessary; that I should just check whether the data belongs to the user in every SQL query, but I thought I'd ask if there's a middleware or policy architecture that takes care of this, or maybe even authorise through caching.

The only solution I can think of is that every SQL query returns the the user id with the result, then I just create a service that checks every result if the id matches or not. If yes, then proceed. If not rollback the query and return unauthorised error. Is this ok?

I very much appreciate your advice, help, and if you can point me in the right direction.

Many thanks in advance.

Save the userId (or ownerId) in every table, and create a middleware where each db access method requires the userId as a parameter, for example:

readOne(id, userId) {
    // implements SELECT * FROM example WHERE id = id AND userId = userId
}

updateOne(id, data, userId) {
    // implements UPDATE example SET data = data WHERE id = id AND userId = userId
}
...

For security reasons, never send as a response "Requested data exist by you aren't the owner".

The simplest things usually work best. You wouldn't have to have a special service for checking authorization rights for every entity and you can do it at data access level eg. SELECT * FROM foo WHERE user_id =:currentUser or UPDATE foo SET foo = bar WHERE user_id =:currentUser

It also depends whether you want to notify the user about unallowed access via HTTP401 or not to reveal that such a resource even exists for different user HTTP404.

For HTTP401 the scenario would be:

const entity = loadFromDB(id);
if(entity.userId !== currentUserId) { 
  res.send(401); 
  return;
}

... update entity logic ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM