nrikiji / breeze-api
Requires
- php: ^7.3|^8.0
- illuminate/filesystem: ^8.42
- illuminate/support: ^8.42
- illuminate/validation: ^8.42
This package is not auto-updated.
Last update: 2024-09-20 09:58:51 UTC
README
这是一个基于 Breeze 的 API 端点轻松实现的包。
因为它只提供 API,所以不包含任何与 Breeze 视图相关的文件(blade、javascript、css)。
它还与 Sanctum 一起使用,以在 SPA 中实现基于会话和基于令牌的认证。
setup
$ laravel new my-app
$ cd my-app
$ composer require nrikiji/breeze-api
$ php artisan breeze-api:install
接下来,安装 sanctum
$ composer require laravel/sanctum
$ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
$ php artisan migrate
在 User 模型中使用 HasApiTokens trait 以使用 API 令牌
app/Models/User.php
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
向 API 添加中间件以使用 Sanctum 和会话
app/Http/Kernel.php
protected $middlewareGroups = [
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
# Added the following three items
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
],
];
如果需要 cors
※ 示例
后端: https://:8000
前端: https://:3000
.env
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
app/config/cors.php
'supports_credentials' => true,
启用用户电子邮件认证
实现 MustVerifyEmail 接口
app/Models/User.php
use Illuminate\Contracts\Auth\MustVerifyEmail;
class User extends Authenticatable implements MustVerifyEmail
{
・・・
}
如果您需要发送电子邮件
用于电子邮件地址验证和密码重置功能
配置邮件服务器
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=465
MAIL_USERNAME=mail_username
MAIL_PASSWORD=mail_password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=no-reply@example.com
MAIL_FROM_NAME="${APP_NAME}"
设置确认电子邮件中包含的链接的 URL。
app/Http/Providers/AuthServiceProvider.php
// URL for email address verification
VerifyEmail::createUrlUsing(function ($notifiable) {
$id = $notifiable->getKey();
$hash = sha1($notifiable->getEmailForVerification());
・・・
// This URL will be inserted as a link in the email, using the id and hash to request the $endpoint
$parsed = parse_url($endpoint);
$url = "https://example.com" . $parsed["path"] . "?" . $parsed["query"];
return $url;
});
// URL for password reset
ResetPassword::createUrlUsing(function ($user, string $token) {
// This URL will be inserted as a link in the email, and the token will be used to request the API
return 'https://example.com/reset-password?token=' . $token;
});
用法
API 令牌
用户注册
$ curl -v -X POST -H 'Accept: application/json' https://:8000/api/register -d 'name=hoge' -d 'email=hoge@example.com' -d 'password=password' -d 'password_confirmation=password'
{"token":"xxxxxxxxxx"}
重新发送用户电子邮件地址验证 URL
curl -v -X POST -H 'Accept: application/json' -H 'Authorization: Bearer xxxxxxxxxx' "https://:8000/api/email/verification-notification"
用户电子邮件地址验证
*端点由电子邮件正文的 URL 确定。
$ curl -v -X GET -H 'Accept: application/json' -H 'Authorization: Bearer xxxxxxxxxx' "https://:8000/api/verify-email/123/yyyyyyyyyy?expires=1623304571&signature=zzzzzzzzzz"
登录
$ curl -v -X POST -H 'Accept: application/json' https://:8000/api/login -d 'email=hoge@example.com' -d 'password=password'
{"token":"xxxxxxxxxx"}
用户信息
$ curl -v -X GET -H 'Accept: application/json' -H 'Authorization: Bearer xxxxxxxxxx' https://:8000/api/user
{"id":1,"name":"hoge","email":"hoge@example.com","email_verified_at":null,"created_at":"2021-06-10T02:34:45.000000Z","updated_at":"2021-06-10T02:34:45.000000Z"}
注销
$ curl -v -X POST -H 'Accept: application/json' -H 'Authorization: Bearer xxxxxxxxxx' https://:8000/api/logout
密码重置
$ curl -v -X POST -H 'Accept: application/json' https://:8000/api/forgot-password -d "email=hoge@example.com"
密码重置2
- 从确认电子邮件的正文中获取令牌。
$ curl -v -X POST -H 'Accept: application/json' https://:8000/api/reset-password -d "email=hoge@example.com" -d "password=password" -d "password_confirmation=password" -d "token=xxxxxxxxxx"
SPA
axios 示例
对于 cors,设置 withCredentials=true
axios.defaults.withCredentials = true;
用户注册
await axios.get(API_URL + 'sanctum/csrf-cookie');
await axios.post(API_URL + 'api/register',{
name: "hoge",
email: "hoge@example.com",
password: "password",
password_confirmation: "password",
});
重新发送用户电子邮件地址验证 URL
await axios.post(API_URL + 'email/verification-notification');
用户电子邮件地址验证
*端点由电子邮件正文的 URL 确定。
const path = "api/verify-email/123/xxxxxxxxxx?expires=1623206775&signature=yyyyyyyyyy";
await axios.get(API_URL + path);
登录
await axios.get(API_URL + 'sanctum/csrf-cookie');
await axios.post(API_URL + 'api/login', { email: "hoge@example.com", password: "password" });
用户信息
const user = await axios.get(API_URL + 'api/user');
console.log(user); // => {id: 1, name: "hoge", email: "hoge@example.com", email_verified_at: null,…}
注销
await axios.post(API_URL + 'api/logout');
密码重置
await axios.post(API_URL + 'api/forgot-password', { email: "hoge@example.com" });
密码重置2
- 从确认电子邮件的正文中获取令牌。
await axios.post(API_URL + 'api/reset-password', {
email: "hoge@example.com",
password: "password",
password_confirmation: "password",
token: "xxxxxxxxxx",
});
故障排除
API 响应变为 HTML(文本)而不是 JSON。
将 "Accept: application/json" 添加到 HTTP 请求头。Laravel 将尝试在使用 Ajax 请求或指定此头时使响应为 JSON。当通过 Ajax 或指定此头请求时,Laravel 将尝试使响应为 JSON。
但是,我们已经为无法添加此头的情况准备了 HandleAuthApiRequests 中间件。请根据需要使用它。这可以通过将其添加到 app/Http/Kernel.php 中来启用。