>  기사  >  백엔드 개발  >  yii에 새로운 사용자 인증을 추가하는 방법

yii에 새로운 사용자 인증을 추가하는 방법

不言
不言원래의
2018-06-15 16:20:261292검색

이 글은 yii에 신규 사용자 인증을 추가하는 방법에 대한 자세한 분석 및 소개입니다. 필요하신 분들은 참고하시면 됩니다

1 왜 신규 사용자 인증을 추가해야 할까요? 웹사이트를 추가하고 싶습니다. 백엔드와 프론트엔드가 동일한 Yii 애플리케이션에 내장되어 있습니다. 하지만 프론트엔드에도 회원 관리 센터가 포함되어 있습니다. 두 가지 사용자 인증이 완전히 다르기 때문에 두 개의 다른 로그인 페이지가 필요하며, 사용자 정보도 있어야 합니다. 또는 다른 쿠키에 저장됩니다. 따라서 애플리케이션에 사용자 확인을 추가해야 합니다.
2.yii 사용자 확인:
사용자 확인을 사용자 정의하기 전에 먼저 yii의 확인 및 승인 방법을 파악해야 합니다. .
사용자를 확인하려면 확인 논리가 포함된 확인 클래스를 정의해야 합니다. Yii에서 이 클래스는 IUserIdentity 인터페이스를 구현해야 하며, 각 클래스는 일반적으로 웹사이트 로그인에 사용자 이름과 비밀번호가 필요합니다. Yii는 CUserIdentity 클래스를 제공하며, 이 클래스는 일반적으로 사용자 이름과 비밀번호를 확인하는 데 사용됩니다. 상속한 후에는 authenticate() 메서드를 다시 작성하여 자체 확인 방법을 구현해야 합니다.
Php

class UserIdentity extends CUserIdentity  
{  
    private $_id;  
    public function authenticate()  
    {  
        $record=User::model()->findByAttributes(array('username'=>$this->username));  
        if($record===null)  
            $this->errorCode=self::ERROR_USERNAME_INVALID;  
        else if($record->password!==md5($this->password))  
            $this->errorCode=self::ERROR_PASSWORD_INVALID;  
        else 
        {  
            $this->_id=$record->id;  
            $this->setState('title', $record->title);  
            $this->errorCode=self::ERROR_NONE;  
        }  
        return !$this->errorCode;  
    }  
    public function getId()  
    {  
        return $this->_id;  
    }  
}

사용자가 로그인할 때 다음 코드가 호출됩니다.

Php code

// 使用提供的用户名和密码登录用户  
$identity=new UserIdentity($username,$password);  
if($identity->authenticate())  
    Yii::app()->user->login($identity);  
else 
    echo $identity->errorMessage;

사용자가 종료할 때 다음 코드가 호출됩니다.

Php code

// 注销当前用户  
Yii::app()->user->logout(); 
 其中的user是yii的一个components.需要在protected/config/main.php中定义
Php code
'user'=>array(  
    // enable cookie-based authentication  
    'allowAutoLogin'=>true,  
        'loginUrl' => array('site/login'),  
),
여기에서는 사용자의 클래스 이름을 지정하지 않습니다. 왜냐하면 yii에서는 기본 사용자가 CWebUser 클래스의 인스턴스이기 때문입니다.

이제 사용자 로그인 확인 및 로그아웃을 구현했지만 이제 사용자는 로그인 여부에 관계없이 모든 작업에 액세스할 수 있습니다. 다음 단계는 사용자 액세스를 승인하는 것입니다. 액세스 제어 필터, 즉 액세스 제어 필터를 통해 사용자 승인이 구현됩니다.

Php 코드

class AdminDefaultController extends CController  
{   
    public function filters()  
        {  
            return array('accessControl');  
        }  
        public function accessRules()  
        {  
            return array(  
                array(  
                    'allow',  
                    'users' => array('@'),  
                ),  
                array(  
                    'deny',  
                    'users' => array('*')  
                ),  
            );  
        }  
}

필터 메소드에 특정 필터를 설정한 것을 볼 수 있습니다.
CController 클래스에 filterAccessControl 메소드가 있습니다.

Php 코드

public function filterAccessControl($filterChain)  
{  
    $filter=new CAccessControlFilter;  
    $filter->setRules($this->accessRules());  
    $filter->filter($filterChain);  
}
새로운 CAccessControlFilter 인스턴스는 다음과 같습니다. 그 안에 생성되며 setRules 시 accessRules() 메서드에서 반환된 매개변수가 전달됩니다.
$filter->filter($filterChain)가 계속해서 다른 필터를 호출합니다.

그리고 모든 특정 권한 부여 규칙은 accessRules에 정의됩니다.


Php 코드

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('*'),  
            ),  
        );  
    }

특정 규칙은 yii 매뉴얼을 참조하세요.

3. 새로운 확인 시스템을 추가합니다:

먼저 CWebUser에서 CAdminUser를 상속합니다: Php 코드

class CAdminWebUser extends CWebUser  
{  
    public $loginUrl = array('admin/admin/login');  
}

글로벌 애플리케이션인 경우 protected/config/main.php의 구성 요소를 전달합니다. 섹션:

Php code

'user'=>array(  
    // enable cookie-based authentication  
        'class' => 'CAdminUser',  
    'allowAutoLogin'=>true,  
       'loginUrl' => array('site/login'),  
),

모듈에 있는 경우 모듈의 init 메소드에 다음 코드를 추가하세요. class:

Php code

$this->setComponents(array(  
       'adminUser' => array(  
                'class' => 'CAdminWebUser',  
                'allowAutoLogin' => false,  
        )  
));

최종 호출 방법

Php code

//全局应用  
Yii::app()->getComponent('adminUser');  
//在模块中  
Yii::app()->controller->module->getComponent('adminUser');
하지만 이것만으로는 충분하지 않습니다. 컨트롤러의 필터도 수정하여 확인 및 인증을 구현해야 합니다. 첫 번째 단계는 필터를 사용자 정의하는 것입니다:
Php 코드

class CAdminAccessControlFilter extends CAccessControlFilter  
{  
    protected function preFilter($filterChain)  
    {  
        $app=Yii::app();  
        $request=$app->getRequest();  
        $user = Yii::app()->controller->module->getComponent('adminUser');  
        $verb=$request->getRequestType();  
        $ip=$request->getUserHostAddress();  
        foreach($this->getRules() as $rule)  
        {  
            if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed  
                break;  
            else if($allow<0) // denied  
            {  
                $this->accessDenied($user);  
                return false;  
            }  
        }  
        return true;  
    }  
}


그런 다음 CController 클래스 Method
Php 코드

public function filterAccessControl($filterChain)  
{  
    $filter = new CAdminAccessControlFilter();  
    $filter->setRules($this->accessRules());  
    $filter->filter($filterChain);  
}  
//在这里我们使用自定义的filter类替换了原来的filter

의 filterAccessController를 다시 작성합니다. 여기서는 accessRules에서 adminUser의 인증을 지정할 수 있습니다. () of this Controller


위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다. 관련 내용은 PHP 중국어 홈페이지를 참고해주세요!

관련 권장 사항:


PHP의 Yii 프레임워크에서 로그인 기능 구현 정보

yii2.0 사용자가 다른 테이블에 로그인하는 데 사용되는 사용자 테이블을 수정하는 방법

위 내용은 yii에 새로운 사용자 인증을 추가하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.