I am building a website that will use chrome extension for some of its feature, I am using Next Auth and would like to authenticate from my extension whether or not the user is logged in/ has the next auth token.
I am currently getting the token from the cookies of my website “localhost” for now. And then sending it to content.js for whatever reason. and then sending the request to the next js backend with the token in the authorization header
// This is the content script
async function run() {
const response = await chrome.runtime.sendMessage({ type: "REQ_COOKIE" })
const cookies = response.cookies as chrome.cookies.Cookie[]
console.log(cookies)
if (response.cookies.length > 0) {
const authCookie = cookies.find(
(cookie) => == "__Secure-next-auth.session-token"
).value
console.log(authCookie)
const tokenString = `Bearer ${authCookie}`
fetch("http://localhost:3000/api/auth", {
headers: { Authorization: tokenString }
})
}
}
run()cookie.name
I currently have this going on my backend, with which all the origin can make request to this endpoint
// This is the backend
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { env } from "@/env";
import { cookies } from "next/headers";
export async function OPTIONS(req: NextRequest) {
return new NextResponse("", {
headers: {
"Access-Control-Allow-Origin": "*", // replace "*" with your actual origin
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Authorization",
},
});
}
export async function GET(req: NextRequest) {
console.log(req.headers.get("Authorization"));
const token = await getToken({ req, secret: env.NEXTAUTH_SECRET });
if (token) {
console.log(token);
return new NextResponse("Successfull yay", {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Authorization",
},
});
} else {
return new Response("Not verified", {
status: 401,
statusText: "Unauthorized",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Authorization",
},
});
}
}
Is there a way for me to make it so that, only the request from the background script of chrome extension is allowed.