RESTful way of having a single resource based on authentication - api

I have an API that provides an Account resource based on the authentication (login) that is supplied. As a user can only have one account, and can only see it's own account and not those of others, this API will basically be a single resource API in all cases.
So to keep things simple, I have this resource under the url accounts/ and when you access accounts/?username=dude&password=veryhard you'll get your account data (if you dohn't supply authentication you'll get a 403).
Now I wonder if this is RESTful. Also, you should be able to update your account info, and I wonder if PUT would be appropriate. In my knowledge, PUT should be done on a unique URI for the resource. Well, is this a unique URI for the resource? Generally a URI for an account would look like accounts/3515/ where 3515 is the account id. However, users don't know their account id. Also, there should be more ways to log in, instead of a username + password you should also be able to use a token (like accounts/?token=d3r90jfhda139hg). So then we got 2 URL's that point to the same resource, which also isn't really beautiful for a RESTful URI, is it?
So, what would be the most RESTful solution? Or should I not do this RESTful?

REST purists will consider that use of /accounts/ to obtain a single account is bad practice as it should specify a collection. Instead consider a key which cannot be mistaken for an ID, for example if your IDs are UUIDs then use a token such as 'me' so your URL is /accounts/me. This has the advantage that if later on you wish to obtain different account information, say for example you need to list users or you have an administration system using the same API, then you can expand it easily.
Putting username and password in the URL is also not pure REST. The query parameters should be directly related to the resource you are obtaining; commonly filtering and limiting the resources returned. Instead you should seriously consider using something like HTTP Basic authentication over an encrypted (HTTPS) connection so that you separate out your authentication/authorisation and resource systems. If you prefer to use a token system then take a look at oauth or hawk.
Finally, yes if you use PUT you should supply a full resource identifier. Given that it is very common for systems to read data before updating it the lack of ID won't be a problem as that will come back as part of the prior GET.

Yes accounts/?username=dude&password=veryhard is a correct REST URL.
PUT is used with an id if it used to update a resource, if you use it to create you must supply an ID. otherwise you use post to create a resource without id

Related

Is it better to get ID from URL or JWT in an authenticated API

So I am creating some api's on Laravel using Passport (JWT).
I am having issues deciding what is the preferred method for the following:
PUT: api/users/{user_id}
PUT: api/users/me
I need the api so that the user can change his own information, but I would also like it for the api to be accessible for the Admin to change said information.
At the moment I am only using the first API and checking if the ID is the same as the one in the JWT auth or if the one requesting the api is the Admin.
But I was also thinking that maybe it was better to have them separate. The first api should only be accessible to the Admin, and I should be taking the ID from the JWT auth for the second api.
What would be the correct choice? Or is there a better choice?
I would say using this approach is better:
PUT: api/users/{user_id}
That allows anyone to consistently link to your own profile or to some other user profile in the same way. Then depending on your authentication and authorization, you can be allowed to do different operations on that resource.
There is no correct or better choice. You seem to understand the implications of using any of them so it's really up to you to choose. With the /{user_id} version you have to be extra careful not to remove proper validation rules from your code. If you used /users/me for a GET operation you would have to be careful with setting cache headers. If a browser would cache a response to users/me and then another user would request this endpoint, then you could get some other user's data. For PUT operations, though, this is not a concern.

REST API URI Design for sensitive resources

I have an application backed by RESTFul API. The application have user management section through which an admin user can manage other users. One sample URI for one of the API operation endpoint is below.
Update User : POST https://example.com/api/users/user1
Here user1 is the Username of the user being edited by the admin.
Suggestion from the security side is to remove the username from the URI since it is sensitive info and since it is part of url it will be recorded in network logs. Solution suggested is to pass the username data in POST Request Body .
Moving the data to request body is fine. But if I remove the username from URI ,the URI will be like "**POST https://example.com/api/users**" . This clearly doesn't look like a valid REST URI. And my USER entity doesn't have any other unique property which can be used in the URI.
Is there any recommended way to form a proper REST URI in such a scenario ?
POST /api/users
This clearly doesn't look like a valid REST URI.
Sure it does.
REST doesn't care what spelling you use for your resource identifiers, so long as the spelling is consistent with the production rules in RFC 3986.
That said, there's no particular reason that the identifier for a document needs to include sensitive information.
There are a couple of possible solutions - if the client and the server both know the sensitive data, then you can use a hashed value, rather than a raw value, as part of your identifier.
That's not ideal: we have mechanical ways of communicating URI that accept parameters, but no standard that I know of for communicating that some value should be hashed first.
If code-on-demand is an option, you might be able to manage to instruct the general purpose client to hash the data before sending it.
Otherwise, I think you are reduced to communicating the hashing out of band -- imagine a web form that instructs the human being to type in the hashed value of the sensitive information.
REST is optimized for the use cases that it was optimized for, and that means that some other use cases are more clumsy than we might like. Hooray for trade offs.
One way is to use an "id" instead of "username":
https://example.com/api/users/{id}
where "id" is usually a UUID https://en.wikipedia.org/wiki/Universally_unique_identifier

