Yii2 CORS with Auth not working for non CRUD actions

前端 未结 2 1964
耶瑟儿~
耶瑟儿~ 2021-01-13 02:03

I am building an API in Yii2 and have added CORS and authentication. This works fine for all Create/Read/Update/Delete actions but not for custom actions. Has anyone experie

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 02:36

    try this:

    public function behaviors()
    {
        $behaviors = parent::behaviors();
    
        unset($behaviors['authenticator']);
    
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ],
        ];
    
        $behaviors['authenticator'] = [
            'class' =>  HttpBearerAuth::className(),
            'except' => ['options','login'],
        ];
    
        return $behaviors;
    }
    

    It will unset the default authenticator implemented by the parent controller to be sure that cors is treated first. Then we force cors to allow credentials before implementing your own authenticator.


    The other thing that may raise that Unauthorized error is a not-found or wrong Options response as a browser request it first to get a list of allowed verbs. You may check that list in its headers response within your browser's network tab.

    The general rule is when you ask your browser to perform a sensible verb like PUT, DELETE or POST to any url it may first send an OPTIONS request to that same url (check this) to check if that verb is allowed before sending the real request. So Yii should be configured to respond to all those OPTIONS verbs by performing the correct redirections.

    The default CRUD actions implemented by ActiveController are using those default patterns:

    'PUT,PATCH {id}' => 'update',
    'DELETE {id}' => 'delete',
    'GET,HEAD {id}' => 'view',
    'POST' => 'create',
    'GET,HEAD' => 'index',
    '{id}' => 'options',
    '' => 'options',
    

    So whatever configurations you did implement in urlManager['rules'] be sure to not override the last 2 of them and if you are using custom patterns always remember to include its equivalent options verbs like in this example:

    [
        'class' => 'yii\rest\UrlRule', 
        'controller' => ['account' => 'auth/account'], 
        'patterns' => [
            'POST,HEAD login'  => 'login',
            'POST,HEAD signup' => 'signup',
            'POST req-reset-pass' => 'request-password-reset',
            'POST reset-pass' => 'reset-password',
            // OPTTIONS VERBS
            'OPTIONS login' => 'options',
            'OPTIONS signup' => 'options',
            'OPTIONS req-reset-pass' => 'options',
            'OPTIONS reset-pass' => 'options',
        ]
    ],
    

    The same applies when adding custom patterns within extraPatterns.


    The Options action is implemented by default in ActiveController. it's code can be seen here. In case you are extending a different controller than ActiveController like maybe \yii\rest\Controller be sure to manually include it:

    public function actions() 
    {
        $actions = parent::actions();
        $actions['options'] = [
            'class' => 'yii\rest\OptionsAction',
            // optional:
            'collectionOptions' => ['GET', 'POST', 'HEAD', 'OPTIONS'],
            'resourceOptions' => ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
        ];
        return $actions;
    }
    

提交回复
热议问题