Representation of a User in REST - rest

I'm slowly beginning to unerstand REST and theres one thing thats confusing me .
I understand that most of the things in REST is a "resource" . So i was wondering what kind of a resource would we be referring to in the case of a user signup / login ?
Is it users ? Then does it mean that a POST on users would signup for a new user . If that is the case , then how do i authenticate a user ? a GET on users with an encoded password / username pair?
I'm really confused with this.
I may be COMPLETELY wrong in my understanding given that i'm just starting to understand REST.
Any help is appreciated !
Thanks!

It's a bit of an unusual but common problem for REST. Keep thinking about resources.
When you login you're asking the server to create a session for you to access certain resources. So in this case the resource to create would be a session. So perhaps the url would be /api/sessions and a POST to that url with a session object (which could just be an object consisting of a username or password and perhaps the UUID) would create a session. In true REST you'd probably point to a new session at /api/sessions/{UUID} but in reality (and for security purposes) you'd probably just register a session cookie.
That's my own personal approach to login forms if I were to implement them myself but I always tend to use Spring security for that job so this requirement never really takes much consideration.

I am working on something similar and this is the solution I have taken so far. Any suggestions welcome :)
I have users exclusively for singup and account modifications.
GET /users/{id} gets a user for the profile page for instance
PUT /users creates a new user with username and password. In reality this should send an email with a link to somewhere that confirms the signup with a GET method.
POST /users/{id} modifies the user (for example change password)
DELETE /users/{id}
For authentication I tend to think that the resource I request is the token or the authentication. I have tried to avoid the word "session" because it is supposed to be anti-RESTful, but if you are just creating the illusion of an actual server-side session for your clients, I guess it is fine.
PUT /authentication/ with usename/password returns Set-Cookie with the pair user_id / hashed value. Maybe it should be POST. Not sure
DELETE /authentication/{user_id} just deletes the cookie and the user is signed out. Maybe instead of user_id it should be a unique token_id.

Resources can be created, read, update and deleted using a restful approach, see e.g.:
https://cwiki.apache.org/S2PLUGINS/restful-crud-for-html-methods.html
So if you'd like to administrate you users this would be the restful approach to do so.
If you'd like to authenticate the users which you have in your administration dataset you need
to design or select a restful authentication mechanism see e.g.
http://de.slideshare.net/sullis/oauth-and-rest-web-services
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/
For a jumpstart on these issues you might want to check out dropwizard:
http://dropwizard.codahale.com/

A resource may have one URI or many
but One URI will have exactly one Resource
Therefore, When Authenticating a user, you are addressing a user who is already registered
While when registering, you are addressing the user (resource) which is yet to be registered.
All you need is a way to process it to your SERVER.
THIS is an example taken from SUGARCRM REST web services implementation.
REST is like http requests to your SERVER.
For eg, when implementing REST Web Services.
Every REST Request is going to same File say
www.your_domain.com/Rest.php?json={your_json_method:'method',params:'watever'}
Where in Json is the request you are sending as a parameters
Requesting to authenticate a user
{method:'SignUp', username:'abc', pass:'pass', confirm_pass:'pass'}
Requesting to register a user
{method:'Login', username:'abc', pass:'pass'}
by this way you can have as many params as you want
Remember JSON is not necessory to be used. you can use simple get params for your query

Related

REST resources for a login/registration form

I want to create REST login/registration URI in order to make a an existing user login or a new user to register. After a little search I found that most of such forms are designed using the following rules:
GET /login to get the login resource
POST /login to login and get back the user profile resource
GET /register to get the registration resource
POST /register to register and get back the new user profile resource
However, I think that this is not a 100% REST approach as one of the rules of REST is that resources should be nouns and not verbs (except from some special cases like a search api). What's the best solution for such a situation ?
There's no one right answer to this, so I'll attempt to give some ideas on a common ways to solve this.
Login
Login (aka Authentication) itself is typically handled in a non RESTful way, ourside, such as OAuth2. Should there really be a 'login' if HTTP is stateless? Every request should carry all the information to allow a server to authenticate the client. If you do want to really handle login as a RESTful endpoint, you could ask yourself: "What state am I changing? One way to answer this is that maybe you a creating a set of credentials". I'm assuming for now that you are looking for a best practice / common approach to this though, and not a very purist REST approach for this.
Current user information
Getting the current user is often handled via an endpoint such as /current-user or /whoami. Doing a GET request on this could either yield information about the user, or it could immediately redirect to a canonical user endpoint such as /users/1234. Executing a PUT request could again either update the user, or return a redirect to the actual user endpoint.
Registration
If you have a list of users on a resource like /users. It would kind of make sense to create a new user resource by doing a POST request on this collection.

