Home  >  Article  >  Backend Development  >  PHP development: Use Laravel Sanctum to implement SPA application security certification

PHP development: Use Laravel Sanctum to implement SPA application security certification

WBOY
WBOYOriginal
2023-06-14 11:37:091503browse

Laravel Sanctum is a lightweight user authentication library officially recommended by the Laravel framework. It is designed to provide simple and modern authentication for single page applications (SPA) and mobile applications. This article will introduce how to use Laravel Sanctum to implement security authentication for SPA applications.

1. Install Laravel
First you need to install Laravel. You can install the latest version of Laravel through composer:

composer create-project --prefer-dist laravel/laravel your-project-name

2. Configure Sanctum
After installing Laravel, you need to configure Sanctum. Please execute the following command first:

composer require laravel/sanctum

Under Laravel 5.5 or below version, you need to add service providers and facades in the config/app.php file:

'providers' => [

...
LaravelSanctumSanctumServiceProvider::class,

],

'aliases' => [

...
'Sanctum' => LaravelSanctumSanctum::class,

],

In Laravel 5.5 and above, there is no need to manually add service providers or facades.

You then need to perform a database migration to create the tables required by Sanctum:

php artisan migrate

If your application needs to use SPA authentication, it should be in config/ Add your application domain and trusted domains in the cors.php file. In the example below, we assume you are building a backend API with a frontend application:

'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['http://your-app-url.com'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age ' => false,

'supports_credentials' => true,

3. Create API and authentication controller
Create an index.blade.php file in resources/views , used to display the SPA interface.

Write API routes in routes/api.php. We create a test route here to return the user information of the currently authenticated user:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {

return $request->user();

});

Next, we need to add a SPA application-specific controller to create and manage Sanctum tokens. This controller is responsible for creating tokens and issuing authentication cookies for users.

First create an API controller in the app/Http/Controllers folder, such as AuthController:

php artisan make:controller API/AuthController

Then add it in AuthController Register and login methods:

public function register(Request $request)
{

$request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|unique:users|max:255',
    'password' => 'required|string|min:8|confirmed'
]);

$user = new User([
    'name' => $request->name,
    'email' => $request->email,
    'password' => Hash::make($request->password)
]);

$user->save();

return response()->json([
    'message' => 'Successfully registered'
], 201);

}

public function login(Request $request)
{

$request->validate([
    'email' => 'required|string|email',
    'password' => 'required|string',
    'remember_me' => 'boolean'
]);

$credentials = request(['email', 'password']);

if (!Auth::attempt($credentials)) {
    return response()->json([
        'message' => 'Unauthorized'
    ], 401);
}

$user = $request->user();

$tokenResult = $user->createToken('Personal Access Token');

$token = $tokenResult->token;

if ($request->remember_me) {
    $token->expires_at = Carbon::now()->addWeeks(1);
}

$token->save();

return response()->json([
    'access_token' => $tokenResult->accessToken,
    'token_type' => 'Bearer',
    'expires_at' => Carbon::parse(
        $tokenResult->token->expires_at
    )->toDateTimeString()
]);

}

4. Handling Authentication
Now that you have all the necessary code to create a token, user registration, and user login, we will start building the authentication process.

The SPA application uses Sanctum to send POST requests to verify user credentials via the email and password parameters. If the authentication is successful, the application receives the OAuth Token.

When using a SPA application, add Authorization: Bearer d6fb5a6237ab04b68d3c67881a9080fa in the headers to access the protected API through application routing.

After completing the authentication, you can use the authentication route through Sanctum to obtain the information of the currently authenticated user. For example, we can retrieve the name of the currently authenticated user using the following code:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {

return $request->user()->name;

});

5. Create related pages and components
Be sure to ensure that your Laravel entry point file contains the necessary JavaScript libraries (here using Vue.js, Vue Router and Axios ). In the resources/js/app.js file, define the Vue component:

require('./bootstrap');

import Vue from 'vue';
import App from ' ./views/App';
import router from './router';
import store from './store';

Vue.component('App', App);

const app = new Vue({

el: '#app',
router,
store

});

Create resource folders views and views/App.vue, add necessary components (login form, registration form, etc. ). Create all required page components in the views folder.

For the convenience of demonstration, the amount of code here is slightly larger. Please refer to the official Laravel documentation.

6. Reconstruct API routing and AckController
Update API routing, map SPA routing to AckController, and ensure that the middleware will use Sanctum configuration:

Route::middleware('auth :sanctum')->get('/user', function (Request $request) {

return $request->user();

});

Route::post('/register', 'APIAuthController@ register');
Route::post('/login', 'APIAuthController@login');

Route::middleware('auth:sanctum')->get('/spa/ {any}', function () {

return view('index');

})->where('any', '.*');

We add the forgottenPassword and resetPassword methods in AckController, using To handle requests when users forget passwords and respond to password reset links:

public function forgotPassword(Request $request)
{

$request->validate(['email' => 'required|email']);

$user = User::where('email', $request->email)->first();

if (!$user) {
    return response()->json([
        'message' => 'We could not find your account'
    ], 404);
} else {
    $user->sendPasswordResetNotification($request->email);
}

return response()->json([
    'message' => 'We have e-mailed your password reset link!'
]);

}

public function resetPassword( Request $request)
{

$request->validate([
    'email' => 'required|email',
    'token' => 'required|string',
    'password' => 'required|string|confirmed|min:8'
]);

$resetPasswordStatus = Password::reset($request->only('email', 'password', 'password_confirmation', 'token'), function ($user, $password) {
    $user->forceFill([
        'password' => Hash::make($password)
    ])->save();
});

if ($resetPasswordStatus === Password::INVALID_TOKEN) {
    return response()->json(['message' => 'The reset token is invalid']);
}

return response()->json(['message' => 'Your password has been updated']);

}

7. Add routing
In Laravel Sanctum, routing needs to be configured to enable authentication, CSRF protection and error protection, and use groban/laravel-livewire to implement routing for SPA applications.

8. Run the SPA application
After completing the above steps, we can use the following command to run the SPA application:

npm run dev

Open in the browser Run the host IP address or URL on the device to view the SPA application.

Finally, we have successfully used Laravel Sanctum to implement security authentication for SPA applications. With this approach, application data can be secured, preventing unauthorized access and protecting private information.

The above is the detailed content of PHP development: Use Laravel Sanctum to implement SPA application security certification. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn