Search code examples
angularjsapireststatelessauth-token

Identifying non-logged in users in a stateless RESTful API


I'm developing a stateless RESTful API which will be consumed by an iOS app and an AngularJS browser app. In this API, auth tokens are required for any actions relating specifically to an authenticated user (adding new content, editing details etc).

Now, my application also requires non-authenticated users to be able to add items to their shopping carts. This is where I'm unsure. Since the application is stateless and therefore has no sessions - I'm not sure how to identify the user if they haven't already logged in and been given an access token.

One solution I'm considering is generating some other lower class of token that will identify this non-logged-in user. Then I can send this with every request to fetch and modify the cart.


Solution

  • The issue described here is not really that you need a token, but that you need a way to uniquely identify specific shopping carts.

    My assumption based on the question is that there is some generic /cart endpoint, that has a different content based on who's interacting with it. This design is a bit problematic (as you're seeing) as it might be better to just have a unique shopping cart uri per user.

    /cart/[some-unique-id]

    However, even in this scenario you might still want to use some form of authentication to identify that someone who's modifying the cart is still allowed to.

    If you're using OAuth2, the easiest would be to just create a new grant type. OAuth2 is extensible, so you could definitely add some 'anonymous' grant type that doesn't require any info, but just provides a bearer token.

    In this case your server would always have to make sure that the token is valid, but also make sure that it still correctly disallows accessing the endpoints that require 'real authentication'.