how to secure my api's?
Answered
Waterman posted this in #help-forum
WatermanOP
In a video I have been watching a little bit, this was his setup (almost)
and I basically have a lot of different sort of routes that looks like this, both get, put, post etc
but is there a go to method of doing this? because as you can see i am using next auth and I have therefore access to the session, how can i easily restrict these api ,or what every they are called, so that no other than the logged in user can do the request...
I appreciate all help 🙂
const session = await getServerSession(req, res, authOptions);
if (!process.env.EMAILS?.includes(session?.user?.email)) {
throw "Not Admin";
}
and I basically have a lot of different sort of routes that looks like this, both get, put, post etc
export const PUT = async (req: NextRequest, res: Response) => {
const body: kropp = await req.json();
const {
namn,
fulltNamn,
beskrivning,
his
**More Code...**
but is there a go to method of doing this? because as you can see i am using next auth and I have therefore access to the session, how can i easily restrict these api ,or what every they are called, so that no other than the logged in user can do the request...
I appreciate all help 🙂
Answered by Waterman
I now tried this:
It seems to be working
const session = await getServerSession(authOptions);
if (!session) {
throw "Not Admin";
}
It seems to be working
3 Replies
WatermanOP
I also tried
but I got: Error: React Context is unavailable in Server Components
const { data: session, status } = useSession();
if (status === "unauthenticated") {
throw "Not Admin";
}
but I got: Error: React Context is unavailable in Server Components
WatermanOP
I also tried :
but then I just got "not Admin" all the time even when signed in
const token = await getToken({ req });
if (token) {
// Signed in
console.log("JSON Web Token", JSON.stringify(token, null, 2));
} else {
// Not Signed in
throw "Not Admin";
}
but then I just got "not Admin" all the time even when signed in
WatermanOP
I now tried this:
It seems to be working
const session = await getServerSession(authOptions);
if (!session) {
throw "Not Admin";
}
It seems to be working
Answer