Creating user record / profile for first time sign in

I use an authentication service Auth0 to allow users to log into my application. The application is a Q&A platform much like stackoverflow. I store a user profile on my server with information such as: 'about me', votes, preferences, etc.
When new user signs in i need to do 1 of 2 things:
For an existing user - retrieve the user profile from my api server
For a new user - create a new profile on the database
After the user signs in, Auth0(the authentication service) will send me some details(unique id, name and email) about the user but it does not indicate whether this is a new user(a sign up) or a existing user(a sign in).
This is not a complex problem but it would be good to understand best practice. I can think of 2 less than ideal ways to deal with this:
**Solution 1 - GET request **
Send a get request to api server passing the unique id
If a record is found return it
Else create new profile on db and return the new profile
This seems incorrect because the GET request should not be writing to the server.
**Solution 2 - One GET and a conditional POST request **
Send a get request to api server passing the unique id
The server checks the db and returns the profile or an error message
If the api server returns an error message send a post request to create a new profile
Else redirect to the home page
This seems inefficient because we need 2 requests to achieve a simple result.
Can anyone shed some light on what's best practice?
There's an extra option. You can use a rule in Auth0 to send a POST to the /users/create endpoint in your API server when it's the first time the user is logging in, assuming both the user database in Auth0 and in your app are up-to-date.
It would look something like this:
[...]
var loginCount = context.stats.loginsCount;
if (loginCount == 1) {
// send POST to your API and create the user
// most likely you'll want to await for response before moving on with the login flow
}
[...]
If, on the other hand, you're referring to proper API design and how to implement a find-or-create endpoint that's RESTful, maybe this answer is useful.
There seems to be a bit of disagreement on the best approach and some interesting subtleties as discussed in this post: REST Lazy Reference Create GET or POST?
Please read the entire post but I lean towards #Cormac Mulhall and #Blake Mitchell answers:
The client wants the current state of the resource from the server. It is not aware this might mean creating a resource and it does not care one jolt that this is the first time anyone has attempted to get this resource before, nor that the server has to create the resource on its end.
The following quote from The RESTful cookbook provided by #Blake Mitchell makes a subtle distinction which also supports Mulhall's view:
What are idempotent and/or safe methods?
Safe methods are HTTP methods that do not modify resources. For instance, using GET or HEAD on a resource URL, should NEVER change the resource. However, this is not completely true. It means: it won't change the resource representation. It is still possible, that safe methods do change things on a server or resource, but this should not reflect in a different representation.
Finally this key distinction is made in Section 9.1.1 of the HTTP specification:
Naturally, it is not possible to ensure that the server does not
generate side-effects as a result of performing a GET request; in
fact, some dynamic resources consider that a feature. The important
distinction here is that the user did not request the side-effects,
so therefore cannot be held accountable for them.
Going back to the initial question, the above seems to support Solution 1 which is to create the profile on the server if it does not already exist.

How to design URL to return data from the current user in a REST API?

I have a REST based service where a user can return a list of their own books (this is a private list).
The URL is currently ../api/users/{userId}/books
With each call they will also be supplying an authentication token supplied earlier.
My question(s) is:
Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.
Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?
Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?
Short answer
You could use me in the URL to refer to the current user. With this approach, you would have a URL as following: /users/me/books.
An answer for each question
Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.
You could consider doing something like this: /users/me/books. Where me refers to the current user. It's easier to understand than /users/books, which can be used to return all books from the users.
For some flexibility, besides /users/me/books, you could support /users/{userId}/books.
The URL /users/me can be used to return data from the current user. Many APIs, such as StackExchange, Facebook, Spotify and Google+ adopt this approach.
Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?
I don't think it will break any REST principles, but I think your resources will not be properly indetified. As I answered above, I would use /users/me/books and also support /users/{userId}/books.
Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?
When using the userId in the URL to request private information from a user, there's no harm in checking if the token belongs to the user with the userId included in the URL.
I dont think that removing userId would break any REST principles, because after all, /users and them /books, its a little bit openend to interpretation and REST says basically nothing about it, on the other way if you are going to stay with the id inside the request, you MUST check that the user id is the same as the connected user, anyways, for me the 1 is redundant because you already have that information, plus, every time you are going to make useless checks because anyways the authentified userId is the one that you are going to trust in all cases.
Best Regards
REST is resources oriented so in your point what is the resource user or book. My point of view it's book. And I think you can request this resources
/api/books?user={userid}
But this URL can not solve your permission issue so you have to do it in your code with token information you can get with a OAuth2 protocol or whatever.

