title: Yii2 and OAuth2 Plugin Filsh/yii2-oauth2-server: Unauthorized when sending POST data
body: <hr>
  
  <p><strong>EDIT: SOLVED</strong></p>
  
  <p>Apparently this plugin, was having some problem <strong>missing</strong> the request headers. The solution was adding</p>
  
  <pre><code>SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
  </code></pre>
  
  <p>To the .htaccess file to make Authorizaion variable available as this issue report says:</p>
  
  <pre><code>https://github.com/yiisoft/yii2/issues/6631
  </code></pre>
  
  <hr>
  
  <p>I'm currently working with Yii2 and using <a href="https://github.com/Filsh/yii2-oauth2-server" rel="nofollow">this OAuth2 plugin</a> (Filsh/yii2-oauth2-server) for login and to work with tokens from a mobile HTML5 app.</p>
  
  <p>I've configured everything, and it's retrieving the token, but when I try to send the token via POST it throws an error.</p>
  
  <p>I start by calling <code>send()</code> to retrieve the token.</p>
  
  <pre><code>function send(){
      var url = "http://www.server.org/app/api/oauth2/rest/token";
      var data = {
          'grant_type':'password',
          'username':'user',
          'password':'pass',
          'client_id':'clientid',
          'client_secret':'clientsecret',
      };
  
      $.ajax({
          type: "POST",
          url: url,
          data: data,
          success:function(data){
          console.log(data);
              token = data.access_token;
          },
      })
  };
  </code></pre>
  
  <p>Then when I perform this a call to <code>createuser()</code>.</p>
  
  <pre><code>function createuser(){
          var url = "http://www.server.org/app/api/v1/users/create";
          var data = {
              'callback':'asdf',
              'username': 'user',
              'password':'pass',
              'first_name':'name',
              'last_name':'lastname'
          };
  
          $.ajax({
              type: "POST",
              url: url,
              data: data,
              beforeSend: function (xhr) {
                  xhr.setRequestHeader('Authorization', 'Bearer ' + token);
              },
              success:function(r){
                  console.log(r);
              },
          });
      }
  </code></pre>
  
  <p>It returns</p>
  
  <blockquote>
    <p>Unauthorized: You are requesting with an invalid credential</p>
  </blockquote>
  
  <p><strong>When I change to GET instead, it works fine.</strong></p>
  
  <p>This is my controller, I'm already using:</p>
  
  <blockquote>
    <p>['class' => HttpBearerAuth::className()],
      ['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],</p>
  </blockquote>
  
  <p>As authentication method.</p>
  
  <pre><code>&lt;?php
  
  namespace app\api\modules\v1\controllers;
  
  use Yii;
  use app\models\OauthUsers;
  use yii\rest\ActiveController;
  use yii\web\Response;
  use yii\helpers\ArrayHelper;
  
  use yii\filters\auth\HttpBearerAuth;
  use yii\filters\auth\QueryParamAuth; 
  use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
  use filsh\yii2\oauth2server\filters\auth\CompositeAuth;
  
  class UsersController extends \yii\web\Controller
  {
  public function behaviors()
  {
      return ArrayHelper::merge(parent::behaviors(), [
          'authenticator' =&gt; [
              'class' =&gt; CompositeAuth::className(),
              'authMethods' =&gt; [
                  ['class' =&gt; HttpBearerAuth::className()],
                  ['class' =&gt; QueryParamAuth::className(), 'tokenParam' =&gt; 'accessToken'],
              ]
          ],
          'exceptionFilter' =&gt; [
              'class' =&gt; ErrorToExceptionFilter::className()
          ],
          'class' =&gt; \yii\filters\ContentNegotiator::className(), 
  
      ]);
  }
  
  /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
  public function actionCreate()
  {
      $model = new OauthUsers;
  
      try {
          if ($model-&gt;load($_POST) &amp;&amp; $model-&gt;save()) {
              return $this-&gt;redirect(Url::previous());
          } elseif (!\Yii::$app-&gt;request-&gt;isPost) {
              $model-&gt;load($_GET);
          }
      } catch (\Exception $e) {
          $msg = (isset($e-&gt;errorInfo[2]))?$e-&gt;errorInfo[2]:$e-&gt;getMessage();
          $model-&gt;addError('_exception', $msg);
      }
      return "true";
  }
  
  }
  </code></pre>
  
  <p>This is my configuration object</p>
  
  <pre><code>'oauth2' =&gt; [
          'class' =&gt; 'filsh\yii2\oauth2server\Module',            
          'tokenParamName' =&gt; 'accessToken',
          'tokenAccessLifetime' =&gt; 3600 * 24,
          'storageMap' =&gt; [
              'user_credentials' =&gt; 'app\models\OauthUsers', 
          ],
          'grantTypes' =&gt; [
              'user_credentials' =&gt; [
                  'class' =&gt; 'OAuth2\GrantType\UserCredentials',
              ],
              'refresh_token' =&gt; [
                  'class' =&gt; 'OAuth2\GrantType\RefreshToken',
                  'always_issue_new_refresh_token' =&gt; true
              ]
          ]
      ]
  </code></pre>
  
  <p>This is class OauthUsers</p>
  
  <pre><code>&lt;?php
  
  namespace app\models;
  
  use Yii;
  use \app\models\base\OauthUsers as BaseOauthUsers;
  
  /**
  * This is the model class for table "oauth_users".
  */
  class OauthUsers extends BaseOauthUsers 
  implements \yii\web\IdentityInterface,\OAuth2\Storage\UserCredentialsInterface
  
  {
  /**
   * @inheritdoc
   */
  public static function findIdentity($id) {
      $dbUser = OauthUsers::find()
              -&gt;where([
                  "id" =&gt; $id
              ])
              -&gt;one();
      if (!count($dbUser)) {
          return null;
      }
      return new static($dbUser);
  }
  
  /**
   * @inheritdoc
   */
  public static function findIdentityByAccessToken($token, $userType = null) {
  
      $at = OauthAccessTokens::find()
              -&gt;where(["access_token" =&gt; $token])
              -&gt;one();
  
      $dbUser = OauthUsers::find()
              -&gt;where(["id" =&gt; $at-&gt;user_id])
              -&gt;one();
      if (!count($dbUser)) {
          return null;
      }
      return new static($dbUser);
  }
  
  /**
   * Implemented for Oauth2 Interface
   */
  public function checkUserCredentials($username, $password)
  {
      $user = static::findByUsername($username);
      if (empty($user)) {
          return false;
      }
      return $user-&gt;validatePassword($password);
  }
  
  /**
   * Implemented for Oauth2 Interface
   */
  public function getUserDetails($username)
  {
      $user = static::findByUsername($username);
      return ['user_id' =&gt; $user-&gt;getId()];
  }
  
  /**
   * Finds user by username
   *
   * @param  string      $username
   * @return static|null
   */
  public static function findByUsername($username) {
      $dbUser = OauthUsers::find()
              -&gt;where([
                  "username" =&gt; $username
              ])
              -&gt;one();
      if (!count($dbUser)) {
          return null;
      }
      return new static($dbUser);
  }
  
  /**
   * @inheritdoc
   */
  public function getId()
  {
      return $this-&gt;id;
  }
  
  /**
   * @inheritdoc
   */
  public function getAuthKey()
  {
      return $this-&gt;authKey;
  }
  
  /**
   * @inheritdoc
   */
  public function validateAuthKey($authKey)
  {
      return $this-&gt;authKey === $authKey;
  }
  
  /**
   * Validates password
   *
   * @param  string  $password password to validate
   * @return boolean if password provided is valid for current user
   */
  public function validatePassword($password)
  {
      return $this-&gt;password === $password;
  }
  }
  </code></pre>
  
  <p>I've changed <code>createuser</code> too, but still receiving a 401. I'm not sure it is passing through <code>findIdentityByAccessToken</code> (access_token is in a different table than oauth users, thats why I'm querying it first). </p>
  
  <p>Any thoughts?</p>