laravel api_token认证

1.php artisan migrate

2.修改users表,添加api_token字段

2.App\User.php

 'datetime',
    ];
}

3.config/auth.php

    'defaults' => [
        'guard' => 'api',(改)
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

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

4.php artisan make:request BaseRequest

5.api.php

Route::post('/register','Auth/ApiController@register');
Route::post('/login','Auth/ApiController@login');
Route::post('/refresh','Auth/ApiController@refresh');
Route::post('/logout','Auth/ApiController@logout');

6.php artisan make:controller Auth/ApiController

middleware('auth')->except('login', 'register');
    }

    protected function username()
    {
        return 'name';
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
///
//        if (!request('password')){
//            return 123;
//        }

        $api_token = Str::random(50);
        $data = array_merge($request->all(), compact('api_token'));
        $this->create($data);

        return compact('api_token');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'unique:users',],
//            'email' => ['required', 'string', 'email', 'max:255',],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    protected function create(array $data)
    {
        return User::forceCreate([
            'name' => $data['name'],
//            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'api_token' => hash('sha256', $data['api_token']),
        ]);
    }

    public function logout()
    {
        auth()->user()->update(['api_token' => null]);

        return ['message' => '退出登录成功'];
    }

    public function login()
    {
        $user = User::where($this->username(), request($this->username()))
            ->firstOrFail();

        if (!password_verify(request('password'), $user->password)) {
            return response()->json(['error' => '抱歉,账号名或者密码错误!'],
                403);
        }

        $api_token = Str::random(80);
        $user->update(['api_token' => hash('sha256', $api_token)]);

        return compact('api_token');
    }

    public function refresh()
    {
        $api_token = Str::random(80);
        auth()->user()->update(['api_token' => hash('sha256', $api_token)]);

        return compact('api_token');
    }
}

附:其实这套方案我还是觉得太复杂了,不适合我这个菜B,于是我改了一下。

    public function register(Request $request)
    {
        $data = $request->all();
        $rules = [
            'email' => 'required'
        ];
        $messages = [
            'email.required' => '邮箱不能为空'
        ];
        $validator = Validator::make($request->all(),$rules,$messages);
        if($validator->fails()){
            return $validator->errors();
        }
        DB::table('users')->insert([
            'name' => $data['name'],
            'password' => $data['password'],
            'api_token' => Str::random(80),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

这样就简单多了,反正够用就行。

你可能感兴趣的:(php,laravel)