最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

authentication - Role not Populating in Next-Auth JWT Token for Middleware Role-Based Access - Stack Overflow

programmeradmin0浏览0评论

I'm implementing role-based access control in a Next.js app using Drizzle ORM, Supabase (Postgres), and Auth.js. My middleware isn't receiving the user's role from the JWT token (request.auth.user.role is undefined). I'm using google as an Oauth provider

Setup:

  • Auth Config: Extended User and Session interfaces to include role.
  • Auth.ts: Configured DrizzleAdapter, JWT, and session callbacks to propagate role from the user to the token and session.
  • Middleware.ts: Uses auth() middleware to redirect based on role.

Issue: The JWT callback's token.role and session data aren't populated with the user's role. In middleware, request.auth?.user?.role logs as undefined, despite assigning it in callbacks. The JWT token shows role is missing.

Code Snippets:

  1. JWT Callback:
callbacks: {
  async jwt({ token, user }) {
    if (user) {
      token.role = user.role; // Here it's ok
      token.id = user.id;
    }
    return token;
  },
  async session({ session, token }) {
    session.user.role = token.role; // Propagates to session
    return session;
  }
}
  1. Middleware Logic:
const role = request.auth?.user?.role; // 
发布评论

评论列表(0)

  1. 暂无评论