Secure authentication / authorization in a single-page application

I create the following:

  • One-page JavaScript application;
  • A Node.js backend, which provides a RESTful API that will store user data;

User credentials (email / password) can be created using the single page application and stored in the backend. There is no need to interact with external providers, such as Facebook Login , but this may be needed in the future.

A single-page application should interact with the backend through its RESTful API as soon as the user is authenticated using his credentials.


I'm trying to figure out how to set up authentication and authorization of users based on credentials so that they are safe and compatible with the limitations of a single page application.

I found information about OAuth 2.0 and JSON Web Tokens . I can’t imagine how I should use these technologies to achieve my ultimate goal, regardless of whether they should work together or independently, and I try my best to realize the pitfalls that come with each.


Could you do the steps and components necessary to create a successful authentication / authorization mechanism for a single page application with a custom backend, if possible, also covering the following topics:

  • Advantages / disadvantages of using OAuth 2.0 compared to JWT or other methods;
  • Using cookies, in contrast to storing tokens in different ways (for example, LocalStorage) and security implications;
+5
source share
1 answer

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

Keep in mind that OAuth2 manages authorization, not authentication. OAuth2 does not mind user authentication. To handle authentication, tou can take a look at OpenId Connect , a layer on top of Oauth2. OpenId Connect will send your application a signed id_token containing information about the user ID.

After authenticating the user with OpenId Connect, you can contact the OAuth server to get access_token (JWT or not). This token will be used to communicate with your API. Implicit grant flow is recommended for use in SPA.

For JWT, it is used for 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 to clients (e.g. guid). By value, your token is collapsible, and the contained data can be read by clients.

To use the component, I personally work with Keycloak from RedHat.

Hope this helps.

0
source

All Articles