【发布时间】:2016-01-06 20:00:21
【问题描述】:
我正在尝试学习 Laravel,我的目标是能够构建一个 RESTful API(不使用视图或刀片,只有 JSON 结果。稍后,AngularJS 网络应用程序和 Cordova 混合移动应用程序将使用此 API .
经过一些研究,我倾向于选择 JWT-Auth 库以获得完全无状态的好处。我的问题是:我有两种主要类型的用户:客户和版主。客户不需要密码。我需要能够生成一个令牌,以便仅使用提供的电子邮件进行访问。如果该电子邮件存在于数据库中并且属于客户,它将生成并返回令牌。 如果它存在并且属于版主,它将返回 false 以便接口可以请求密码。如果邮件不存在,则抛出无效参数错误。
我阅读了文档here,它说可以使用自定义声明。但是文档没有解释什么是声明以及作为自定义声明传递的数组的含义。我想要一些关于如何实现我上面解释的内容的意见。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
}
谢谢。
更新
赏金代码
public function authenticate(Request $request) {
$email = $request->input('email');
$user = User::where('email', '=', $email)->first();
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
【问题讨论】:
标签: php angularjs authentication jwt