Redirect user to previous page after auth (yii2)

我的未来我决定 提交于 2019-12-10 14:57:18

问题


I have the main controller from which the others are inherited. Code is something like this

public function init()
{
    $this->on('beforeAction', function ($event) {
        ...

        if (Yii::$app->getUser()->isGuest) {
            $request = Yii::$app->getRequest();
            // dont remember login page or ajax-request
            if (!($request->getIsAjax() || strpos($request->getUrl(), 'login') !== false))                  {
               Yii::$app->getUser()->setReturnUrl($request->getUrl());
              }
           }
        }
        ...
    });
}

It works perfectly for all pages, except the page with captcha. All the pages with captcha are redirected to something like this - /captcha/?v=xxxxxxxxxxxxxx

If the object is logged Yii::$app->getRequest() then I see that for pages with captcha it is used twice. For the first time the object is corect, and the second time I see the object with captcha. How can I solve this problem with yii? Is there a chance not to track the request for captcha?


回答1:


The default (generated) controller uses something like this:

public function actions()
{
    return [
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
        ],
    ];
}

Does your controller contain something like this?

This means that there is an action "captcha" that is used for displaying captchas (it returns the image). When you have a page displaying a captcha the image is called after the page you want to return to. Therefore that latest page visited is the one with the captcha.

I think you have to filter out this action.

Another possibility could be to use the default $controller->goBack() method. I think this handles registering of the returnUrl by default.

Reference: Class yii\web\Controller




回答2:


Guid security authorization

Use Access Control Filter(ACF) in your controller.

use yii\web\Controller;
use yii\filters\AccessControl;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['login', 'logout', 'signup'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['login', 'signup'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['logout'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    // ...
}


来源:https://stackoverflow.com/questions/24100608/redirect-user-to-previous-page-after-auth-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!