Skip to main content

OAuth2Login

This document describes a ready-to-use UI component (OAuth2Login) used for logging in users via an OAuth2 provider. It includes details about its functionality, component API, and sample usage.

OAuth2Login Component (OAuth2 Login)

This component handles the login callback logic via OAuth2 in a Next.js application using NextAuth.js. It decodes the JWT token, logs in the user via the credentials provider, and redirects them back to the page they were visiting.

Full Component Code with Explanations

Retrieves parameters from the URL (e.g., access_token, refresh_token).

import { useRouter } from "next/router";

Used to sign the user in using NextAuth's credentials provider.

import { signIn } from "next-auth/react";

Executes the login logic when the component is mounted, using useEffect.

import { useEffect } from "react";

Displays a visual loading indicator during the login process.

import Loading from "@/components/Loading";

Decodes the JWT refresh_token to extract user information such as name, role, and tax ID.

import { jwtDecode } from "jwt-decode";

A TypeScript type that defines the structure of the decoded JWT payload.

import { CustomJwtPayload } from "@/types";

Main Component.

const OAuth2Login = () => {
const router = useRouter();

useEffect: Executes Once.

useEffect(() => {
const handleLogin = async () => {
const { access_token, refresh_token } = router.query;
const previousUrl = localStorage.getItem("previousUrl") || "/";

JWT Decoding and Login.

if (access_token && refresh_token) {
const decoded: CustomJwtPayload = jwtDecode(String(refresh_token));
const result = await signIn("credentials", {
redirect: false,
access_token,
refresh_token,
role: decoded.role,
first_name: decoded.first_name,
last_name: decoded.last_name,
afm: decoded.afm,
});
if (result?.error) {
console.error("Login error:", result.error);
} else {
window.location.href = previousUrl;
localStorage.removeItem("previousUrl");
}
}
};

handleLogin();
}, [router.query]);

Loading.

 return <Loading />;
};

Export.

export default OAuth2Login;

Example Flow

  1. The user visits a protected page and is redirected to the identity provider.
  2. After authentication, they return to: /oauth2-login?access_token=abc123&refresh_token=xyz456
  3. The page:
    • Decodes the refresh_token
    • Logs in the user via signIn("credentials", ...)
    • Redirects them to the page they were on

CustomJwtPayload Type

export interface CustomJwtPayload {
role: string;
first_name: string;
last_name: string;
afm: string;
[key: string]: any;
}

Requirements

  • A credentials provider set up in pages/api/auth/[...nextauth].ts.
  • jwt-decode installed:
npm install jwt-decode

or

yarn add jwt-decode
  • The identity provider must return JWT tokens with user data.
  • The previousUrl must be stored in localStorage before redirection.

Summary

This component completes the OAuth2 login cycle. It receives tokens from an external provider, decodes them, and logs in the user using NextAuth.

It acts as a silent bridge between the third-party identity provider and the frontend application.


We'd love your feedback
Was this helpful?