Laravel Passport + Provider authjs
社区authjslaravel-passport
Jericho1060
本节提供了一个关于如何配置 NuxtAuthHandler
以使用 Laravel Passport Oauth2 和 SSO 的示例。
您可以参考官方 Laravel 文档 以向 Passport 添加新客户端。
默认情况下,您可以简单地使用以下命令创建一个客户端
sh
php artisan passport:client
它会要求您选择一个
client ID
,以及- 一个
redirect URI
。
保留客户端 ID 以进行下一步,并将重定向 URI 设置为 http://localhost:3000/api/auth/callback/laravelpassport
(开发环境的默认值,根据您的环境进行修改,您可以添加多个以逗号分隔的 URI)。
2. 添加一个返回用户数据的 Laravel API 路由
接下来,创建一个返回给用户的路由。 在这里给出的示例中,我们将使用 /api/v1/me
。
该路由将返回您的用户数据字段。您必须返回一个键为 id
的字段。
3. 设置配置和提供程序
3.1. 将配置存储在您的 .env 文件中
您可以将以下变量添加到您的 .env 文件中
PASSPORT_BASE_URL
:您的 passport APP 的 URLPASSPORT_CLIENT_ID
:您在上一步中设置的客户端 IDPASSPORT_CLIENT_SECRET
:Laravel 在步骤 1 结束时为您生成的客户端密钥
bash
# .env
PASSPORT_BASE_URL=http://www.my_passport_app.test
PASSPORT_CLIENT_ID=123456789
PASSPORT_CLIENT_SECRET=123456789
3.2. 将您的配置添加到 runtimeConfig
然后将这些值添加到您的 runtimeConfig
ts
// ~/nuxt.config.ts
export default defineNuxtConfig({
// ...
modules: [
// ...
'@sidebase/nuxt-auth',
],
runtimeConfig: {
// ...
passport: {
baseUrl: process.env.PASSPORT_BASE_URL,
clientId: process.env.PASSPORT_CLIENT_ID,
clientSecret: process.env.PASSPORT_CLIENT_SECRET,
}
},
})
2.3. 创建 catch-all NuxtAuthHandler
并添加此自定义提供程序:
ts
// ~/server/api/auth/[...].ts
import { NuxtAuthHandler } from '#auth'
const { passport } = useRuntimeConfig() // get the values from the runtimeConfig
export default NuxtAuthHandler({
// ...
providers: [
{
id: 'laravelpassport', // ID is only used for the callback URL
name: 'Passport', // name is used for the login button
type: 'oauth', // connexion type
version: '2.0', // oauth version
authorization: {
url: `${passport.baseUrl}/oauth/authorize`, // this is the route created by passport by default to get the autorization code
params: {
scope: '*', // this is the wildcard for all scopes in laravel passport, you can specify scopes separated by a space
}
},
token: {
url: `${passport.baseUrl}/oauth/token`, // this is the default route created by passport to get and renew the tokens
},
clientId: passport.clientId, // the client Id
clientSecret: passport.clientSecret, // the client secret
userinfo: {
url: `${passport.baseUrl}/api/v1/me`, // this is a custom route that must return the current user that must be created in laravel
},
profile: (profile) => {
// map the session fields with you laravel fields
// profile is the user coming from the laravel app
// update the return with your own fields names
return {
id: profile.id,
name: profile.username,
email: profile.email,
image: profile.image,
}
},
idToken: false,
}
],
})
了解更多
您可以在问题 #149 中找到完整讨论。解决方案由 @Jericho1060 提供