Yii authorization and redirecting

Asked
Active3 hr before
Viewed126 times

9 Answers

authorizationredirecting
90%

1 You should not do it this way. The recommended way is to do it with if(Yii::app()->user->isGuest) Yii::app()->user->loginRequired();. It will redirect to the login page and store the return URL for you. – Michael Härtl Apr 17 '13 at 17:41 ,I have created AdminModule.php. In this, I have created a function that will check if the user is logged in or not. And also there are public pages, which doesn't require login.,I'm new in Yii, and I need to fix some thing: there is some controller with some actions, and if user tries to load some action, I need to check if he's authorized; if yes, then do some actions, if no - to redirect to login page. How can I do it? I hope I needn't to check through Yii::user and redirect manually in each action? Thanks in advance. , Oh sorry, I mean if user is not logged in he should be gone to login page. Your comment is good and it works, but tell me, how can I set controller/action for loginRequired() method? – user2218845 Apr 17 '13 at 17:51

In short, create method in controller:

    public
    function filters() {
       return array(
          'accessControl',
       );
    }

And then define access rules for actions with method:

public
function accessRules() {
   return array(
      array('deny',
         'actions' => array('create', 'edit'),
         'users' => array('?'),
      ),
      array('allow',
         'actions' => array('delete'),
         'roles' => array('admin'),
      ),
      array('deny',
         'actions' => array('delete'),
         'users' => array('*'),
      ),
   );
}

To define url for redirect if user is not authenticated, define it in user component:

'user' => [
   'class' => 'CWebUser', // or custom
   'allowAutoLogin' => true, // for autologin
   'loginUrl' => ['/ua/user/login'], // if not authenticated go here
]
load more v
88%

CAccessControlFilter throws CHttpException with error code "403" when an access is denied. If your errorHandler is configured that errorAction is "site/index", then you can modify SiteController as follows:,#0 E:\Users\thiagovidal\Development\xampp\htdocs\yii\framework\web\auth\CAccessControlFilter.php(115): CAccessControlFilter->accessDenied(Object(WebUser), ‘You are not aut…’),You are not authorized to perform this action. (E:\Users\thiagovidal\Development\xampp\htdocs\yii\framework\web\auth\CAccessControlFilter.php:153),More Learn Books Resources Develop Download Yii Report an Issue Report a Security Issue Contribute to Yii About What is Yii? Release Cycle News License Team Official logo

CAccessControlFilter throws CHttpException with error code "403" when an access is denied. If your errorHandler is configured that errorAction is "site/index", then you can modify SiteController as follows:

class SiteController extends CController

{

   ...

   public
   function actionError()

   {

      if (Yii::app() - > errorHandler - > error['code'] == 403)

         $this - > redirect('url');

      else

         $this - > render('error');

   }

   ...

}
load more v
72%

If the user is a guest, it will call yii\web\User::loginRequired() to redirect the user browser to the login page.,Authorization is the process of verifying that a user has enough permission to do something. Yii provides two authorization methods: Access Control Filter (ACF) and Role-Based Access Control (RBAC).,Access Control Filter,If the user is already authenticated, it will throw a yii\web\ForbiddenHttpException.

The code below shows how to use ACF in the site controller:

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

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

I'm new in Yii, and I need to fix some thing: there is some controller with some actions, and if user tries to load some action, I need to check if he's authorized; if yes, then do some actions, if no - to redirect to login page. How can I do it? I hope I needn't to check through Yii::user and redirect manually in each action? Thanks in advance. ,I have created AdminModule.php. In this, I have created a function that will check if the user is logged in or not. And also there are public pages, which doesn't require login.,To define url for redirect if user is not authenticated, define it in user component:,And then define access rules for actions with method:

In short, create method in controller:

    public
    function filters() {
       return array(
          'accessControl',
       );
    }

And then define access rules for actions with method:

public
function accessRules() {
   return array(
      array('deny',
         'actions' => array('create', 'edit'),
         'users' => array('?'),
      ),
      array('allow',
         'actions' => array('delete'),
         'roles' => array('admin'),
      ),
      array('deny',
         'actions' => array('delete'),
         'users' => array('*'),
      ),
   );
}

To define url for redirect if user is not authenticated, define it in user component:

'user' => [
   'class' => 'CWebUser', // or custom
   'allowAutoLogin' => true, // for autologin
   'loginUrl' => ['/ua/user/login'], // if not authenticated go here
]
load more v
75%

1What I can tell jquery plugins for smooth change of the background-position?,0How to fix error when installing gulp-imagemin and other similar plugins?,4Is it possible to access my files, knowing the password of my accounts?,0What the plugin allows you to do filter on aktivnosti in WooCommerce?


public
function behaviors() {
   return [
      'access' => [
         'class' => AccessControl::className(),
         'rules' => [
            [
               'actions' => ['login', 'error'],
               'allow' => true,
            ],
            [
               'actions' => ['logout', 'index'],
               'allow' => true,
               'roles' => ['@'],
            ],
         ],
      ],
      'verbs' => [
         'class' => VerbFilter::className(),
         'actions' => [
            'logout' => ['post'],
         ],
      ],
   ];
}

