Role based authentication in next-auth
Unanswered
European anchovy posted this in #help-forum
European anchovyOP
Hello, I'm using Nextjs (pages folder) & next-auth & TypeScript and Prisma ORM. I'm trying to do role based authentication with Session in my project. This process seems simple for client side.
1. I added
2. I brought the user role information by including session in the callback in AuthConfig in api folder
3. After retrieving the session information in the file, I made various operations by checking the user role
I have not had any problems up to this point. However, I need to do this control in the middleware as well. However, I have not come across many examples on this subject. I would be happy if you can share resources and sample projects that I can browse on this subject.
1. I added
role field to session model in Prisma2. I brought the user role information by including session in the callback in AuthConfig in api folder
3. After retrieving the session information in the file, I made various operations by checking the user role
I have not had any problems up to this point. However, I need to do this control in the middleware as well. However, I have not come across many examples on this subject. I would be happy if you can share resources and sample projects that I can browse on this subject.
11 Replies
decode your next auth token in the middleware
extract the role
do a check against the role
import { getToken } from 'next-auth/jwt';
const token = await getToken({
req,
cookieName: nextAuthCookieName,
secret: process.env.NEXTAUTH_SECRET,
});something like this
inspect the contents of the token
if you set up your next auth options correctly to add the role
it should be present in the token
i think you can omit cookie name if you didnt modify it
European anchovyOP
I'm not using JWT for auth. How can I do with session? I found this provided code in below at StackOverflow. Is it looks good usecase?
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized: ({ req, token }) => {
const path = req.nextUrl.pathname;
// Check if the middleware is processing the
// route which requires a specific role
if (path.startsWith("/admin")) {
return token?.role === "admin";
}
// By default return true only if the token is not null
// (this forces the users to be signed in to access the page)
return token !== null;
}
}
});
// Define paths for which the middleware will run
export const config = {
matcher: ["/profile/:path*", "/admin/:path*"]
};It works fine btw, I'm just trying to make sure this is the safe way