当前位置:网站首页>Larave uses sanctum for API authentication
Larave uses sanctum for API authentication
2022-07-24 08:28:00 【micro_ cloud_ fly】
The goal is
1. Use laravel Framework for user login , register , authentication
2. The front and back ends are separated , User interface request , Use API token authentication
step
Installing the
composer create-project laravel/laravel example-app
cd example-app
php artisan serve
here , By visiting http://127.0.0.1:8000 You can see that the visit was successful
Install expansion pack
Next install laravel Official Expansion Pack Sanctum, To achieve the goal
composer require laravel/sanctum
Next , You need to use vendor:publish Artisan Order release Sanctum Configuration and migration files .Sanctum The configuration file of will be saved in config In the folder :
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Modify the configuration file
And then you need to modify it .env The database configuration in the file , Change it to :
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=caixin
DB_USERNAME=root
DB_PASSWORD=root
Database migration
Last , You should run database migration . Sanctum A database table will be created to store API token :
php artisan migrate
Next , If you want to use Sanctum Yes SPA Authentication , You should Sanctum Middleware added to your application app/Http/Kernel.php In the document api In the middleware group :
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
At this point to see app/Models/User.php file ,User The model should use Laravel\Sanctum\HasApiTokens trait:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
}
Analog data
here , In the database user Add a random piece of data to the table
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`)
VALUES
(1, 'java0904', '[email protected]', NULL, '', NULL, NULL, NULL);
Add access routes
At this time in routes/api.php Configure routing in , To get token
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
$user = \App\Models\User::find(1);
Simulated landing , here , Will be the user of session Storage , But actually through API At the time of certification , You can't use it here
// \Illuminate\Support\Facades\Auth::login($user);
$token =$user->createToken($user->name);
return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');
Test acquisition token
Visit at this time http://127.0.0.1:8000/api/tokens/create, You can get token
curl The way
curl -d '' http://127.0.0.1:8000/api/tokens/create
{
"token":"7|ZbSuwu7UBDeQjvXx6iNUCcZJKsbSSO6nctmqLjDq"}
postman test

Test other interfaces
No token
here , To access other API Interface , You need to take it with you Authorization token To visit , otherwise , The following exceptions will occur 
close token
here , hold token close , The effect is as follows
curl test
curl -H 'Authorization: Bearer 7|ZbSuwu7UBDeQjvXx6iNUCcZJKsbSSO6nctmqLjDq' http://local.app.com/api/user
{
"id":1,"name":"java0904","email":"[email protected]","email_verified_at":null,"created_at":null,"updated_at":null}
postman test

Knowledge points supplement 1
app/Providers/RouteServiceProvider.php The role of this file and core code analysis
<?php
class RouteServiceProvider extends ServiceProvider
{
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
//routes/api.php The route in this route file , By default api middleware , And the routing prefix is /api
Route::prefix('api')
// ->middleware(['api'])// Here is the default middleware , There is only one default
// Here I add auth:sanctum This middleware , As a global use , There is no need to add this middleware for each route , But get token The routing , You need to exclude this middleware
->middleware(['api','auth:sanctum'])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
//'routes/web.php' The route in this file , By default web This middleware
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
}
The above code mentioned two built-in middleware api and web, Their definition is app/Http/Kernel.php In file , Its core code is as follows :
protected $middlewareGroups = [
//web middleware
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// We need to pay more attention here , all /route/web.php The routing , If it is post request , There will be csrfToken Validation of the , Of course, you can also manually exclude some routes
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
//api middleware
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Look for the web middleware There is \App\Http\Middleware\VerifyCsrfToken::class, This line , His function is all /route/web.php The routing , If it is post request , There will be csrfToken Validation of the , Of course, you can also manually exclude some routes
Knowledge points supplement 2
/route/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
$user = \App\Models\User::find(1);
Simulated landing , here , Will be the user of session Storage , But actually through API At the time of certification , You can't use it here
// \Illuminate\Support\Facades\Auth::login($user);
$token = $user->createToken($user->name);
return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');
Route::post('/tokens/create2', function (Request $request) {
// Here you can write some of your own verification logic
// User to get token, You must bring your user name and password
$password = $request->get("password");
$username = $request->get("username");
$user = \App\Models\User::where('password', $password)->where('username', $username)->first();
if (!$user) {
return [
'code' => 500,
'msg' => ' Wrong username and password '
];
}
$token = $user->createToken($user->name);
return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');
// Used for writing session, It's not user login with front and back ends separated
Route::post('/login', function (Request $request) {
//laravel Internal verification method
if (\Illuminate\Support\Facades\Auth::attempt([
'username' => $request->get("name"),
'password' => $request->get("password")])) {
// Landing successful
// preservation session
} else {
// Login failed
}
})->withoutMiddleware('auth:sanctum');
Code warehouse
边栏推荐
- [interview] Why do you need foreach with the for cycle?
- [golang from introduction to practice] student achievement management system
- Introduction to wechat authorized login third-party app applet method
- A knight's journey
- Shanghai issued a document to support the entry of NFT cultural exchange: the trend of digital collections has arrived!
- 【游戏合集】手机都要被塞爆了,6款优质Pygame游戏合集降临~(附源码)
- Stack / heap / queue question brushing (Part 2)
- Aquanee: the true meaning of "p2e"
- Wargames bandit (21-33) problem solving essay
- 「题解」零钱兑换
猜你喜欢

SVG 从入门到后悔,怎么不早点学起来(图解版)

Figure storage geabase

Wechat payment V3 version of openresty implementation and pit avoidance Guide (service side)

JMX console unauthorized access vulnerability

国产“火箭心”人工心脏上市 不同人工心脏有什么区别?

Digital collections are both outlets and risks!

Error reported by Nacos: error Nacos failed to start, please see d:\nacos\logs\nacos log for more details.

Database | simple hospital patient appointment system based on opengauss
![[wechat applet development] (III) homepage banner component uses swiper](/img/d6/28252a4bb6425d53715221f7665b04.png)
[wechat applet development] (III) homepage banner component uses swiper

MySQL date formatting
随机推荐
[ByteDance] ByteDance access (including login and payment)
Wechat applet host environment, applet architecture, concise operation structure
WordPress free theme: document, making reading more convenient
[Google play access] payment server token acquisition
Overseas media, domestic we media, media publicity
MySQL counts the total sales data of each month
M-dao creates a one-stop Dao platform, allowing hundreds of millions of players to join Dao space
Wargames NATAS (16-19) problem solving essays
[interview] Why do you need foreach with the for cycle?
js获取当前浏览器的默认语言
The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool
Ansible automatic operation and maintenance
Do you know the private domain traffic in app?
how to add square on screenshot
[technical interview] how to introduce yourself
Musk responded that the brain has been uploaded to the cloud: already did it!
Implementation of unity hub free version
Database | simple hospital patient appointment system based on opengauss
Dynamic programming & backtracking various deformation problems
Web3≠NFT? A digital Renaissance?