简体   繁体   English

Laravel与OAuth2问题

[英]Laravel with OAuth2 issue

I am working on a project with laravel and lucadegasperi/oauth2-server-laravel with password grand type. 我正在使用laravel和lucadegasperi / oauth2-server-laravel使用密码大类型的项目。 Everything is working fine and all my API endpoints are protected by oauth2. 一切正常,我的所有API端点均受oauth2保护。

I only have one API that should always return a JSON data response but this response depends if the user is logged in or not. 我只有一个应始终返回JSON数据响应的API,但是此响应取决于用户是否登录。 And since the Auth check is being handled in the Middleware "OAuthExceptionHandlerMiddleware", if the user is not logged in the request is stopped and do not reach my controller and i get the following response: 并且由于在中间件“ OAuthExceptionHandlerMiddleware”中处理了Auth检查,因此,如果用户未登录,则请求将停止并且不会到达我的控制器,并且我得到以下响应:

{
  "error": "invalid_request",
  "error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."
}

What I am looking to achieve is to be able to handle the request inside my controller only for one API endpoint: 我希望实现的是能够仅在一个API端点上处理控制器内的请求:

  • If the user is not logged in, return the normal response + other data and not the "Invalid Request" response. 如果用户未登录,则返回普通响应和其他数据,而不是“无效请求”响应。
  • If the user is logged in return the normal response. 如果用户已登录,请返回正常响应。

Thank you for any help on how to achieve the above. 感谢您对实现上述目标的任何帮助。

You can add exceptions to your middleware to remove your auth rule. 您可以向中间件添加例外,以删除身份验证规则。

Something like 就像是

$this->middleware('auth', ['except' => array('getActivate', 'getLogin')]);

see Laracasts 见《 拉拉卡斯》

To authenticate inside the controller and not in the Middleware, I ended up up doing the following: 为了在控制器内部而不在中间件中进行身份验证,我最后做了以下工作:

use League\OAuth2\Server\Entity\AccessTokenEntity;
use LucaDegasperi\OAuth2Server\Facades\Authorizer;
use Illuminate\Http\Request;

class ProductController extends Controller {

    public function __construct(Request $request) {
        $this->middleware('oauth', ['except' => ['index']]);
    }

    public function index(Request $request) {
        Authorizer::setRequest($request);
        $accessTokenString = Authorizer::getChecker()->determineAccessToken(true);
        $accessToken = Authorizer::getChecker()->getAccessTokenStorage()->get($accessTokenString);
        if ($accessToken instanceof AccessTokenEntity) {
            echo "logged In with user_id = " . $accessToken->getSession()->getOwnerId();
            //return public products + products related to user 
        }else{
            echo "not logged in";
            //return public products
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM