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
credentialsprovider.
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_tokento extract user information such as name, role, and tax ID.
import { jwtDecode } from "jwt-decode";
A
TypeScript typethat 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 Decodingand 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
- The user visits a protected page and is redirected to the identity provider.
- After authentication, they return to:
/oauth2-login?access_token=abc123&refresh_token=xyz456 - The page:
- Decodes the
refresh_token - Logs in the user via
signIn("credentials", ...) - Redirects them to the page they were on
- Decodes the
CustomJwtPayloadType
export interface CustomJwtPayload {
role: string;
first_name: string;
last_name: string;
afm: string;
[key: string]: any;
}
Requirements
- A credentials
providerset up inpages/api/auth/[...nextauth].ts. jwt-decodeinstalled:
npm install jwt-decode
or
yarn add jwt-decode
- The
identity providermust returnJWT tokenswith user data. - The
previousUrlmust be stored inlocalStoragebefore 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.
