How to use DotNet Core 5.0 authentication with Next.js

Viewed 1876

I have a Next.js website I'm working on and a dotnet core API connected to a SQL Server database. I have a login page and intend to create a page to add new users and was wondering how I could do this using dotnet core identity? I added the NextAuth.js package thinking I could utilize it, however it seems to work best if connecting directly to the database and not go through an API.

I managed to return the token to NextAuth.js but I don't know where to go from there. How can I use next-auth to manage the session? Or is there a better way to go about doing this without using NextAuth.js?

My reason for using dotnet core identity is because it already has support for roles and setup is fairly simple and makes authorizing different sections of the API easy. Based on a user's role, they should be authorized to access certain routes or view certain pages.

I tried looking at the following doc from microsoft Intro to auth for SPA, but it's not exactly clear to me how I can manage the session.

1 Answers

First, generally, when we using JWT authentication, the workflow as below:

  1. Client sends a request (which contains the user information, such as: name and password) to server for token
  2. Server receives the user information and checking for authorization. If validated success, server generates a JWT token.
  3. Client receives the token and stores it somewhere locally.
  4. Client sends the token in the future requests.
  5. Server gets the token from request header, computes Hash again by using a) Header from token b) payload from token c) secret key which server already has.
  6. If ("newly computed hash" = "hash came in token"), token is valid otherwise it is tempered or not valid

After configure your application uses Identity and JWT authentication. When a User login, you could send the user information to the server side and check if the current user is valid or not, then generate a JWT token, and on the client side you could store the token in the web storage. After that, when you want to access the resource by passing this token into the authentication HTTP header. More detail information, please refer to the following article: JWT Authentication In ASP.NET Core

Related