Ignore or not API endpoint parameters based on access level

I am working on an API endpoint that returns a list of products:
"api/products"
The endpoint accepts the following parameters:
page_size
page_number
Each product has a boolean property named IsApproved.
In the web application used by common users I always want to return only the Approved products ... On the web ADMIN application used by administrators I want to return all products, Approved or Not ...
My idea would be to add a new parameter (enumeration) named:
ApprovedStatus
And the values would be Approved, NotApproved and All.
On each API call I would check the user permissions ... If is admin I will consider the value on this parameter. If not then I will always return only approved products.
Another solution would be to have different endpoints ...
Any advice on which approach to take or is there other options?
The approval status is part of the product, therefore, in a perfect REST world, you don't want a different endpoint at all since you're accessing the same resource.
Then, for filtering a resource based on a property value, I think the convention is that if you specify that property as a query parameter it will only return those matching the value, and if not, it will return all of them, so I don't see the need to define a special ApprovedStatus parameter with some special values. Just query by isApproved!
Finally, about how to handle authorization. This, I think, should be handled at a completely separate layer**. If authorization is involved, you should have an explicit authorization layer that decides, for a specific resource and user, wether access is granted or not. This means the query would be triggered and if one of the resources generated by the query fails to be authorized for the user that triggered the query, it's taken out of the results. This accomplishes the behaviour you want without having any code that is checking specific users against specific query parameters, which is good because if tomorrow you have another endpoint that exposes this objects you won't have to implement the same authorization policy twice. Pundit is a perfect example on how to do this with Ruby elegantly.
**Of course, this approach retrieves data from the database unnecessarily which could matter to you, and also opens your endpoint up to timing attacks. Even then, I would consider tackling these problems premature optimizations and should be ignored unless you have a very good reason.
You're right about your ideas:
You can create a new endpoint just for admins, that will return all products
You can use a kind of authorization (e.g. Authorization Header) in order to check if the API is being called through admin or normal user. Then you can route internally to get all products or just IsApproved products.
You can add a proxy in front of your API to route to the right action, but it can also be achieved directly in the API but I think the second solution is easier.
Adding one more property is a bad idea.
In my opinion, adding another end point is very good. Because it will increase the protection in the admin end point.
Otherwise, since it is a web application, Simply set a cookie and a session to identify and separate the admin and user.
Going with the principle of least astonishment, I'd be in favour of adding a second endpoint for admin users. Such that you'll have:
GET /api/products (for regular users)
GET /api/admin/products (for admins)
This allows your code and API documentation to be nicely separated, and all of the admin-specific authentication details can live under the "admin" namespace.
The intention behind each API call is also clearer this way, which helps developers; and means that you can differentiate between admin vs regular usage in any usage stats that you track.
With ApprovedStatus, I think the specifics here don't matter much, but - considering what a developer using the API might reasonably expect / assume - it would be good to:
Ensure the ApprovalStatus parameter name matches the property name for "approval" that you return with each product object
Defaults to "approved" if it is not specified
Alert the user when an invalid value is specified, or one that they don't have access to
Bottom line: to answer your headline question - I think it's bad practice to ignore user input... sometimes. Design your API such that distinctions around when input can be passed in is very clear; and always alert the user if you receive input values that are technically acceptable, but not in the way that the user has requested, or for their access level. Ignoring values that are plain wrong (e.g. an argument that doesn't exist) is another story, and can be useful for future proofing or backwards compatibility.

Receiving data using GET with a RESTful API

