3 回答
TA贡献1803条经验 获得超6个赞
您可以使用 JWT
设置 jwt 之后,您可以使用此代码登录并返回令牌:
public function login() {
/// validation
$credentials = request(['email', 'password']);
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json([
'token' => $token, // Token
'expires' => auth('api')->factory()->getTTL() * 60, // Expiration
]);
}
TA贡献1963条经验 获得超6个赞
使用Laravel Passport然后你可以做这样的事情
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token ' . str_random(10));
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(10);
}
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at)
->toDateTimeString(),
]);
}
这将为您提供一个访问令牌以用于您的以下请求
TA贡献1111条经验 获得超0个赞
下面是一个控制器方法的例子,register它使用 Laravel Passport 的createToken()方法来生成唯一的访问令牌。您可以使用类似的功能在用户登录时返回此令牌。
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'retype_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), Response::HTTP_FORBIDDEN);
}
$user = User::firstOrCreate(
['email' => $request->email],
['name' => $request->name, 'password' => bcrypt($request->password)]
);
$response = [
'token' => $user->createToken('MyApp')->accessToken
];
return response()->json($response, Response::HTTP_CREATED);
}
- 3 回答
- 0 关注
- 182 浏览
添加回答
举报