Laravel access authentication -api routing -token

Our separation of the front and rear end, all of the projects are in the development of server-side API, this article sets out the detailed implementation steps, unfamiliar with Laravel classmates reference.

Basic Operations

1, the database table structure adjustment

In the user table, such an increase in the code

Schema::table('users', function ($table) {
    $table->string('api_token', 80)->after('password')
                        ->unique()
                        ->nullable()
                        ->default(null);
});

 

2, generated for the user api_token, and encrypted storage

 Since the separation of the front and rear end, so api_token creation and return only when the user is logged in. then:

Api define a route, user / login

Route::post('/user/login', 'Api\UserController@login');

 Create a controller, App / Http / Controllers / Api / UserController, in the login process, api_token stored encrypted, the unencrypted api_token and returned to the requestor.

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\HOBaseController;
use App\Http\Requests\UserLoginRequest;
use App\Http\Models\User;
use Illuminate\Support\Str;

class UserController extends HOBaseController
{
    //
    public function login(UserLoginRequest $request)
    {
        $validated = $request->validated();

        $user = User::where('name', $request->username)
                            ->where('password', $request->password)
                            ->first();

        if(null == $user){
            $this->error()->incorrectUsernameOrPassword();
        }

        $token = Str::random(60);
        $user->api_token = hash('sha256', $token);
        $user->save();

        return $this->response($token);
    }
}

In config / auth.php document, the guard of the api hash attribute set to "true"

'api' => [
    'driver' => 'token',
    'provider' => 'users',
    'hash' => true,
],

 

3, route protection

With auth: api api to protect all routes (login except routing)

Route::middleware('auth:api')->post('/test', 'Api\TestController@test'); 

 

4, after the failure of the authentication redirection

Create a new route, a name called the "unauthenticated", we put it in UserController inside, and creates a corresponding method unauthenticated, used to return message to the user.

Route::post('/user/unauthenticated', 'Api\UserController@unauthenticated')->name('unauthenticated');
public function unauthenticated(Request $request)
{
    $this->error()->unauthenticated();
}

App / Http / Middleware / Authenticate.php file, modify redirectTo. When the user authentication is not passed, the visit will be redirected to the specified route. For api access, this situation we should return an error message to the user informing that this time have no right to this access, retrieve token.

 protectedfunction redirectTo($request){

return route('unauthenticated');
}

 

Guess you like

Origin www.cnblogs.com/zhaoxizhe/p/11308128.html