我正在尝试学习 Laravel,我的目标是能够构建一个 RESTful API(不使用 View 或 Blade ,仅使用 JSON 结果。稍后,AngularJS 网络应用程序和 Cordova 混合移动应用程序将使用此 api .
经过一些研究,我倾向于选择 JWT-Auth 库以获得完全无状态的好处。我的问题是:我有两种主要类型的用户:客户 和版主。客户不需要密码。我需要能够生成一个 token ,以便仅使用提供的电子邮件进行访问。如果该电子邮件存在于数据库中并且属于客户,它将生成并返回 token 。 如果它存在并且属于主持人,它将返回 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'));
}
最佳答案
试试这个:
$user=User::where('email','=','user2@gmail.com')->first();
if (!$userToken=JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
return response()->json(compact('userToken'));
对我有用,希望能帮到你
关于php - 无需密码即可使用 JWT Laravel 5 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028630/