Skip to main content

Laravel

配置Authok

获取应用密钥

你需要如下信息

  • Domain
  • Client ID
  • Client Secret

配置回调URL

配置 Logout URL

创建 Laravel 应用

composer create-project --prefer-dist laravel/laravel DIRECTORY_NAME dev-master

安装 AuthOK SDK

composer require authok/login

配置 SDK

php artisan vendor:publish --tag=authok-config

打开.env文件添加配置:

# AuthOK 租户域名
# 可在 AuthOK 应用的设置页面找到.
AUTHOK_DOMAIN=YOUR_DOMAIN

# AuthOK 应用的 Client ID
# 可在 AuthOK 应用的设置页面找到.
AUTHOK_CLIENT_ID=YOUR_CLIENT_ID

# AuthOK 应用的 Client Secret
# 可在 AuthOK 应用的设置页面找到.
AUTHOK_CLIENT_SECRET=YOUR_CLIENT_SECRET

# AuthOK 自定义API的唯一标识.
# 可以在自定义API的设置页面找到.
AUTHOK_AUDIENCE=undefined

# 认证回调URI, 和 AuthOK 应用设置中保持一致.
AUTHOK_REDIRECT_URI=http://localhost:3000/authok/callback

配置应用

config/auth.php

'defaults' => [
'guard' => 'authok',
],

然后,找到guards章节,添加authok:

config/auth.php
'guards' => [
'authok' => [
'driver' => 'authok',
'provider' => 'authok',
],
],

最后,在providers章节,添加authok:

config/auth.php
'providers' => [
// ...

'authok' => [
'driver' => 'authok',
'repository' => \Authok\Laravel\Auth\User\Repository::class
],
],

认证路由

编辑routes/web.php文件:

routes/web.php
// 添加以下代码

Route::get('/login', \Authok\Laravel\Http\Controller\Stateful\Login::class)->name('login');
Route::get('/logout', \Authok\Laravel\Http\Controller\Stateful\Logout::class)->name('logout');
Route::get('/authok/callback', \Authok\Laravel\Http\Controller\Stateful\Callback::class)->name('authok.callback');

保护路由

编辑routes/web.php文件:

routes/web.php
Route::get('/', function () {
if (Auth::check()) {
return view('authok.user');
}

return view('authok/guest');
})->middleware(['authok.authenticate.optional']);

接下来添加另外一个路由:

routes/web.php
Route::get('/required', function () {
return view('authok.user');
})->middleware(['authok.authenticate']);

添加视图

resources/views/authok/guest.blade.php
<!DOCTYPE html>
<html>
<body>
<p><a href="{{ route('login') }}">登录</a></p>
</body>
</html>

创建resources/views/authok/user.blade.php文件:

<!DOCTYPE html>
<html>
<body>
<p><a href="{{ route('logout') }}">注销</a></p>
<div>
<pre><?php print_r(Auth::user()) ?></pre>
</div>
</body>
</html>

运行应用

php artisan serve --port=3000