Home > Article > PHP Framework > API Authentication and Authorization with Laravel: Protecting Sensitive Data and Operations
Using Laravel for API authentication and authorization: protecting sensitive data and operations
Overview:
API (Application Programming Interface) is an important part of modern web application development component, which allows data interaction and function calls between various systems. In API applications, data security is crucial. Laravel is a popular PHP framework that provides powerful API authentication and authorization functions, which can help us protect sensitive data and operations and prevent unauthorized access.
1. Install and configure Laravel
First, we need to use composer to install Laravel. Run the following command in the command line:
composer global require laravel/installer
After the installation is complete, we can use the following command to create a new Laravel project:
laravel new api-auth
Enter the directory where the project is located:
cd api-auth
Next, we need to generate a key to encrypt our user data. Run the following command:
php artisan key:generate
2. Create API authentication and authorization related files
php artisan make:model User -m
This command will generate a User model and the corresponding database migration file.
php artisan make:controller AuthController
routes/api. php
file, defining API-related routes: Route::post('login', 'AuthController@login'); Route::post('register', 'AuthController@register'); Route::middleware('auth:api')->group(function () { Route::get('user', 'AuthController@user'); Route::post('logout', 'AuthController@logout'); });
The above routes define user login, registration, user information acquisition, logout and other interfaces.
app/Http/Controllers/AuthController.php
file and write the following code: namespace AppHttpControllers; use IlluminateHttpRequest; use AppUser; use IlluminateSupportFacadesAuth; class AuthController extends Controller { public function register(Request $request) { $validatedData = $request->validate([ 'name' => 'required|max:55', 'email' => 'email|required|unique:users', 'password' => 'required|confirmed' ]); $validatedData['password'] = bcrypt($request->password); $user = User::create($validatedData); $accessToken = $user->createToken('authToken')->accessToken; return response(['user' => $user, 'access_token' => $accessToken]); } public function login(Request $request) { $loginData = $request->validate([ 'email' => 'email|required', 'password' => 'required' ]); if (!Auth::attempt($loginData)) { return response(['message' => 'Invalid credentials']); } $accessToken = Auth::user()->createToken('authToken')->accessToken; return response(['user' => Auth::user(), 'access_token' => $accessToken]); } public function user() { return response(['user' => Auth::user()]); } public function logout(Request $request) { $request->user()->token()->revoke(); return response(['message' => 'Successfully logged out']); } }
In the above code , we define user registration, login, obtaining user information and logout operations.
3. Configure API authentication and authorization
config/auth.php
file and find guards
and providers
Configuration items, configure according to the following example: 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users' ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ] ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => AppUser::class ] ],
php artisan migrate
php artisan passport:install
After execution, a pair of encrypted public and private keys will be generated for issuing and verifying access. Token.
php artisan passport:client --personal
5. Test API authentication and authorization
http://localhost:8000/api/register
to send the following data: { "name": "John Doe", "email": "johndoe@example.com", "password": "password", "password_confirmation": "password" }
http://localhost:8000/api/login
Send the following data: { "email": "johndoe@example.com", "password": "password" }
http://localhost: 8000/api/user
Send a request and add Authorization: Bearer {access_token}
in the Headers, where {access_token}
is the access token returned when logging in. http://localhost:8000/api/logout
, also add Authorization: Bearer {access_token}
in the Headers . Above, we have successfully protected sensitive data and operations through Laravel's API authentication and authorization functions. Using the user model, controller, routing and the functions provided by Passport, we can easily implement authentication and authorization control of the API.
The above is the detailed content of API Authentication and Authorization with Laravel: Protecting Sensitive Data and Operations. For more information, please follow other related articles on the PHP Chinese website!