cranetm / yii2-json-rpc-2.0

Other
26 stars 18 forks source link

How to get a error response using a `beforeAction` filter #18

Closed cboulanger closed 6 years ago

cboulanger commented 6 years ago

Hi, I am trying to use the beforeAction filter to implement access control with the \JsonRpc2\extensions\AuthTraite extension llike so:

  public function beforeAction($action)
  {
    if (!parent::beforeAction($action)) {
      return false;
    }

    // authenticate action is always allowed
    if (in_array($action->id, ["authenticate"])) {
      return true;
    }

    // on-the-fly authentication with access token
    $token = $this->getAuthCredentials();
    if (!$token or ! User::findIdentityByAccessToken($token)) {
      return false;
      // @todo this doesn't work:
      // throw new AuthException('Missing authentication', AuthException::MISSING_AUTH);
    }

    // we're fine.
    return true;
  }

However, it seems to be impossible to force the controller to output a JSONRPC error message. Returning false from the beforeAction method simply returns null, and if I raise an Exception, it will be rendered as a HTML error page. The reason is that beforeAction is executed without catching exceptions. How would I impement generic access control without duplicating code in each action method?

Thank you.

cranetm commented 6 years ago

I suggest not to use AuthTraite at all. Send your token in headers and you can easily fetch it in beforeAction without exceptions from AuthTraite. In next release RFC 6750 with Authorization-header will be supported.