[英]Can we use same route for authenticated and non-authenticated users in laravel with same controller and same view?
[英]Is it possible to use Auth::user() on non-authenticated routes?
这一定是一件非常简单的事情,但我在 Laravel 中没有很多经验,我一直在寻找和努力,但没有运气。
我正在处理一个现有的项目,它有一些使用auth:api
中间件的路由,如下所示:
Route::group(['namespace' => 'Api', 'prefix' => 'api', 'middleware' => 'auth:api', 'throttle:100,1'], function () {
// Route.....
});
在这些路由的任何控制器中, Auth::user() 工作正常,并返回登录的用户实例。 到现在为止还挺好。
现在,我有另一组路由,它们是公开的,因此它们不使用auth:api
中间件。 但是,登录用户也可以访问这些路由,并且基于此条件(无论是否登录),我想运行其他逻辑。 总而言之,登录用户和公共用户都可以访问该页面; 但是如果用户登录了,我们会运行一个额外的逻辑。 但是,当我尝试使用Auth::user()
它返回 null,而auth()->check()
返回 false。
请记住,我不能使用 auth 中间件,因为这会限制公共用户访问页面,这不是我们所需要的。
如果用户拥有需要验证的信息,您可以在用户请求路由时手动验证该用户。 如果他没有,那么您可以对未经身份验证的用户使用您的逻辑。
https://laravel.com/docs/5.7/authentication#authenticating-users
您应该将 auth 与警卫一起使用。
{{ \Auth::guard('api')->user(); }}
或者,您可以通过 Illuminate\\Http\\Request 实例访问经过身份验证的用户。
说明
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
/**
* Update the user's profile.
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
// $request->user() returns an instance of the authenticated user...
}
}
检查文档
在调用Auth::guard('api')->user()
工作时,我发现每次尝试访问经过身份验证的用户时都必须设置默认保护非常难看。
您可以做的是创建一个新的中间件,为特定路由设置默认保护。
创建一个新的中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class DefaultGuard
{
/**
* The authentication factory instance.
*
* @var Auth
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param Auth $auth
*
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param $request
* @param Closure $next
* @param $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard)
{
$this->auth->shouldUse($guard);
return $next($request);
}
}
将它添加到app\\Http\\Kernel.php
的$routeMiddleware
属性
protected $routeMiddleware = [
'guard' => DefaultGuard::class,
];
将其应用于您的公共路线:
Route::group([ 'middleware' => 'guard:api'], function () {
// Route.....
});
现在您可以像往常一样访问经过身份验证的用户,例如:
Auth::user();
$request->user();
etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.