I'm building an API. When requesting the data of a user this is shown to be the best practice to retrieve the data:
Requests user data with ID:
https://api.example.com/users/1
However it would be more convenient to requests user data with their email:
https://api.example.com/users/johnsmith#outlook.com
Is it safe to use the second method? Even if I was to use the first method, there is no way that a developer would know the ID for the user which they would like to request, so it would not be useful at all.
So is the second method safe? If not, is there a solution? Thanks.
As long as the ID is unique and parsable in the URI. The '#' would need to be encoded into a "%40". Other than that its fine, IMHO. If you have two different types of identifiers, like email and ID then you might want to allow a client to select which identifier to use
https://api.example.com/users?email=johnsmith#outlook.com
or
https://api.example.com/users?id=1
Here is some good literature for how to use filters in REST API's.
Passing email address in URL is not a good idea as it is non-public information. If you really need to go with email address then go with POST call or you can use id which is completely safe if you are using proper authorization at API end.

RESTful HTTP: Showing different representations to two users on the same URI

I'm designing a hypermedia API, yes, a RESTful API, with the hypertext constraint.
Each user of the system will access the system using their own credentials, so every request we process is authenticated and authorized. Each user will typically have specific credentials so that they may have different permissione (e.g. none, read, read/write) on each collection.
We want the client to be primed with the one URI that it starts with, which would be perhaps an atom services document, or a hierarchy (draft atom hierarchy extensions) of atom collections.
My question is basically should users see different representations for the same URI, or should users be directed to different URIs based on their permissions?
For example: User A and User B have different permissions in the system. They log in with different credentials, to the same start URI. A successful response may be one of the following 2:
200 OK, and User A sees something different than user B on the same URI
302 (or other redirect) each user to e.g. /endpoint/userA (which they own)
The tradeoff between cacheability is of course minimal, since resources are cached only by the client and not by intermediaries, but there's a tradeoff for visibility too (URI contains (aythenticated) user ID). Finally there's the future possibility of allowing User A (or a super user) to see what User B sees.
I'm not asking what Twitter or Facebook do, I'm more interested in what REST practicioners have to say about this.
My question is basically should users see different representations
for the same URI, or should users be directed to different URIs based
on their permissions?
For example: User A and User B have different permissions in the
system. They log in with different credentials, to the same start URI.
A successful response may be one of the following 2:
200 OK, and User A sees something different than user B on the same
URI
302 (or other redirect) each user to e.g. /endpoint/userA (which
they own)
Both ways are RESTful. The representation of a resource can depend on the permissions. The communication is stateless because you send the credentials (username, password) with http auth by every request. Redirection to another representation variant after permission check is a great idea. That way you can completely separate the authorization logic from the resource representation logic, so you can move it even to another server and you can create very well cacheable resource representations. For example by GET /endpoint/userA you can redirect userA to /endpoint/userA?owner=true, because she is the owner of the profile, or you can create a composition of features: /endpoint/userA?feature1=true&feature2=false etc... It is very easy to setup fine grained access control for that. Another way to stay cacheable if you append the user id to every request's queryString, but this solution with redirection is much cleaner. Thank you for that!
Personally I find this a really tough call to make and I think it depends a lot how much content would change. If the difference is the omission of a few extra details then I would probably treat it as a single resource that varies based on the user.
However, once the differences start to get more significant then I would look at creating different resources. I would still try and avoid creating resources that are specific to a particular user. Maybe for a particular resource you could create a set of subresources, with differing levels of content. e.g.
/Customer/123?accesslevel=low
/Customer/123?accesslevel=medium
/Customer/123?accesslevel=high
This method in combination with the 302 may be sufficient in some cases. For more complex cases you could use multiple query string parameters.
/Employee/123?SocialSecurityNo=yes&SalaryInfo=yes
I do not believe there is an easy answer to this question. I think the answer is similar to most tricky REST scenarios: your solution can be as creative as you want as long as you don't violate the constraints :-)
Option 1, replying with 200 is an acceptable REST response and is more user friendly than option 2.
The Google Data APIs provide a decent REST implementation on top of their user services, and they implement option 1. For example the Google Calendar Data API allows a user to query the person's own feed by performing a HTTP GET request on http://www.google.com/calendar/feeds/default/private/full.