How to develop authentication of REST queries correctly when REST client is browser

I am at start of develoment of web-application. Application should be RESTful.
I am new to REST. And now I can't understand how user login/logout need to be done correctly to meet REST restrictions.
I spent good time to understand REST and already read many articles and answers on StackOverflow. Also I understand basic principle of "stateless" and it's benefits. So please no links on Wikipedia and basic sources about REST.
About task:
I have list of books in database on server. User who has login/password may come to site, enter login/password and view page with these books. So before to answer with list of books server need to be sure that user has rights to do it.
List of books will requested by AJAX call from browser.
I am going to make server to handle URL /books . When server receives GET request to this URL - it should
1) authenticate this call;
2) if OK - answer with list of books in JSON format.
As I understand so far - correct way of authentication for REST server is to authenticate each separate call. Client should use Secret Access Key and Access Key ID to encrypt query parameters. And server will check for Access Key ID, retrieve Secret Access Key (that is shared secret) and validate query in this way.
So server doesn't handle sessions because it violates "stateless" restriction of REST.
Only way how I see it could be done without sessions - use some Secret Access Key and Access Key ID to encrypt query parameters. This is how usual REST clients do. But there is a big difference between "normal" REST client and browser REST client.
Normal REST client (lets say it is standalone application or PHP-application on server) stores their Secret Access Key in some secure way. Nobody can see it. But JS application stores it right in code. And anybody can open this JS code and find this key.
So my question is:
How to organize authentication between browser (REST client) and server that handles REST API without exposing Secret Key to anybody who can open source code.
Or maybe I overestimate issue of storing of Secret Access Key in code?
I just see big difference with classical "stateful" application:
If I am logged in to some site and out of computer at the moment - nobody can come to computer and find my password in any place in memory of browser.
But with storing Secret Access Key in code it is possible.
Try to use the Basic authentication which works with browser based application. But problem with it is that it will always throw a pop-up to the user. An alternative to it is that you use a custom login header to do the authentication of each REST request, for example
headers : { "Authorization" : "customAuth" }

FOSOAuthServerBundle Create Client

I'm currently trying to setup FOSOAuthServerBundle with my Symfony2 app.
Everything seems to be setup and functional, anyway I'm stuck after the installation.
What is the proper workflow with URLs to get the access_token ?
I tried /oauth/v2/auth, but sounds like I need to define a Client object first.
How to create/generate Client ? Clients are always supposed to be created manually ?
FOSOAuthServerBundle doc is great, but seems to skip all the usage workflow. Am I supposed to check the OAuth2 doc for this ?
Thanks !
In short, yes. You should be using the oAuth2 RFC to determine which workflow you want to use. In regards to client registration the RFC specifically states that the means through which a client registers is beyond the scope of the specification (https://www.rfc-editor.org/rfc/rfc6749#section-2).
With that being said I can give you some insight into how I did this. My application is a mobile phone application that connects to several services running on various servers. I'm also using the Resource Owner Password Credentials Grant.
The way I approached this was: when the application loads, the first thing it does is to check if it has an oAuth2 client id. If it doesn't, then it POSTS to a create client endpoint I've setted up with the meta-data I need. The endpoint validates the POST, creates the client and returns the client information. The application stores the client id and the process doesn't have to be repeated the next time.
Application loads;
Application checks for oAuth2 client id;
If there is one, the process ends;
If there isn't, it posts to http://www.example.com/client;
If we get a 200, store the oAuth2 client id.
I could have also created the oAuth2 client when the user created an account in the application, but I wanted to make the registration process as fast as possible. Creating the client would have added some extra waiting time to the process.
Check this: http://blog.logicexception.com/2012/04/securing-syfmony2-rest-service-wiith.html
It's quite simple to convert to Doctrine, whether you use it.
There's a command-line that does exactly what you need: create a Client!