search
HomeBackend DevelopmentPHP TutorialYii2的rbac怎么关联某一个具体的action,有人有例子吗?

看到Yii::$app->authManager->createPermission('createPost')就可以创建createPost权限了;
然后再分配给某个用户,该用户就拥有这个权限了。
我认为'createPost'应该仅仅是权限的名字而已,事实上他也许对应一个logout操作(假设)。那么Yii怎么把权限和具体的action关联起来的呢?
是不是要配合AccessColtrol来使用呢?如果是,那要这个permission有什么意义呢?直接给role不就可以了?
求指教。3Q first~

回复内容:

看到Yii::$app->authManager->createPermission('createPost')就可以创建createPost权限了;
然后再分配给某个用户,该用户就拥有这个权限了。
我认为'createPost'应该仅仅是权限的名字而已,事实上他也许对应一个logout操作(假设)。那么Yii怎么把权限和具体的action关联起来的呢?
是不是要配合AccessColtrol来使用呢?如果是,那要这个permission有什么意义呢?直接给role不就可以了?
求指教。3Q first~

正好做到做鉴权判断这块,我给你解答。

AccessColtrol 这种是一种形式

index、view 两个动作就是能通过AccessColtrol来判断了

<code>public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['index', 'view', 'create', 'update'],
            'rules' => [
                [
                    'actions' => ['index'], //来宾可见
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['view', 'create', 'update'], //登录用户
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'actions' => ['create', 'update'], //Post请求
                    'allow' => true,
                    'verbs' => ['POST']
                ],
            ],
        ],
    ];
}

public function actionIndex()
{
    return '来宾可见';
}

public function actionView()
{
    echo '登录用户可见:'."\n";
    return Yii::$app->user->identity->id;
}
  </code>

使用Rbac,放在各自的方法里

优点是使用灵活,缺点是每次都要写相识的代码

<code>public function actionCreate()
{
    if (Yii::$app->user->can('CreatePost')) {
        return '可以的';
    } else {
        throw new UnauthorizedHttpException('对不起,您现在还没获此操作的权限。');
    }
}

public function actionUpdate()
{
    if (Yii::$app->user->can('UpdatePost')) {
        return '可以的';
    } else {
        throw new UnauthorizedHttpException('对不起,您现在还没获此操作的权限。');
    }
}

</code>

使用Rbac,放在beforeAction这个方法里

正好跟上面一点相反,要根据请求的动作来判断哪个权限

<code>public function beforeAction($action) {
    if (parent::beforeAction($action)) {
        //print_r($action); // 权限名字传递过去(CreatePost)
        if (!Yii::$app->user->can('CreatePost')) {
            throw new UnauthorizedHttpException(Yii::t('yii', '对不起,您现在还没获此操作的权限'));
        }
        return true;
    } else {
        return false;
    }
}

</code>

最后给你参考资料:http://www.yiichina.com/doc/guide/2.0/security-authorization

[该用户已被屏蔽]被屏蔽是什么意思啊?

Javascript局部变量有没有属性描述符

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)