'urlManager' => [
   'enablePrettyUrl' => true,
   'showScriptName' => false,
   'rules' => [
      'login' => 'site/login',
      "=> 'site/index'
   ],
],
load more v
40%

Small note from contributor: As i can see in docs:,Only add Header to Response, but not redirect user immediately to login page and asked controller still execute! So you must add ->send() and (i don`t now why exit(0), because return true or false was not working). Final code:,\Yii::$app->getResponse()->redirect($this->redirectUri);,@coobic you are right, have added ->send(), thanks!

Only add Header to Response, but not redirect user immediately to login page and asked controller still execute!
So you must add ->send() and (i don`t now why exit(0), because return true or false was not working).
Final code:

\
Yii::$app - > getResponse() - > redirect($this - > redirectUri) - > send();
exit(0);
22%

i install rights module to my site and i create controller called ProfileController ,first: you shold make role to your controller from your rights module like: access profile,I also want to point out, that you will need to create the "components" directory if you haven't done so. This is where many people add their custom Classes. Whether it be your own helper class, or extending a base Yii component (such as extending yiiwebController).,Console application does not have Yii->$app->user. So, you need to configure user component in configconsole.php.

i install rights module to my site and i create controller called ProfileController

class ProfileController extends RController {

   public
   function filters() {
      return array('rights');
   }
}

i decided who can access this controller but when user try to access this page it redirect him to

Error 403
You are not authorized to perform this action.
load more v
60%

If you go to the URL http://localhost:8080/index.php?r=site/about, you will see the page, but if you open the URL http://localhost:8080/index.php?r=site/contact, you will be redirected to the login page because only authenticated users can access the contact action.,@ − matches an authenticated user.,The process of verifying that a user has enough permission to do something is called authorization. Yii provides an ACF (Access Control Filter), an authorization method implemented as yii\filters\AccessControl. Modify the behaviors() function of the SiteController −,roles − Defines user roles that this rule matches. Two special roles are recognized − ? − matches a guest user. @ − matches an authenticated user.

The process of verifying that a user has enough permission to do something is called authorization. Yii provides an ACF (Access Control Filter), an authorization method implemented as yii\filters\AccessControl. Modify the behaviors() function of the SiteController −

public
function behaviors() {
   return [
      'access' => [
         'class' => AccessControl::className(),
         'only' => ['about', 'contact'],
         'rules' => [
            [
               'allow' => true,
               'actions' => ['about'],
               'roles' => ['?'],
            ],
            [
               'allow' => true,
               'actions' => ['contact', 'about'],
               'roles' => ['@'],
            ],
         ],
      ],
   ];
}
load more v
48%

and this is how it redirects normally to the main page, but does not authorize the user.,I took a code from another site, it worked well, a person registered, entered data, pressed a button, and he was redirected to the main page and immediately authorized, this was the code:,Well, in SiteController, no changes. As a result, the redirect stopped working, and I understand that the script does not go into this piece of code, How to access assets directly without hash? 1 Answers

I took a code from another site, it worked well, a person registered, entered data, pressed a button, and he was redirected to the main page and immediately authorized, this was the code:

public
function signup() {
   if (!$this - > validate()) {
      return null;
   }

   $user = new User();
   $user - > username = $this - > username;
   $user - > email = $this - > email;
   $user - > setPassword($this - > password);
   $user - > generateAuthKey();
   return $user - > save() ? $user : null;
public
function actionSignup() {
   $model = new SignupForm();
   if ($model - > load(Yii::$app - > request - > post())) {
      if ($user = $model - > signup()) {
         if (Yii::$app - > getUser() - > login($user)) {
            return $this - > goHome();
         }
      }
   }
   return $this - > render('signup', [
      'model' => $model,
   ]);
}

Everything worked out perfectly. Then I needed to add a role to the RBAC tables during registration, Jeffrey helped me for which I am very grateful to him, everything was added to the database both in user and in RBAC, the code looked like this :

public
function signup() {
   if (!$this - > validate()) {
      return null;
   }

   $user = new User();
   $user - > username = $this - > username;
   $user - > email = $this - > email;
   $user - > setPassword($this - > password);
   $user - > generateAuthKey();
   if ($user - > save()) {
      $role = Yii::$app - > authManager - > getRole('user');
      Yii::$app - > authManager - > assign($role, $user - > id_user);
   }
}

Well, in SiteController, no changes. As a result, the redirect stopped working, and I understand that the script does not go into this piece of code

if ($user = $model - > signup()) {
   if (Yii::$app - > getUser() - > login($user)) {
      return $this - > goHome();
   }
}

and this is how it redirects normally to the main page, but does not authorize the user.

if ($user = $model - > signup()) {
   if (Yii::$app - > getUser() - > login($user)) {
      return $this - > goHome();
   }
}
return $this - > goHome();
load more v

Other "authorization-redirecting" queries related to "Yii authorization and redirecting"