Home > PHP Framework > Laravel > body text

API Authentication and Authorization with Laravel: Protecting Sensitive Data and Operations

WBOY
Release: 2023-08-26 14:33:36
Original
1793 people have browsed it

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
Copy after login

After the installation is complete, we can use the following command to create a new Laravel project:

laravel new api-auth
Copy after login

Enter the directory where the project is located:

cd api-auth
Copy after login

Next, we need to generate a key to encrypt our user data. Run the following command:

php artisan key:generate
Copy after login

2. Create API authentication and authorization related files

  1. Create user model: In Laravel, we often use the Eloquent model to manage data in the database. Run the following command to generate a User model:
php artisan make:model User -m
Copy after login

This command will generate a User model and the corresponding database migration file.

  1. Create a user authentication controller: Run the following command to generate a user authentication controller:
php artisan make:controller AuthController
Copy after login
  1. Create an API route: Edit 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');
});
Copy after login

The above routes define user login, registration, user information acquisition, logout and other interfaces.

  1. Writing user authentication controller: Open the 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']);
    }
}
Copy after login

In the above code , we define user registration, login, obtaining user information and logout operations.

3. Configure API authentication and authorization

  1. Configure Guard and Provider: Open the 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
    ]
],
Copy after login
  1. Run database migration: Run the following command to execute the generated database migration:
php artisan migrate
Copy after login
  1. Configure Passport: Run the following command to publish the Passport configuration file:
php artisan passport:install
Copy after login

After execution, a pair of encrypted public and private keys will be generated for issuing and verifying access. Token.

  1. Create a personal access client: Run the following command to create a personal access client:
php artisan passport:client --personal
Copy after login

5. Test API authentication and authorization

  1. Register a new user: Use a POST request to http://localhost:8000/api/register to send the following data:
{
    "name": "John Doe",
    "email": "johndoe@example.com",
    "password": "password",
    "password_confirmation": "password"
}
Copy after login
  1. Log in a user: Use a POST request to http://localhost:8000/api/loginSend the following data:
{
    "email": "johndoe@example.com",
    "password": "password"
}
Copy after login
  1. Get user information: Use GET request to http://localhost: 8000/api/userSend a request and add Authorization: Bearer {access_token} in the Headers, where {access_token} is the access token returned when logging in.
  2. Log out the user: Use POST request to send a request to 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!