NextAuth自定义Provider实现:如何获取wellKnown URL?
关于NextAuth.js自定义Provider的疑问
我已经按照NextAuth.js文档,用官方GithubProvider实现了登录,步骤是在pages/auth/[...nextauth].js里配置GithubProvider的clientId和clientSecret,并用SessionProvider包裹应用。现在想尝试用Custom Provider,但不清楚具体实现方法。
根据文档,如果提供商支持OpenID Connect且/.well-known/openid-configuration端点支持authorization_code授权类型,只需要传入该配置文件URL并定义基础字段。但我不理解示例中的wellKnown字段,比如wellKnown: "https://accounts.google.com/.well-known/openid-configuration",是不是把地址改成Github的就能用于自定义Github登录?我改了代码但不确定正确的wellKnown URL,想请教怎么获取Github或其他自定义Provider的wellKnown URL?
我的尝试代码如下:
import NextAuth from "next-auth"; export const authOptions = { providers: [ { id: "github", name: "Github", type: "oauth", wellKnown: "https://accounts.google.com/.well-known/openid-configuration", // 应改为Github的对应地址? authorization: { params: { scope: "openid email profile" } }, idToken: true, checks: ["pkce", "state"], profile(profile) { return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, }; }, }, ], }; export default NextAuth(authOptions);
解答
1. Github的OpenID Connect配置地址
Github的well-known配置URL是:https://github.com/.well-known/openid-configuration,直接替换代码里的Google地址即可。
2. 获取任意Provider的wellKnown URL的方法
- 遵循OpenID Connect规范的服务商,通常会把配置文件放在域名根目录下的
/.well-known/openid-configuration路径,直接拼接域名+该路径尝试访问即可,返回JSON格式配置文件则说明地址正确。 - 若不确定,直接查看服务商官方文档,搜索“OpenID Connect discovery endpoint”或“well-known configuration”,官方一般会明确给出地址。
3. 自定义Github Provider的关键补充
替换wellKnown地址后,还需要注意以下两点:
- 必须补充
clientId和clientSecret字段(和使用官方GithubProvider时的参数一致),当前代码中遗漏了这两个必填项,修正后的代码片段:
{ id: "github", name: "Github", type: "oauth", wellKnown: "https://github.com/.well-known/openid-configuration", clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, authorization: { params: { scope: "openid email profile" } }, idToken: true, checks: ["pkce", "state"], profile(profile) { return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, }; }, }
- 确保Github开发者后台已配置正确的回调地址,且应用权限包含
openid email profile对应的访问权限。
内容的提问来源于stack exchange,提问作者FD3
相关产品推荐
相关产品推荐

