秘诀示例:使用 JWT 的身份验证流程
¥Examples cookbook: Authentication flow with JWT
此页面是后端定制示例手册的一部分。请确保你已阅读其 introduction。
¥This page is part of the back end customization examples cookbook. Please ensure you've read its introduction.
💭 上下文:
¥💭 Context:
开箱即用,FoodAdvisor 的前端网站不提供任何登录功能。通过访问位于 localhost:1337/admin
的 Strapi 管理面板来完成登录。
¥Out of the box, the front-end website of FoodAdvisor does not provide any log in functionality. Logging in is done by accessing Strapi's admin panel at localhost:1337/admin
.
让我们向 FoodAdvisor 的 /client
文件夹中包含的由 Next.js 驱动的前端网站添加一个基本登录页面。登录页面可在 localhost:3000/auth/login
访问,并包含典型的电子邮件/密码登录表单。这将允许以编程方式验证发送到 Strapi 的 API 请求。
¥Let's add a basic login page to the front-end, Next.js-powered website included in the /client
folder of FoodAdvisor. The login page will be accessible at localhost:3000/auth/login
and contain a typical email/password login form. This will allow programmatically authenticating API requests sent to Strapi.
🎯 目标:
¥🎯 Goal:
创建前端组件以:
¥Create a front-end component to:
-
显示登录表单,
¥to display a login form,
-
向 Strapi 后端服务器的
/auth/local
路由发送请求进行身份验证,¥send a request to the
/auth/local
route of the Strapi back-end server to authenticate, -
获取 JSON 网络令牌 (JWT),
¥get a JSON Web Token (JWT),
-
并将 JWT 存储到浏览器的
localStorage
属性中,以便以后检索和验证我们的请求。¥and store the JWT into the
localStorage
property of your browser for later retrieval and authentication of our requests.
有关 JWT 身份验证的其他信息可以在 用户和权限插件 文档中找到。
¥Additional information about JWT authentication can be found in the Users & Permissions plugin documentation.
🧑💻 代码示例:
¥🧑💻 Code example:
为此,你可以在 FoodAdvisor 项目的 /client
文件夹中创建一个包含以下示例代码的 pages/auth/login.js
文件。高亮的行显示发送到 Strapi 的用户和权限插件提供的 /auth/local
路由的请求:
¥To achieve this, in the /client
folder of the FoodAdvisor project, you could create a pages/auth/login.js
file that contains the following example code. Highlighted lines show the request sent to the /auth/local
route provided by Strapi's Users & Permissions plugin:
此文件使用 formik 包 - 使用 yarn add formik
安装它并重新启动开发服务器。
¥This file uses the formik package - install it using yarn add formik
and restart the dev server.
import React from 'react';
import { useFormik } from 'formik';
import { Button, Input } from '@nextui-org/react';
import Layout from '@/components/layout';
import { getStrapiURL } from '@/utils';
const Login = () => {
const { handleSubmit, handleChange } = useFormik({
initialValues: {
identifier: '',
password: '',
},
onSubmit: async (values) => {
/**
* API URLs in Strapi are by default prefixed with /api,
* but because the API prefix can be configured
* with the rest.prefix property in the config/api.js file,
* we use the getStrapiURL() method to build the proper full auth URL.
**/
const res = await fetch(getStrapiURL('/auth/local'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
});
/**
* Gets the JWT from the server response
*/
const { jwt } = await res.json();
/**
* Stores the JWT in the localStorage of the browser.
* A better implementation would be to do this with an authentication context provider
* or something more sophisticated, but it's not the purpose of this tutorial.
*/
localStorage.setItem('token', jwt);
},
});
/**
* The following code renders a basic login form
* accessible from the localhost:3000/auth/login page.
*/
return (
<Layout>
<div className="h-full w-full flex justify-center items-center my-24">
<form onSubmit={handleSubmit} className="flex flex-col gap-y-6 w-4/12 ">
<h1 className="font-bold text-3xl mb-6">Login</h1>
<Input
onChange={handleChange}
type="email"
name="identifier"
label="Email"
placeholder="Enter your email"
/>
<Input
type="password"
name="password"
label="Password"
placeholder="Enter your password"
onChange={handleChange}
/>
<Button type="submit" className="bg-primary rounded-md text-muted">
Login
</Button>
</form>
</div>
</Layout>
);
};
export default Login;
详细了解自定义 服务和控制器 如何帮助你调整基于 Strapi 的应用。
¥Learn more about how custom services and controllers can help you tweak a Strapi-based application.