laravel - 我只能在我 auth()->login() 的方法中访问我的 auth()->user() 而不能在同一个控制器中访问其他方法
问题描述
我正在尝试在新控制器中使用护照实现我自己的登录/注销。
class AuthController extends AccessTokenController
{
use AuthenticatesUsers;
.
.
我的登录方法工作正常:
public function login(ServerRequestInterface $request)
{
if (!auth()->attempt([
'email' => $request->getParsedBody()['email'],
'password' => $request->getParsedBody()['password']
])) {
return response()->json('failed attempt...');
}
auth()->login(User::where('id', Auth::user()->id)->first());
.
.
// I can access auth()->user() here just fine ..
}
但是我无法在注销方法中访问经过身份验证的用户,因此我可以获取他的令牌并删除它们。
public function logout()
{
//I can't access the authenticated user here
return auth()->user();
//return response()->json('Logged out successfully', 200);
}
我究竟做错了什么?注意:我在登录方法中省略了与颁发令牌相关的任何内容,因为它与问题无关。
更新:我的路线/api.php
Route::post('register', 'Auth\RegisterController@register');
Route::post('login', 'Auth\AuthController@login');
Route::post('logout', 'Auth\AuthController@logout');
解决方案
如果您正在使用,api
那么您应该发送authorization header
否则它应该适用于session
基于authentication
然后您可以使用请求访问经过身份验证的用户
public function logout(Request $request)
{
return $request->user(); //the user that made the request (the authenticated user)
}
或者:
public function logout(Request $request)
{
return Auth::user(); //the user that made the request (the authenticated user)
}
推荐阅读
- algorithm - 背包式问题的动态规划
- excel - VBA,自动填充系列而不是复制单元格
- kubernetes - 如何将现有的 kubernetes 清单文件添加到 Helm Chart
- javascript - 一部分是先编译的
- canvas - 如何在fabricjs中添加图案以适合圆圈?
- python - 职员匹配查询不存在
- python - 如何在 Fast API Python 中读取 URL 参数和正文类型
- react-admin - React-admin:登录后useQuery未在仪表板上获取数据
- java - Java Swing GridLayout 看起来不像我期望的那样
- powershell - 在 Windows power shell 中,如何提取属性文件值并将其保存到 env var?