Guide
Authentication
Credentials Provider Using NextAuth.js

Credentials Provider Using NextAuth.js

The Credentials Provider in NextAuth.js allows you to authenticate users using custom credentials, such as email and password, without relying on external authentication providers. This is useful for scenarios where you want to handle authentication locally, such as for admin accounts or internal users.

Configuration

The context/auth.ts file in your AMRO Next.js 14 admin template project contains the configuration for the Credentials Provider using NextAuth.js. Here's an overview of the configuration:

  • Secret: A secret used for encrypting cookies and tokens. It should be kept secure and unique.
  • Session Configuration: Configures session management, enabling JSON Web Token (JWT) for sessions.
  • Providers: Specifies the authentication providers. In this case, the Credentials Provider is used with custom email and password fields.
  • Authorize Function: Defines the custom authentication logic. It verifies the provided credentials and returns user information if authentication is successful.

Example Authentication Logic

In the provided example, the authentication logic verifies the email and password against hardcoded values. If the credentials match, it returns user information including an ID, email, name, role, and image. Otherwise, it returns null.

Callbacks

Callbacks are used to customize the authentication flow and handle session-related tasks. The authorized callback restricts access to certain pages based on the user's authentication status. The jwt and session callbacks add the user's role to the JWT token and session data, respectively.

Default Sign-In Page

The pages configuration specifies the default sign-in page URL, which redirects users to the login page (/login) when authentication is required.

Conclusion

With the Credentials Provider in NextAuth.js, you can implement custom authentication logic for your AMRO admin template project, providing a secure and efficient way to authenticate users using email and password credentials. By configuring and customizing the authentication flow according to your requirements, you can ensure seamless user authentication and access control within your admin template application.