Token authentication in SPA app - api

I started new project. It is small application (playground) to learn couple new concepts. I will create backend API using Ruby on Rails and Single Page Application using React. I stuck in Authentication. I would like to create custom Token-based Authorization/Authorization. I came to following auth flow:
User fill password/login and send to backed using Ajax and through secured HTTPS connection.
Backed checks if user exist in DB. If user exist backend create Token and save to Redis with user id.
Backend response with token to client app.
On client side I will save above token to local storage.
Before every request I will get token from locale storage and pass to request header.
On backend I will take token from header and check if exist in Redis db.
Is this flow correct? Should I decrypt token on client side or It is not necessary? This project is only playground but I would like to do It properly. Please give me some comments if above flow isn't good enough.

I think that you have the right approach. This link could give you more details about token-based authentication:
Implementing authentication with tokens for RESTful applications - https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/
Hope it helps you,
Thierry

Related

Need help regarding refresh token mechanims

I have a client facing React native application.
I'm using JWT for authentication with quickly expiring access tokens(10m) & long lasting refresh tokens (7d).
I have two servers, one for auth & one for fetching other things.
ex: server.com/auth, server.com/activities
My question is, how to have a good refresh mechanism here ?
Ex: If a user logs in after 2 days and queries an API through my app, how should I send him the new access token back (using his refresh token) - keeping in mind my auth server is at a separate location ?
The obvious solution I see here is to contact /auth from /activities, get the new tokens and send the new tokens in the header of the response, while on the client side keep checking for new tokens in the header & saving them if present.
Is there a better solution than this ? Is this even a good solution ?
An perhaps better option is to look at using the Backend For Frontend (a.k.a BFF) pattern to secure SPA applications.
See
Backend For Frontend Authentication Pattern with Auth0 and ASP.NET Core
The BFF Pattern (Backend for Frontend): An Introduction
Securing SPAs using the BFF Pattern (once and for all)
What I would do, and as far as I know is what most people do is to have your API (/activities) respond with 403 if the access token is expired. The frontend should catch these responses and then ask the authorization server for a new access token based on the refresh token you have. The AS will respond with a fresh access token, which the frontend can now use to send to the API. Usually this exchange will happen automatically and the frontend will eventually retry calling the API with the new access token.
If the refresh token happens to be expired, then the authorization server will respond with a 403, which is a signal to the frontend app that it should ask the user to log in again.

OAuth2 flow in full-stack NestJS application

Yet another OAuth2 question that isn't quite covered elsewhere.
I'm using NestJS backend, React frontend, Passport and my own DB for authentication. Trying to add an
OAuth2 identity provider (Google).
I configured my NestJS app as an OAuth Client. After logging in I'm receiving the callback at which point I have an access_token and the requested user details extracted from the payload of the id_token. This is encapsulated in a class extending PassportStrategy(Strategy, 'google') and an AuthGuard('google') and much of it is handled automatically. Code here.
At this point however, I need to maintain an authenticated session between backend (NestJS) and frontend (React). I suppose I need a JWT, but I'm wondering about the best approach:
Can I use a token provided by the IdP (e.g. id_token or access_token)? So that I don't have to worry about issuing tokens myself. I.e. the frontend receives the token (either from backend, or the IdP directly), sends it on every request, backend verifies it with the IdP on every request (verifyIdToken or getTokenInfo of google-auth-library).
One drawback here is the extra network request every time. I'm not sure if there's a need for that because the IdP is only used to identify the user, not for access to other resources. Another drawback is that I need to store a refresh token and handle when the token expires (get new one, update it on the frontend).
So alternatively, could I just issue a JWT myself and not worry about checking in with the IdP? Once the JWT expires I'd need to prompt the user to log in again. In this case, I wouldn't need to store the IdP tokens. But is this good practice? One issue I can think of is that I won't detect if the user revokes access in the IdP (until the JWT expires).
I ended up issuing my own JWT tokens and managing User sessions in my app, as described in this article: OAuth2 in NestJS for Social Login (Google, Facebook, Twitter, etc)
probably my solution would be helpful.
you could access complete source code of my app that implemented with react typescript (redux toolkit rtk Query) and nestjs included of google oauth2 flow with passport.js. resource

Authenticating a Vuejs frontend with an Express Backend

I am looking for some advice on implementing authentication when the client and the server live in separate projects.
The Server
This API was built as an Express Server. It has routes for CRUD operations with a MySQL database. It also has a user model that utilize bcrypt to encrypt passwords. There is no Frontend, in this project.
The Client
This is a Vue project made with the vue-cli and hits the above API to get the data to display.
The Issue
I need to add authentication. I was thinking I would do this with express-session, but I am a little confused with how exactly it works. All of the tutorials I have seen use express-session in combination with passport. This seems fine, but in all the examples passport forwards to a login page that lives on the server. This is usually written in handlebars or some other templating framework. I am not sure the best way of implementing since the login page lives in the client project.
How I thought it worked (Am I missing something?)
I was originally of the impression that for a new user express-session would create a token that I would save in the users table (maybe generated at login and stored temporarily). Once the user logs in with the correct password this token is passed to the client to be stored as a cookie. When the client wants access to restricted data, it would pass the token as a Authentication header to the server to get permission.
The Questions
Since my projects are separated is passport still useful for my use case?
Is it secure to create the session cookie on the server and send the token to the client as a response to the client's login POST?
Do I need to store the session token in the database?
Is there a better option?
In my project I have almost the same setup, and I ended up with JWT to generate an access token.
The cycle begins with the user sending his/her email and password to my login endpoint.
In this stage I hash the password using some secret string, fetch the user from database and check if authentication succeed.
After that I generate an access token with an expiring time set, and I expected this access token in all protected routes.
With this approach you can easily implements refresh token to exchange at time to time, saving the refresh token in your database.
This is very simple and Is good to you understand how the process of authentication is done.
jsonwebtoken

How to manage a JWT login procedure from Micronaut client to a REST API?

I am new to Micronaut and trying to develop a gateway that connects on the client side to a REST API. The API requires an authentication token which is obtained by first sending a POST requests with credentials in the body. The API is then responding with a valid token which needs to be refreshed from time to time. I am able to inject a bearer token in the headers to authenticate my requests but I do not understand whether I have to handle the whole authentification process myself or if the Micronaut framework can manage it on its own?
Thank you very much for your help.
You could create an HttpClientFilter to handle authentication, refresh and the header. You can find an example here which cover basic authentication.
Yours will be more complicated since you need to refresh etc.
Also doing this way, allow you to decouple your authentication code from your API.

Oauth2 Authentication with React Native

i am trying to add authentication to my app using OAuth2 & also secure the back-end so only logged in users can access it.
Im just trying to wrap my head around the process and some clarification would be great. To my understanding here is how i would do it.
User logs in with oauth2 provider in app.
App sends the returned code to the back-end.
back-end fetches access token and returns to the app to be saved.
now, for all secure requests. I send the accesstoken as a parameter to the back-end which checks if it is valid or not.
would this be the correct way of creating a secure dashboard type app with oauth2?
thankyou.
It's correct except that in step 2 you send the authorization code back to the OAuth2 provider - as part of an authorization code grant message.
Here's an example of the message workflow during a user session. For a mobile app the same OAuth messages are used:
https://authguidance.com/2018/01/18/desktop-app-technical-workflow/
If it helps there are some code samples of mine to demo this behaviour - it is tricky to implement though:
https://authguidance.com/home/code-samples-quickstart/