dozxos6346 2014-11-29 16:58
浏览 58

在Yii2中拒绝未登录用户的视图站点

I have this code in Yii2, where I define users (in models/Users.php):

<?php

namespace app\models;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'my_password',
            'authKey' => 'my_authkey',
            'accessToken' => 'my_accessyoken',

And this is my code in SiteController.php:

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

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

The problem is:

1) Right now, visitors can view any page in my website without being logged. Which is the easiest way to force users to be logged in to see any pages?

2) How can I let only specific users view some private pages?

I've already tried some options with no luck...

Thanks!

  • 写回答

1条回答 默认 最新

  • dqgxazo4483 2014-11-30 21:50
    关注

    Well, you are preventing anybody that is not logged in to access your logout page. But you are not preventing guests from accessing any other page in the controller. You can do this: https://github.com/yiisoft/yii2-app-advanced/blob/master/frontend/controllers/SiteController.php

    see how they defined that only logged in people have access to logout and only guests can signup.

    Regarding the second part, only allow certain logged in customers to access some parts, you can always create your own filter: http://www.yiiframework.com/doc-2.0/guide-structure-filters.html or you can try just overwriting beforeAction of the controller.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料