使用 Auth0 和 Next Auth 请求用户角色

问题描述 投票:0回答:1

我只是想知道,我需要在 Auth0 设置中添加什么,以便我可以使用 docs 中概述的受限路由:

import { withAuth } from "next-auth/middleware"

export default withAuth(
  // `withAuth` augments your `Request` with the user's token.
  function middleware(req) {
    console.log(req.nextauth.token)
  },
  {
    callbacks: {
      authorized: ({ token }) => token?.role === "admin",
    },
  }
)

export const config = { matcher: ["/admin"] }

我创建了一个 Auth0 帐户,创建了一个用户并为该用户分配了一个角色,但该角色没有显示在用户令牌中。

我找到了验证用户并使用 Auth0 请求标准声明的文档,这是我需要查看的地方吗?测试代码时

exports.onExecutePostLogin = async (event, api) => {

  if (event.authorization) {
    // Set claims 
    api.idToken.setCustomClaim("userData", JSON.stringify(event.user));
  }
};

但是,我在

userData
中没有看到任何角色,也许是因为测试用户没有分配给任何角色?

我还找到了请求用户角色的文档。将此请求放入中间件是否有意义,这样我就可以从端点请求用户的角色,而不是

authorized: ({ token }) => token?.role === "admin"

next.js middleware auth0 next-auth
1个回答
0
投票

好的,我想我明白了:

首先在 Auth0 中创建 Login / Post Login 操作:

exports.onExecutePostLogin = async (event, api) => {
  if (event.authorization) {
    api.idToken.setCustomClaim("https://example.com/roles", event.authorization.roles);
  }
};

然后配置您的身份验证路由

  providers: [
    Auth0Provider({
      clientId: process.env.AUTH0_CLIENT_ID,
      clientSecret: process.env.AUTH0_CLIENT_SECRET,
      issuer: process.env.AUTH0_ISSUER,
      profile(profile) {
        return {
          id: profile.sub,
          name: profile.nickname,
          email: profile.email,
          image: profile.picture,
          roles: profile["https://example.com/roles"]
        }
      },
    }),
  ],

我不知道这是否是最佳实践,而且我也不完全理解命名空间的作用(here有解释),但到目前为止这段代码似乎有效!

© www.soinside.com 2019 - 2024. All rights reserved.