我有一条路线,我正在使用auth中间件,它工作得很好。
Route::group(['prefix' => 'v1','middleware' => ['auth:api']], function()
{
Route::resource('user', 'v1\MyController');
});
问题是我也希望这条路由也可以被非认证用户访问。有了上述内容,我收到401 Unauthorized错误,我无法为未经身份验证的用户返回任何内容。那么,如何验证此路由(以便传递用户数据),同时即使用户未经过身份验证也允许路由继续进行?
(我尝试在路由器页面上进行有条件的Auth检查,但似乎用户已通过身份验证,因此它始终保持错误。)
编辑:我还应该注意,我正在使用带有密码授予和访问令牌的API路由。
我遇到了同样的情况。
由于auth中间件仅检查经过身份验证的用户,因此我们可以为未经过身份验证的用户使用客户端凭据。
客户端凭据在Laravel \ Passport \ Http \ Middleware \ CheckClientCredentails中有一个独立的中间件。
我已经创建了一个自定义中间件来组合两个中间件,以允许任何一个通过。
这是我的自定义中间件
namespace Laravel\Passport\Http\Middleware;
use Closure;
use League\OAuth2\Server\ResourceServer;
use Illuminate\Auth\AuthenticationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
class CheckClientCredentials
{
/**
* The Resource Server instance.
*
* @var ResourceServer
*/
private $server;
/**
* Create a new middleware instance.
*
* @param ResourceServer $server
* @return void
*/
public function __construct(ResourceServer $server)
{
$this->server = $server;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$scopes)
{
$psr = (new DiactorosFactory)->createRequest($request);
try{
$psr = $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
throw new AuthenticationException;
}
foreach ($scopes as $scope) {
if (!in_array($scope,$psr->getAttribute('oauth_scopes'))) {
throw new AuthenticationException;
}
}
return $next($request);
}
}
Kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.api' => \App\Http\Middleware\APIAuthenticate::class,
....
路线\ api.php
Route::group([
'namespace' => 'API',
'middleware' => 'auth.api:api',
], function(){
....
从当前路由组(应用auth中间件)中删除此路由。
然后
public function __construct()
{
if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER)) {
$this->middleware('auth:api');
}
}
然后
if (Auth::check()) {
// Auth users
} else{
//Guest users
}
不要在auth中间件中为访客用户和经过身份验证的用户提供这些网址。因为auth中间件仅允许经过身份验证的用户。
要检查经过身份验证和未经身份验证的用户,可以在视图中使用以下代码
@if (Auth::guest())
//For guest users
@else
//for authenticated users
@endif
编辑:在控制器使用
if (Auth::check()) {
// Auth users
} else{
//Guest users
}
您可以使用此示例:
@if(Auth::user())
echo "authincatesd user";
@else
echo "unauthorised";
@endif