如何使用Next.js和'next-auth'在服务端回调中创建并确认会话?当调用“signIn”时,我们仅限于客户端钩子调用。使用扩展OAuth的自定义提供程序时,如何在服务器的回调块期间创建会话?假设我已经使用“http://localhost:3000/api/authentication/signin”访问配置的提供程序并重定向到我的SSO页面。
我能够创建一个自定义提供程序,SSO域在我的“pages/API/callback/custom”端点上执行重定向到回调GET。在这个调用过程中,我如何分配和创建会话后,我已经消化和获取我的令牌服务器到服务器。
所有的“登录”功能都是通过客户端钩子完成的。我不知道如何告诉'next-auth'会话存在,并且应该在服务器端端点可用。
封装会话提供程序:
//_app.tsx
<SessionProvider session={session} refetchInterval={5 * 60}>
<Provider store={reduxStore}>
<Component {...pageProps} />
</Provider>
</SessionProvider>
自定义提供者:
//CustomProvider.tsx
import { OAuthConfig, OAuthUserConfig } from "next-auth/providers"
export interface MyCustomProviderProfile extends Record<string, any> {
sub: string
nickname: string
email: string
picture: string
}
export interface MyCustomOAuthUserConfig<P> extends OAuthUserConfig<P> {
applicationId: string,
}
export default function MyCustomProvider<P extends MyCustomProviderProfile>(
options: MyCustomOAuthUserConfig<P>
): OAuthConfig<P> {
return {
id: `${options.id}`,
name: "Your Custom Account",
type: "oauth",
authorization:
{
url: `${options.authorization}`,
params: {
client_id: `${options.clientId}`,
app_id: `${options.applicationId}`,
},
},
checks: ["pkce", "state"],
idToken: true,
profile(profile) {
return {
id: profile.sub,
name: profile.nickname,
email: profile.email,
image: profile.picture,
}
},
style: {
logo: "/auth0.svg", //TODO: Replace with the correct graphic
logoDark: "/auth0-dark.svg",
bg: "#fff",
text: "#EB5424",
bgDark: "#EB5424",
textDark: "#fff",
},
options,
}
}
配置
//[...nextauth].tsx
export const authOptions: NextAuthOptions = {
providers: [
MyCustomProvider({
id: "custom",
applicationId: applicationIdentifier,
clientId: clientIdentifier,
clientSecret: 'your-client-secret',
issuer: 'https://your-issuer.com',
authorization: `${rootApiServer}/_AppAuth`,
}),
],
session: {
strategy: "jwt",
maxAge: 3000,
},
callbacks: {
async session({ session, token, user }) {
console.log('This was session called.');
return session
},
async jwt({ token, account, profile }) {
console.log('This was jwt called.');
return token
}
}
}
export default NextAuth(authOptions)
回调:
//pages/api/authentication/callback.tsx
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Make sure that we have the code to digest.
const code = req.query?.code as string;
if (code == null) {
res.status(401).json({ message: 'Not authorized' });
return;
}
//Exchange the SSO code for bearer token.
const tokenResponse = await exchangeCodeForToken(code, req);
if (tokenResponse == null) {
res.status(403).json({ message: 'Error authenticating user. Please try again.' });
return;
}
// Use the bearer token to get the user's scope.
const scopesResponse = await getUserScopes(tokenResponse.token);
if (scopesResponse == null) {
res.status(403).json({ message: 'There was an error determining the user\'s scope.' });
return;
}
}
1条答案
按热度按时间jk9hmnmh1#
原来我已经覆盖了API路径,并期望我需要创建回调作为OIDC的代码消化。
当提供程序正确实现时,由“next-auth”生成的回调将处理代码消化。