第一步
执行以下命令:
composer require laravel/passportPHP artisan migratePHP artisan passport:install
第二步
修改 config/auth.PHP 文件中的 Gurds:
... 'guards' => [ 'web' => [ 'driver' => 'session', 'provIDer' => 'users', ], 'API' => [ 'driver' => 'passport', 'provIDer' => 'users', ], ],...
第三步
app/User.PHP
<?PHPnamespace App;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Passport\HasAPITokens;class User extends Authenticatable { use Notifiable, HasAPITokens; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hIDden for arrays. * * @var array */ protected $hIDden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verifIEd_at' => 'datetime', ];}
第四步
app/RepositorIEs/User/UserRepositoryInterface.PHP
<?PHPnamespace App\RepositorIEs\User;use Illuminate\http\Request;interface UserRepositoryInterface { public function register(Request $request); public function login(Request $request); public function refreshToken(Request $request); public function details(); public function logout(Request $request); public function response($data, int $statusCode); public function getTokenAndRefreshToken(string $email, string $password); public function sendRequest(string $route, array $formParams); public function getoClIEnt();}
第五步
创建 app/RepositorIEs/User/UserRepository.PHP 文件
<?PHPnamespace App\RepositorIEs\User;use App\User;use Guzzlehttp\ClIEnt;use Illuminate\http\Request;use Illuminate\Support\Facades\Auth;use Laravel\Passport\ClIEnt as OClIEnt;use Guzzlehttp\Exception\ClIEntException;use App\RepositorIEs\User\UserRepositoryInterface;class UserRepository implements UserRepositoryInterface { const SUCCUSUS_STATUS_CODE = 200; const UNAUTHORISED_STATUS_CODE = 401; const BASE_URL = "http://mylemp-Nginx"; public function __construct(ClIEnt $clIEnt) { $this->http = $clIEnt; } public function register(Request $request) { $email = $request->email; $password = $request->password; $input = $request->all(); $input['password'] = bcrypt($input['password']); User::create($input); $response = $this->getTokenAndRefreshToken($email, $password); return $this->response($response["data"], $response["statusCode"]); } public function login(Request $request) { $email = $request->email; $password = $request->password; if (Auth::attempt(['email' => $email, 'password' => $password])) { $response = $this->getTokenAndRefreshToken($email, $password); $data = $response["data"]; $statusCode = $response["statusCode"]; } else { $data = ['error'=>'Unauthorised']; $statusCode = self::UNAUTHORISED_STATUS_CODE; } return $this->response($data, $statusCode); } public function refreshToken(Request $request) { if (is_null($request->header('Refreshtoken'))) { return $this->response(['error'=>'Unauthorised'], self::UNAUTHORISED_STATUS_CODE); } $refresh_token = $request->header('Refreshtoken'); $OclIEnt = $this->getoClIEnt(); $formParams = [ 'grant_type' => 'refresh_token', 'refresh_token' => $refresh_token, 'clIEnt_ID' => $OclIEnt->ID, 'clIEnt_secret' => $OclIEnt->secret, 'scope' => '*']; return $this->sendRequest("/oauth/token", $formParams); } public function details() { $user = Auth::user(); return $this->response($user, self::SUCCUSUS_STATUS_CODE); } public function logout(Request $request) { $request->user()->token()->revoke(); return $this->response(['message' => 'Successfully logged out'], self::SUCCUSUS_STATUS_CODE); } public function response($data, int $statusCode) { $response = ["data"=>$data, "statusCode"=>$statusCode]; return $response; } public function getTokenAndRefreshToken(string $email, string $password) { $OclIEnt = $this->getoClIEnt(); $formParams = [ 'grant_type' => 'password', 'clIEnt_ID' => $OclIEnt->ID, 'clIEnt_secret' => $OclIEnt->secret, 'username' => $email, 'password' => $password, 'scope' => '*']; return $this->sendRequest("/oauth/token", $formParams); } public function sendRequest(string $route, array $formParams) { try { $url = self::BASE_URL.$route; $response = $this->http->request('POST', $url, ['form_params' => $formParams]); $statusCode = self::SUCCUSUS_STATUS_CODE; $data = Json_decode((string) $response->getbody(), true); } catch (ClIEntException $e) { echo $e->getMessage(); $statusCode = $e->getCode(); $data = ['error'=>'OAuth clIEnt error']; } return ["data" => $data, "statusCode"=>$statusCode]; } public function getoClIEnt() { return OClIEnt::where('password_clIEnt', 1)->first(); }}
第六步
app/http/Requests/UserLoginRequest.PHP
<?PHPnamespace App\http\Requests;use Illuminate\Foundation\http\FormRequest;use Illuminate\Contracts\ValIDation\ValIDator;use Illuminate\http\Exceptions\httpResponseException;class UserLoginRequest extends FormRequest { const UNPROCESSABLE_ENTITY = 422; public function rules() { return [ 'email' => 'required|email', 'password' => 'required', ]; } protected function FailedValIDation(ValIDator $valIDator) { throw new httpResponseException(response()->Json($valIDator->errors(), self::UNPROCESSABLE_ENTITY)); }}
第七步
app/http/Requests/UserRegisterRequest.PHP
<?PHPnamespace App\http\Requests;use Illuminate\Foundation\http\FormRequest;use Illuminate\Contracts\ValIDation\ValIDator;use Illuminate\http\Exceptions\httpResponseException;class UserRegisterRequest extends FormRequest { const UNPROCESSABLE_ENTITY = 422; public function rules() { return [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required', 'c_password' => 'required|same:password', ]; } protected function FailedValIDation(ValIDator $valIDator) { throw new httpResponseException(response()->Json($valIDator->errors(), self::UNPROCESSABLE_ENTITY)); }}
第八步
app/ProvIDers/AppServiceProvIDer.PHP
<?PHPnamespace App\ProvIDers;use App\RepositorIEs\User\UserRepository;use App\RepositorIEs\User\UserRepositoryInterface;use Illuminate\Support\ServiceProvIDer;class AppServiceProvIDer extends ServiceProvIDer { /** * Register any application services. * * @return voID */ public function register() { $this->app->bind(UserRepositoryInterface::class, UserRepository::class); } /** * bootstrap any application services. * * @return voID */ public function boot() { // }}
第九步
app/ProvIDers/AuthServiceProvIDer.PHP
<?PHPnamespace App\ProvIDers;use Illuminate\Foundation\Support\ProvIDers\AuthServiceProvIDer as ServiceProvIDer;use Laravel\Passport\Passport;class AuthServiceProvIDer extends ServiceProvIDer { /** * The policy mapPings for the application. * * @var array */ protected $policIEs = [ // 'App\Model' => 'App\PolicIEs\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return voID */ public function boot() { $this->registerPolicIEs(); Passport::routes(); }}
第十步
app/http/Controllers/UserController.PHP
<?PHPnamespace App\http\Controllers;use Illuminate\http\Request;use App\http\Requests\UserLoginRequest;use App\http\Requests\UserRegisterRequest;use App\RepositorIEs\User\UserRepositoryInterface;class UserController extends Controller { const SUCCUSUS_STATUS_CODE = 200; const UNAUTHORISED_STATUS_CODE = 401; public function __construct(UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; } public function login(UserLoginRequest $request) { $response = $this->userRepository->login($request); return response()->Json($response["data"], $response["statusCode"]); } public function register(UserRegisterRequest $request) { $response = $this->userRepository->register($request); return response()->Json($response["data"], $response["statusCode"]); } public function details() { $response = $this->userRepository->details(); return response()->Json($response["data"], $response["statusCode"]); } public function logout(Request $request) { $response = $this->userRepository->logout($request); return response()->Json($response["data"], $response["statusCode"]); } public function refreshToken(Request $request) { $response = $this->userRepository->refreshToken($request); return response()->Json($response["data"], $response["statusCode"]); }}
第十一步
routes/API.PHP
<?PHPuse Illuminate\Support\Facades\Route;Route::post('login', 'UserController@login');Route::post('register', 'UserController@register');Route::post('refreshtoken', 'UserController@refreshToken');Route::group(['mIDdleware' => ['auth:API']], function () { Route::post('logout', 'UserController@logout'); Route::post('details', 'UserController@details');});
推荐教程:《Laravel教程》 总结
以上是内存溢出为你收集整理的Laravel Passport 构建 API 身份验证和授权全部内容,希望文章能够帮你解决Laravel Passport 构建 API 身份验证和授权所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)