wimnat
wimnat

Reputation: 1148

What is the correct workflow for auth to a web site which uses a REST api

I have a web site written in Angular that uses a REST api in order to provide functionality.

I would like to know the proper workflow for authentication to the website.

Let's go back to 1999 - I write a website and all the logic is in the web code. There is no REST API. If someone wants to log in to the website they enter their email and password and I store a cookie on their machine and they now have a 'logged-in' session on my website. By having this cookie they are authorized to do certain things such as write a comment.

All good.

Fast-forward to my new website. This website is written in Angular and all content is provided via a REST API. Some of the REST calls just display data like a bunch of comments. Any anonymous user can make these calls just by browsing the page. However, there the user can log in to the website using their email and password. Again, I store a cookie on the user's machine and they are logged in to the website. Now, because they are logged in to the website they can post comments. These posts are done via a REST API call. However, Google and the Interweb have told me that my REST API should be stateless and i should be using oauth2 for this request.

My question is, what is the workflow for this very common auth pattern?

I thought maybe something like:

  1. User logs in with username and password
  2. One request is sent to my web auth server and a session cookie is created
  3. A second request is sent to my api auth server which issues a valid token for further requests

The two systems are quite separate and do not depend on each other.

If i was to add social login to the mix then (2) above would just be authentication to the required social auth server and (3) would be unchanged.

Upvotes: 0

Views: 764

Answers (1)

unicodeveloper
unicodeveloper

Reputation: 401

Yes, your REST API should be stateless.

This is a typical workflow for authentication for a REST API.

  1. User logs in with username and password.
  2. A JSON web token is issued upon login from the backend and sent to the browser.
  3. The JWT(JSON web token) can be stored in a cookie in the Web Storage(local/Session Storage) on the browser.
  4. Subsequent requests to the REST API will have the token embedded in the header or query string for authorization. With that form of authorization, your REST API understands who is making the request and what kind of resource to return based on the level of authorization

A practical example of this can be found in this blog post. Angular 2 was used for the sample app implementation.

I hope this helps!

Upvotes: 2

Related Questions