5
votes

I am building the following:

  • A JavaScript Single-Page Application;
  • A Node.js backend exposing a RESTful API, which will store user data;

Users credentials (email/password) can be created via the Single-Page Application and are stored in the backend. There is no need for interaction with external providers, such as Facebook Login, but it may be necessary in the future.

The Single-Page Application should interact with the backend via its RESTful API, once the user is authenticated using their credentials.


I'm struggling to understand how to set up user authentication and authorisation, based on credentials, in a way that is both secure and compatible with the constraints of a Single-Page Application.

I found information about OAuth 2.0 and JSON Web Tokens. I can't picture the way I should use these technologies to achieve my end goal, whether they are supposed to work together or independently, and I'm struggling to become aware of the pitfalls that come with each.


Could you provide a walk-through of the steps and components needed in order to build a successful authentication/authorisation mechanism for a Single-Page Application with a custom backend, if possible covering the following topics as well:

  • The benefits/drawbacks of using OAuth 2.0 compared to JWT or other methods;
  • Using cookies as opposed to storing tokens in different ways (e.g. LocalStorage) and security implications;
1

1 Answers

0
votes

You can use JWT without Oauth2 and Oauth2 without JWT or use them together.

Keep in mind that OAuth2 manage authorizations and not authentication. OAuth2 doesn't mind how to authenticate your user. To deal with authentication, tou can take a look at OpenId Connect, a layer on top of Oauth2. OpenId Connect will send to your application a signed id_token containing information about the user identity.

Once you've authenticated your user with OpenId Connect, you can contact you OAuth server to get an access_token (JWT or not). This token will be used to contact your API. For SPA application the Implicit Grant flow is recommended.

For JWT, it's used for the id_token (from OpenId Connect) and can be used for access_token (OAuth2). For access_token, your token can be by reference (recommended for SPA) or by value.

By reference your token is opaque for clients (guid for example). By value your token is parsable and contained data can be read by clients.

For component to use, I personally work with Keycloak from RedHat.

Hope it helps.