跳到主内容

Next.js

nextjs-auth 仓库展示了在 Next.js 中集成 Casdoor 的方法。 以下步骤。

步骤1:部署Casdoor

生产模式. 确认登录页面正常工作(例如,在开发环境中访问http://localhost:8000,使用用户名admin和密码123)。

步骤2:添加中间件

middleware.ts(或 .js)放置在项目根目录下(与 pagesapp 同级,或位于 src 内部)。 中间件会在请求完成之前运行,并可重定向或修改响应。

示例:

const protectedRoutes = ["/profile"];

export default function middleware(req) {
if (protectedRoutes.includes(req.nextUrl.pathname)) {
return NextResponse.redirect(new URL("/login", req.url));
}
}

查看 Next.js middleware

步骤3:使用Casdoor SDK

安装

npm install casdoor-js-sdk # 或:yarn add casdoor-js-sdk

初始化

提供以下六个字符串参数:

参数必需描述
serverUrlCasdoor服务器URL(例如http://localhost:8000)。
clientId应用程序客户端 ID。
clientSecret应用程序客户端密钥。
organizationName组织名称。
appName应用名称。
重定向路径回调路径(例如:/callback)。

示例:

const sdkConfig = {
serverUrl: "https://door.casdoor.com",
clientId: "294b09fbc17f95daf2fe",
clientSecret: "dd8982f7046ccba1bbd7851d5c1ece4e52bf039d",
organizationName: "casbin",
appName: "app-vue-python-example",
redirectPath: "/callback",
};
注意事项

请用您自己的Casdoor实例替换:serverUrlclientIdclientSecret

<b请在应用程序的重定向 URL 中添加回调 URL(例如 http://localhost:8080/callback)。

重定向至登录并处理回调

const CasdoorSDK = new Sdk(sdkConfig);
CasdoorSDK.signin_redirect();

登录后,Casdoor会使用代码进行重定向返回。 兑换为令牌并可选择将用户存储在 Cookie 中:

CasdoorSDK.exchangeForAccessToken()
.then((res) => {
if (res && res.access_token) {
return CasdoorSDK.getUserInfo(res.access_token);
}
})
.then((res) => {
Cookies.set("casdoorUser", JSON.stringify(res));
});

请参阅如何使用Casdoor SDK.

第4步:在中间件中保护路由

在中间件中,将Casdoor用户Cookie的存在视为已认证,并将未认证用户重定向至受保护路由之外:

const protectedRoutes = ["/profile"];
const casdoorUserCookie = req.cookies.get("casdoorUser");
const isAuthenticated = !!casdoorUserCookie;

if (!isAuthenticated && protectedRoutes.includes(req.nextUrl.pathname)) {
return NextResponse.redirect(new URL("/login", req.url));
}