Zend_Auth主要用來認證身份,Zend_Auth可以經由authenticate方法傳入特定的Auth Adapter(例如Zend_Auth_Adapter_Ldap或Zend_Auth_Adapter_DbTable),以便控制與哪方面的身份資料介接

LDAP Auth

application.ini(只列出LDAP設定檔部份)

.....
[ldap]
ldap.master.host = "ldap.com"
ldap.master.port = "636"
ldap.master.username = "uid=webauth,ou=netgroup,dc=test,dc=org,dc=tw"
ldap.master.password = "123"
ldap.master.bindRequiresDn = true
ldap.master.baseDn = "dc=test,dc=org,dc=tw"
ldap.master.useSsl = true
.....

LoginController.php

params = this->_request->getParams();

//建立Zend_Auth Instance
auth = Zend_Auth::getInstance();  //自訂session namespace,預設的namespace為Zend_Auth  auth->setStorage(new Zend_Auth_Storage_Session('TEST'));
//設定timeout(秒)需要再透過Zend_Session
authSession = new Zend_Session_Namespace('TEST');  authSession->setExpirationSeconds(100);

//判斷是否有Identity(已登入)
if (auth->hasIdentity()) {  	this->_redirect('/');
}


if (!empty(params['account']) && !empty(params['passwd'])) {
	//讀入application.ini LDAP的設定檔
	config = new Zend_Config_Ini(dirname(__DIR__) . '/configs/application.ini', 'ldap');  	//ldap server可以設定為多台  	ldap = config->ldap->toArray();    	//建立LDAP的Auth_Adapter  	adapter = new Zend_Auth_Adapter_Ldap(ldap, params['account'], params['passwd']);  	result = auth->authenticate(adapter);

	//取得LDAP的Auth_Adapter log
	print_r(result->getMessages());    	//取得result code  	/*  		result code分類  		Zend_Auth_Result::SUCCESS  		Zend_Auth_Result::FAILURE  		Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND  		Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS  		Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID  		Zend_Auth_Result::FAILURE_UNCATEGORIZED  	*/  	code = result->getCode();  	//登入判斷  	if (Zend_Auth_Result::SUCCESS === code) {
		//透過Auth_Storage可以寫入自行定義資訊
		storage = auth->getStorage();
		storage->write(array('A'=>'Johnson','B'=>'Maple'));  		this->_redirect('/');
	} else {
		echo "Error Code:".$code;
	}
}

IndexController

auth = Zend_Auth::getInstance();  //設定name space  auth->setStorage(new Zend_Auth_Storage_Session('TEST'));
//取得Identity值
print_r(auth->getIdentity());    //清空Identity(登出)  auth->clearIdentity();

注意,因為Zend_Auth只用來做身份認證,所以如果要取得LDAP裡的其他資訊,請使用Zend_Ldap

DB Auth

application.ini

resources.db.adapter = "PDO_MYSQL"
resources.db.params.dbname = ""
resources.db.params.host = "localhost"
resources.db.params.username = ""
resources.db.params.password = ""
resources.db.params.driver_options.1002 = "SET NAMES utf8"
resources.db.isDefaultTableAdapter = true

controller

dbAdapter = Zend_Db_Table::getDefaultAdapter();  auth = Zend_Auth::getInstance();

//DB Auth
authAdapter = new Zend_Auth_Adapter_DbTable(dbAdapter);
//define column
authAdapter->setTableName('table_name')  			->setIdentityColumn('account_column')  			->setCredentialColumn('passwd_column');  			//DB中存的是MD5編碼,可以自動做密碼編碼後的驗證  			->setCredentialTreatment('MD5(?)');  //define value  authAdapter->setIdentity(account)  			->setCredential(password);
result = auth->authenticate($authAdapter);