![](/img/trans.png)
[英]Nextauth deployed on AWS Amplify [next-auth][error][CLIENT_FETCH_ERROR]
[英]Add role based authentication using next-auth in NextJS
我正在使用CognitoProvider使用next-auth v4實現基於角色的身份驗證,我修改它以添加角色但角色屬性未在最終 session json 中傳遞
import NextAuth from "next-auth/next";
function CognitoProvider(options) {
return {
id: "cognito",
name: "Cognito",
type: "oauth",
wellKnown: `${options.issuer}/.well-known/openid-configuration`,
idToken: true,
profile(profile) {
console.log(profile);
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
role: profile["cognito:groups"],
};
},
options,
};
}
export default NextAuth({
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_DOAMIN,
}),
],
callbacks: {
session: (props) => {
console.log(props);
return props.session;
},
},
});
role: profile["cognito:groups"]
我已將用戶添加到管理員組並希望他訪問我的 NextJS 應用程序中的特定路由。
任何幫助,將不勝感激。
您需要配置jwt
和session
回調以在 session 中包含更多數據。
來自 Next-Auth 文檔:
如果你想讓你通過
jwt()
session()
添加到令牌 […]
添加用戶的角色:
export default NextAuth({
// ...
callbacks: {
jwt({ token, account, profile }) {
if (account) {
// modify token
token.role = profile.role;
}
},
session({ session, token }) {
// Send properties to the client
if (session.user) {
// modify session
session.user.roles = token.role;
}
return session;
},
},
});
然后在您的路線中,您將從session session.user.role
獲得用戶的角色
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.