我正在构建一个Laravel API,它使用身份验证令牌对用户进行身份验证。对于任何需要身份验证的路由,我将它们包装在auth
过滤器中:
Route::group(array('before' => 'auth'), function() {
Route::get('user/account', 'UserController@getAccountDetails');
});
我的auth
过滤器基本上解密传入的身份验证令牌并检查它是否有效:
Route::filter('auth', function()
{
// Try catch because Crypt::decrypt throws an exception if it's not a valid string to decrypt
try {
$authToken = Crypt::decrypt(Request::header('Authorization'));
// If there's a user tied to this auth token, it's valid
$user = AuthToken::where('token', '=', $authToken)->first()->user()->first();
if (!$user) {
throw new 'Exception();
}
// Make the user globally accessible in controllers
} catch ('Exception $e) {
return Response::json([
'data' => [
'error' => 'You must be logged in to access this resource.'
],
'success' => false,
'status' => 403
], 403);
}
});
很简单的东西,但我被困在下一部分。我希望能够轻松地检索我的控制器和模型中的当前用户记录。
例如,如果我使用Laravel的Auth
库,我可以通过在我的控制器中执行Auth::user()
来获得当前用户。我想有这种功能,但我不知道如何建立它。我可以写一个类,得到实例化认证后与返回一个User
模型的静态方法?
不确定这是否适合您,但也许您想使用oauth2而不是编写"自己的"基于令牌的身份验证?
有一个非常好的用于laravel项目的ouath2服务器包装器:oauth2-server-laravel.
根据它的文档,你可以(例如密码流认证)把这个放在它的配置:
'password' => array(
'class' => 'League'OAuth2'Server'Grant'Password',
'access_token_ttl' => 604800,
'callback' => function($username, $password){
$credentials = array(
'email' => $username,
'password' => $password,
);
$valid = Auth::validate($credentials);
if (!$valid) {
return false;
}
return Auth::getProvider()->retrieveByCredentials($credentials)->id;
}
)
然后你可以你可以验证(在这种情况下通过用户名和密码)发送post请求,像这样:
POST https://www.example.com/oauth/access_token?
grant_type=password&
client_id=the_client_id&
client_secret=the_client_secret&
username=the_username&
password=the_password&
scope=scope1,scope2&
state=123456789
请求将返回生成的令牌,然后您可以像往常一样进行api调用,只需将令牌放入post数据中。
在您的api逻辑中,通过令牌获取用户非常简单,在这种情况下,只需运行:
User::find(ResourceServer::getOwnerId());
它将使诸如:刷新令牌,其他授权流,范围访问,客户端管理更容易。开箱即用
你也可以像这样保护任何特定的路由:
Route::get('secure-route', array('before' => 'oauth', function(){
return "oauth secured route";
}));
您可以在oauth2-server-laravel文档中找到更多详细信息:https://github.com/lucadegasperi/oauth2-server-laravel
和oauth2文档:http://oauth.net/documentation/
确实,Auth::user()
方法非常方便。那么,为什么不简单地扩展Auth
类来编写您自己的身份验证驱动程序呢?你可以在这里找到所有需要的文档。
然后你就可以使用Auth
facade,就像在你可以编写的其他laravel应用程序中一样…很棒,不是吗?