日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php身份证验证_PHP的身份验证和访问控制

發布時間:2023/12/20 php 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php身份证验证_PHP的身份验证和访问控制 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

php身份證驗證

IBM安全身份和訪問管理

在IBM白皮書“ 何時需要訪問 ”中了解有關在Internet規模上管理訪問控制的更多信息。

在本文的第一部分中,我向您介紹了Sentry 2,逐步介紹了它的安裝和配置,并提供了一些使用它為PHP應用程序實現身份驗證工作流的示例。 除其他外,我演示了如何通過激活電子郵件來設置注冊表。 實施密碼重置工作流程; 以及創建一個支持創建,編輯和刪除用戶帳戶的用戶帳戶管理器。

在第二篇也是最后一篇文章中,我將深入探討Sentry 2權限模型,說明如何創建組,為其分配用戶和權限以及使用權限檢查有選擇地啟用應用程序功能。 我還將展示如何通過登錄限制和臨時用戶停用來強化應用程序,并說明如何將Sentry 2與第三方身份驗證服務(如Google和Twitter)結合使用。 進來,讓我們開始吧!

分配用戶權限

首先,出發點是:權限。 Sentry 2開箱即用地提供了一種合理的權限模型,既支持直接權限(直接分配給用戶的權限)又支持間接權限(分配給組并由該組成員的用戶繼承的權限)。

為了說明它是如何工作的,請參見清單1,其中有一個創建用戶帳戶并為其分配權限的簡單示例。

清單1.用戶權限授予
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// create user record try {$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => 'test@example.com','password' => 'guessme','first_name' => 'Test','last_name' => 'User','activated' => true,'permissions' => array('read' => 1, 'write' => 1)));} catch (Exception $e) {echo $e->getMessage(); } ?>

如清單1所示,將權限分配給用戶帳戶非常簡單:只需在傳遞給createUser()方法的數組中添加一個“ permissions”鍵,然后指定一組權限。 要分配或更改現有用戶帳戶的權限,請檢索相應的User對象,分配新的權限,然后將該對象save()到數據庫中。 權限名稱是完全可自定義的,完全可以由您定義。 分配給權限名稱的值表示是允許(1),拒絕(-1)還是繼承(0)。

清單2通過允許您另外指定用戶是否有權“查看”,“添加”,“編輯”或“刪除”其他用戶帳戶,來更新您在本文第一部分中看到的用戶帳戶創建腳本。

清單2.交互式用戶權限授予
<?php if (isset($_POST['submit'])): ?> <?php// set up autoloaderrequire ('vendor\autoload.php');// configure database$dsn = 'mysql:dbname=appdata;host=localhost';$u = 'sentry';$p = 'g39ejdl';Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// validate input and create user recordtry {$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);$fname = strip_tags($_POST['first_name']);$lname = strip_tags($_POST['last_name']);$password = strip_tags($_POST['password']);$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => $email,'password' => $password,'first_name' => $fname,'last_name' => $lname,'permissions' => $_POST['perms'],'activated' => true,));echo 'User successfully created.';} catch (Exception $e) {echo 'User could not be created. ' . $e->getMessage();} ?> <?php else: ?> <html> <head></head> <body> <h1>Add User</h2><form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">Email address: <br/><input type="text" name="email" /> <br/>Password: <br/><input type="password" name="password" /> <br/>First name: <br/><input type="text" name="first_name" /> <br/>Last name: <br/><input type="text" name="last_name" /> <br/>Permissions: <br/><input type="checkbox" name="perms[view]" value="1" />View<input type="checkbox" name="perms[add]" value="1" />Add<input type="checkbox" name="perms[edit]" value="1" />Edit<input type="checkbox" name="perms[delete]" value="1" />Delete<input type="submit" name="submit" value="Create" /></form> </body> </html> <?php endif; ?>

圖1說明了修改后的用戶帳戶創建表單的外觀。 在提交表單時,使用“權限”鍵將選中的權限分配給新創建的帳戶。

圖1.具有權限授予的帳戶創建表單

驗證用戶權限

分配權限只是難題的第一步。 在應用程序的不同位置,通常將需要檢查用戶是否具有執行特定任務所需的權限,并拒絕對缺少足夠特權的用戶進行訪問。 Sentry 2使用hasAccess()方法使此操作變得容易,該方法可讓您測試用戶是否有權訪問所需的權限。 考慮清單3,該清單修改了本文第一部分中的用戶編輯工具,以僅在登錄用戶具有相應權限的情況下顯示添加,編輯和刪除鏈接。

清單3.用戶權限檢查
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));try {$currentUser = Cartalyst\Sentry\Facades\Native\Sentry::getUser(); if (!$currentUser->hasAccess('view')) {throw new Exception ('You don\'t have permission to view this page.');}$users = Cartalyst\Sentry\Facades\Native\Sentry::findAllUsers(); ?> <html><head></head><body><h1>Users</h1><table border="1"><tr><td>Email address</td><td>First name</td><td>Last name</td><td>Last login</td></tr><?php foreach ($users as $u): ?><?php $userArr = $u->toArray(); ?><tr><td><?php echo $userArr['email']; ?></td><td><?php echo isset($userArr['first_name']) ? $userArr['first_name'] : '-'; ?></td><td><?php echo isset($userArr['last_name']) ? $userArr['last_name'] : '-'; ?></td><td><?php echo isset($userArr['last_login']) ? $userArr['last_login'] : '-'; ?></td><?php if ($currentUser->hasAccess('edit')): ?><td><a href="edit.php?id=<?php echo $userArr['id']; ?>">Edit</a></td><?php endif; ?><?php if ($currentUser->hasAccess('delete')): ?><td><a href="delete.php?id=<?php echo $userArr['id']; ?>">Delete</a></td><?php endif; ?></tr><?php endforeach; ?></table><?php if ($currentUser->hasAccess('add')): ?><a href="create.php">Add new user</a><?php endif; ?><body> </html> <?php } catch (Exception $e) {echo $e->getMessage(); } ?>

清單3設置了Sentry 2數據庫連接,然后使用getUser()方法檢索與當前登錄用戶相對應的User對象。 然后,它在各個位置使用對象的hasAccess()方法來決定用戶是否有權查看用戶帳戶列表(“視圖”)以及該列表中每個帳戶旁邊顯示的編輯鏈接(“編輯”,“刪除”或“添加”)。

清單4提供了另一個示例,該示例首先在允許刪除帳戶之前檢查登錄用戶是否具有“刪除”權限。

清單4.用戶權限檢查
<?php if (isset($_GET['id'])) {// set up autoloaderrequire ('vendor\autoload.php');// configure database$dsn = 'mysql:dbname=appdata;host=localhost';$u = 'sentry';$p = 'g39ejdl';Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));try {$currentUser = Cartalyst\Sentry\Facades\Native\Sentry::getUser(); if (!$currentUser->hasAccess('delete')) {throw new Exception ('You don\'t have permission to view this page.');}// find user by id and delete$id = strip_tags($_GET['id']); $user = Cartalyst\Sentry\Facades\Native\Sentry::findUserById($id);$user->delete();echo 'User successfully deleted.';} catch (Exception $e) {echo $e->getMessage();} } ?>

建立群組

Sentry 2還允許您將用戶分為幾組。 如果要允許不同的用戶級別使用不同的功能級別,則此功能特別有用。 組是使用createGroup()方法創建的,如清單5所示。

清單5.組創建
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// create group record try {$group1 = Cartalyst\Sentry\Facades\Native\Sentry::createGroup(array('name' => 'staff','permissions' => array('view' => 1,'add' => 0,'edit' => 1,'delete' => 0)));$group2 = Cartalyst\Sentry\Facades\Native\Sentry::createGroup(array('name' => 'managers','permissions' => array('view' => 1,'add' => 1,'edit' => 1,'delete' => 1)));} catch (Exception $e) {echo $e->getMessage(); } ?>

清單5創建了兩個新組,名為“ staff”和“ managers”。 “工作人員”組僅具有“查看”和“編輯”權限,而“管理人員”組也具有“編輯”和“刪除”權限。

組記錄存儲在“組”表中。 使用DESC命令查看此表的結構。

mysql> DESC groups;

圖2說明了此表的結構。

圖2. Sentry 2組表的結構

清單6演示了將用戶添加到組的過程。

清單6.組的用戶分配
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// create user record try {$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => 'test@example.com','password' => 'guessme','first_name' => 'Test','last_name' => 'User','activated' => true));$group = Cartalyst\Sentry\Facades\Native\Sentry::findGroupByName('managers');$user->addGroup($group); } catch (Exception $e) {echo $e->getMessage(); } ?>

將用戶添加到組是一個分為兩個步驟的過程。 首先,使用findGroupByName()方法檢索一個Group對象,然后調用User對象的addGroup()方法以將該組附加到用戶帳戶。

合并用戶和組權限

組提供了一種方便的方式來隱式分配權限給用戶。 只需將用戶分配給組,該用戶將自動繼承該組的權限。 按照清單5中的示例,屬于“ staff”組的用戶將自動繼承該組的“查看”和“編輯”權限,而屬于經理組的用戶將自動繼承該組的權限,同時還“編輯”和“刪除”權限”。

通過在創建或更新用戶帳戶時顯式指定不同的值,可以覆蓋用戶的默認組權限。 考慮清單7,它說明了這一點。

清單7.清單7:組權限覆蓋
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// create user record try {$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => 'john@example.com','password' => 'guessme','first_name' => 'John','last_name' => 'User','activated' => true,'permissions' => array('edit' => '-1')));$group = Cartalyst\Sentry\Facades\Native\Sentry::findGroupByName('managers');$user->addGroup($group); } catch (Exception $e) {echo $e->getMessage(); } ?>

在清單7中,用戶“ john@example.com”屬于“ managers”組,因此默認情況下將具有所有權限。 但是,在創建帳戶時,已明確拒絕該帳戶的“編輯”權限。 結果,用戶將僅獲得“查看”,“添加”和“刪除”權限。

清單8演示了使用getMergedPermissions()方法來檢索用戶的直接和間接合并權限。

清單8.合并的用戶和組權限
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// if form submitted if (isset($_POST['submit'])) {try {// validate input$username = filter_var($_POST['username'], FILTER_SANITIZE_EMAIL);$password = strip_tags(trim($_POST['password']));// set login credentials$credentials = array('email' => $username,'password' => $password,);// authenticate// if authentication fails, capture failure messageCartalyst\Sentry\Facades\Native\Sentry::authenticate($credentials, false); } catch (Exception $e) {$failMessage = $e->getMessage();} }// check if user logged in if (Cartalyst\Sentry\Facades\Native\Sentry::check()) {$currentUser = Cartalyst\Sentry\Facades\Native\Sentry::getUser(); } ?> <html> <head></head> <body> <?php if (isset($currentUser)): ?>Logged in as <?php echo $currentUser->getLogin(); ?>. <a href="logout.php">[Log out]</a> <br/>Permissions: <?php echo implode(', ', array_keys($currentUser->getMergedPermissions(), '1')); ?><?php else: ?><h1>Log In</h1><div><?php echo (isset($failMessage)) ? $failMessage : null; ?></div> <form method="post">Username: <input type="text" name="username" /> <br/>Password: <input type="password" name="password" /> <br/><input type="submit" name="submit" value="Log In" /></form><?php endif; ?> </body> </html>

圖3顯示了清單8中計算的“ john@example.com”權限。

圖3.用戶權限顯示

Sentry 2還提供了特殊的“超級用戶”權限,該權限用作向用戶分配“所有可用權限”的快捷方式。 清單9展示了它的運行。

清單9.超級用戶權限授予
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// create user record try {$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => 'root@example.com','password' => 'guessme','first_name' => 'Root','last_name' => 'User','activated' => true,'permissions' => array('superuser' => '1')));} catch (Exception $e) {echo $e->getMessage(); } ?>

限制用戶登錄

Sentry 2還具有一個有趣的功能,可以提高應用程序的安全性:如果登錄嘗試失敗的次數過多,則會自動限制登錄。 在這種情況下,需要了解一些有趣的方法:

  • setAttemptLimit()方法設置限制登錄前允許的最大嘗試次數。
  • setSuspensionTime()方法設置應限制登錄的分鐘數。
  • getLoginAttempts()方法檢索登錄嘗試的次數。
  • clearLoginAttempts()方法清除失敗的登錄嘗試次數,并取消掛起登錄帳戶。
  • check()方法檢索登錄的當前狀態,無論是否受到限制。
  • suspend()方法掛起登錄帳戶, unsuspend()方法將其恢復為活動狀態。
  • ban()方法禁止登錄帳戶, unBan()方法將其恢復為活動狀態。

清單10顯示了將限制添加到登錄工作流程是多么容易。

清單10.登錄限制
<?php // set up autoloader require ('vendor\autoload.php');// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// enable throttling $throttleProvider = Cartalyst\Sentry\Facades\Native\Sentry::getThrottleProvider(); $throttleProvider->enable();// if form submitted if (isset($_POST['submit'])) {try {// validate input$username = filter_var($_POST['username'], FILTER_SANITIZE_EMAIL);$password = strip_tags(trim($_POST['password']));// configure throttling$throttle = $throttleProvider->findByUserLogin($username);$throttle->setAttemptLimit(3);$throttle->setSuspensionTime(5);$credentials = array('email' => $username,'password' => $password,);Cartalyst\Sentry\Facades\Native\Sentry::authenticate($credentials, false); } catch (Exception $e) {// all other authentication failures$failMessage = $e->getMessage();} }// check if user logged in if (Cartalyst\Sentry\Facades\Native\Sentry::check()) {$currentUser = Cartalyst\Sentry\Facades\Native\Sentry::getUser(); } ?> <html> <head></head> <body> <?php if (isset($currentUser)): ?>Logged in as <?php echo $currentUser->getLogin(); ?><a href="logout.php">[Log out]</a><?php else: ?><h1>Log In</h1><div><?php echo (isset($failMessage)) ? $failMessage : null; ?></div> <form method="post">Username: <input type="text" name="username" /> <br/>Password: <input type="password" name="password" /> <br/><input type="submit" name="submit" value="Log In" /></form><?php endif; ?> </body> </html>

清單10實現了您在前面的示例中看到的標準Sentry 2登錄工作流程,但有兩個明顯的區別:

  • getThrottleProvider()方法用于檢索全局限制提供程序的實例。 此提供程序對象用作登錄限制的主要控制點。 調用對象的enable()方法將激活Sentry 2的內置限制功能。
  • 節流對象的findByUserLogin()方法用于檢索用戶節流對象的實例。 對象的setAttemptLimit()和setSuspensionTime()方法用于配置登錄限制的關鍵參數-嘗試次數和暫停時間。

如果現在嘗試使用錯誤的密碼登錄到應用程序,則在三次嘗試失敗后,您的帳戶將自動暫停五分鐘。 這對試圖通過使用字典猜測密碼的僵尸程序和自動腳本提供了可靠的響應。

與第三方網絡集成(Twitter)

如您所見,Sentry 2提供了對存儲在其自己的數據庫中的用戶進行身份驗證所需的一切。 但是,如今,您通常希望您的應用程序還支持通過第三方OAuth提供程序(例如Google,Facebook或Twitter)登錄。

Sentry Social 3是Sentry 2的一個附加組件,旨在與社交網絡集成。 但是,此組件只能在商業許可下使用,因此,它可能不是最適合您的項目的組件。 因此,另一種解決方案是使用每個第三方提供商提供的開源OAuth庫(在大多數情況下)。

放松,實際上并不像聽起來那樣復雜。 為了說明這一點,我將通過將Sentry 2與當今兩個最受歡迎的社交網絡(Twitter和Google+)集成在一起,向您展示一些不同的身份驗證和帳戶創建工作流程的示例。

如果您曾經嘗試使用Twitter,Google或Facebook憑據登錄到應用程序,則可能會注意到該應用程序能夠訪問該網絡上的帳戶詳細信息,并使用該信息預先填寫自己的注冊表格。 清單11通過使用Zend Framework 1.x中的兩個組件(特別是Zend_Oauth_Consumer和Zend_Json)來連接到Twitter API并檢索身份驗證用戶的屏幕名稱,演示了此工作流程。 然后,此信息將用于填充應用程序的本地帳戶創建表單,該表單在提交后會在Sentry 2數據庫中創建一個新的用戶帳戶。

清單11假定您在PHP包含路徑中具有Zend Framework的工作副本。 注意,在使用清單11中的代碼之前,必須首先在Twitter上注冊您的應用程序,獲取使用者密鑰和機密(圖4中的示例),然后將此信息插入到清單11中的適當位置。 請參閱相關信息的鏈接,Zend框架和用于管理應用Twitter API的開發者控制臺。

圖4. Twitter應用程序控制臺設置
清單11.使用Twitter進行用戶身份驗證和配置文件檢索
<?php session_start(); if (isset($_POST['submit'])) {// if form submitted// use input to create user accountrequire ('vendor\autoload.php');// configure database$dsn = 'mysql:dbname=appdata;host=localhost';$u = 'sentry';$p = 'g39ejdl';Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));try {$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);$fname = strip_tags($_POST['name']);$password = strip_tags($_POST['password']);$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => $email,'password' => $password,'first_name' => $fname,));echo 'User successfully created.'; } catch (Exception $e) {echo 'User could not be created. ' . $e->getMessage();}} else {// if form not submitted// connect to Twitter via Oauth// ask for user authorization and retrieve user's name via Twitter API// pre-populate account creation formrequire_once 'Zend/Loader.php';Zend_Loader::loadClass('Zend_Oauth_Consumer');Zend_Loader::loadClass('Zend_Json');$config = array('callbackUrl' => 'http://yourhost/path/to/script.php','siteUrl' => 'https://api.twitter.com/oauth','consumerKey' => 'YOUR-CONSUMER-KEY','consumerSecret' => 'YOUR-CONSUMER-SECRET');$consumer = new Zend_Oauth_Consumer($config);// get access tokenif (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {$token = $consumer->getAccessToken($_GET,unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));$_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($token);} // fetch a request tokenif (!isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {$token = $consumer->getRequestToken();$_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);$consumer->redirect();}// use access token to connect to Twitter API// decode response and retrieve user's screen name// generate form with name pre-filledif (isset($_SESSION['TWITTER_ACCESS_TOKEN'])) {$token = unserialize($_SESSION['TWITTER_ACCESS_TOKEN']);$client = $token->getHttpClient($config);$client->setUri('https://api.twitter.com/1.1/account/verify_credentials.json');$client->setMethod(Zend_Http_Client::GET);$response = $client->request(); $data = Zend_Json::decode($response->getBody()); ?><html><head></head><body> <form method="post">Name: <input type="text" name="name" value="<?php echo $data['name']; ?>" /> <br/>Email address: <input type="text" name="email" value="" /> <br/>Password: <input type="password" name="password" value="" /> <br/><input type="submit" name="submit" value="Create Account" /></form></body></html> <?php} } ?>

清單11從開始一個新的會話開始,該會話將用作在身份驗證過程中接收到的OAuth訪問和請求令牌的存儲容器。 然后,它使用Zend Framework自動加載器加載所需的類并初始化新的Zend_Oauth_Consumer對象。 然后,該代碼實現標準的OAuth工作流程,首先獲取請求令牌,然后將用戶重定向到Twitter以登錄,認證并獲取訪問令牌。

有了訪問令牌,清單11現在可以向Twitter API的/verify_credentials端點發出經過身份驗證的請求。 對此請求的響應是一個JSON文檔,其中包含簡短的用戶個人資料,包括用戶的屏幕名稱。 現在,可以很容易地解碼JSON數據,從中提取用戶的屏幕名稱,并使用此信息來預先填充帳戶創建表單。 用戶現在只需簡單地添加他或她的電子郵件地址并提交表單,這將啟動Sentry 2并使用您之前看到的createUser()方法創建一個用戶帳戶。

圖5顯示了正在進行的Twitter身份驗證的示例以及由此產生的帳戶創建表單,其中用戶的屏幕名稱已經從Twitter API中填充。

圖5. Twitter身份驗證過程

如果您想知道清單11為什么也不能用用戶的電子郵件地址預先填充帳戶創建表單,原因很簡單:Twitter不會通過其API公開電子郵件地址。 由于電子郵件地址是Sentry 2使用的主要帳戶標識符,因此用戶必須手動請求并輸入此信息才能完成帳戶創建過程。 不過,請不要擔心,這是特定于Twitter的約束,清單12(使用Google+)對此有所不同。

與第三方網絡集成(Google)

Google+作為社交網絡正變得越來越流行,并且Google還提供了PHP OAuth客戶端的可靠實現。 該客戶端可以免費下載,可以連接到所有Google API,包括Google+ API。 但是,在使用以下清單中的代碼之前,您必須首先在Google上注冊您的應用程序,獲取客戶ID和密碼,然后將此信息插入每個清單中的適當位置(圖6中的示例)。 請參閱相關信息的鏈接,谷歌PHP OAuth用戶端和谷歌的API控制臺。

圖6. Google應用程序控制臺設置

清單12提供了一個示例,該示例針對Google OAuth服務進行身份驗證,從Google+ API檢索經過身份驗證的用戶名和電子郵件地址,并使用此信息自動創建新的Sentry 2用戶帳戶。

清單12.使用Google進行用戶身份驗證和帳戶創建
<?php // load required classes require_once 'vendor/google-api-php-client/src/Google_Client.php'; require_once 'vendor/google-api-php-client/src/contrib/Google_Oauth2Service.php'; require_once 'vendor/google-api-php-client/src/contrib/Google_PlusService.php'; require_once 'vendor\autoload.php';// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// start session session_start();// initialize OAuth 2.0 client // set scopes $client = new Google_Client(); $client->setApplicationName('Project X'); $client->setClientId('YOUR-CLIENT-ID'); $client->setClientSecret('YOUR-CLIENT-SECRET'); $client->setRedirectUri('http://yourhost/path/to/script.php'); $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/plus.login' )); $oauth2Service = new Google_Oauth2Service($client); $plusService = new Google_PlusService($client);// if code received, authenticate and store token in session if (isset($_GET['code'])) {$client->authenticate();$_SESSION['token'] = $client->getAccessToken();$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));exit; }// if token available in session, set token in client if (isset($_SESSION['token'])) {$client->setAccessToken($_SESSION['token']); }// if token available in client, access API // get user name and email address // generate random password // create user in Sentry2 database and notify user with email if ($client->getAccessToken()) {$userinfo = $oauth2Service->userinfo->get();$profile = $plusService->people->get('me');$email = filter_var($userinfo['email'], FILTER_SANITIZE_EMAIL);$fname = $profile['name']['givenName'];$lname = $profile['name']['familyName'];$password = substr(md5(rand()),0,7);try { $user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => $email,'password' => $password,'first_name' => $fname,'last_name' => $lname,'activated' => true,));$body = <<<EOM Your account was successfully created. Please log in with the credentials below: Email: $email Password: $password EOM;@mail($email, 'Account created successfully', $body); } catch (Exception $e) {$failMessage = $e->getMessage();}$_SESSION['token'] = $client->getAccessToken();} else {$authUrl = $client->createAuthUrl(); } ?> <html> <head></head> <body> <?php if (isset($authUrl)): ?><a href='<?php echo $authUrl; ?>'>Register with Google+</a><?php else: ?><div><?php echo (isset($failMessage)) ? $failMessage : "Account created for '$fname $lname'. Credentials: $email / $password"; ?></div> <?php endif; ?> </body> </html>

清單12首先加載GooglePHP OAuth庫,建立Sentry 2數據庫連接并開始一個新PHP會話。 然后,它將初始化Google OAuth客戶端,設置客戶端ID和從Google API控制臺獲取的密碼,并且重要的是,定義客戶端的范圍。 最后,它初始化兩個服務對象,一個用于OAuth服務,一個用于Google+服務,并使用客戶端的createAuthUrl()方法創建一個身份驗證URL。

按照標準的OAuth工作流程,單擊身份驗證URL的鏈接會將用戶帶到Google身份驗證頁面(圖7)。 用戶對應用程序進行身份驗證并確認其有權訪問的數據之后,將生成訪問令牌并將其存儲在會話中。 通過此訪問令牌,客戶端可以訪問選定的Google API。

圖7. Google身份驗證過程

使用訪問令牌,服務對象可以獲取身份驗證用戶的配置文件信息,例如名字,姓氏和電子郵件地址。 然后,此信息與自動生成的隨機密碼結合在一起,以在Sentry 2數據庫中創建并激活新的用戶帳戶。 然后使用PHP的mail()函數將包括自動生成的密碼在內的帳戶信息通過電子郵件發送給用戶。

此方法的一種變體是從第三方網絡信息創建用戶帳戶,然后手動將用戶登錄到應用程序。 清單13是遵循此方法的清單12的修訂版。

清單13.用戶身份驗證和使用Google登錄
<?php // load required classes require_once 'vendor/google-api-php-client/src/Google_Client.php'; require_once 'vendor/google-api-php-client/src/contrib/Google_Oauth2Service.php'; require_once 'vendor/google-api-php-client/src/contrib/Google_PlusService.php'; require_once 'vendor\autoload.php';// configure database $dsn = 'mysql:dbname=appdata;host=localhost'; $u = 'sentry'; $p = 'g39ejdl'; Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver(new PDO($dsn, $u, $p));// start session session_start();// initialize OAuth 2.0 client // set scopes $client = new Google_Client(); $client->setApplicationName('Project X'); $client->setClientId('YOUR-CLIENT-ID'); $client->setClientSecret('YOUR-CLIENT-SECRET'); $client->setRedirectUri('http://yourhost/path/to/script.php'); $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/plus.login' )); $oauth2Service = new Google_Oauth2Service($client); $plusService = new Google_PlusService($client);// if code received, authenticate and store token in session if (isset($_GET['code'])) {$client->authenticate();$_SESSION['token'] = $client->getAccessToken();$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));exit; }// if token available in session, set token in client if (isset($_SESSION['token'])) {$client->setAccessToken($_SESSION['token']); }// if logout request, destroy session and revoke token if (isset($_REQUEST['logout'])) {unset($_SESSION['token']); $client->revokeToken();Cartalyst\Sentry\Facades\Native\Sentry::logout(); }// if token available in client, access API // get user name and email address // check if user present in Sentry2 database and auto-login // or create new user account and log user in if ($client->getAccessToken()) {$userinfo = $oauth2Service->userinfo->get();$profile = $plusService->people->get('me');$email = $userinfo['email'];$fname = $profile['name']['givenName'];$lname = $profile['name']['familyName'];try {try { $user = Cartalyst\Sentry\Facades\Native\Sentry::findUserByLogin($email);} catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {$password = substr(md5(rand()),0,7);$user = Cartalyst\Sentry\Facades\Native\Sentry::createUser(array('email' => $email,'password' => $password,'first_name' => $fname,'last_name' => $lname,'activated' => true,));$createdMessage = "Account created for '$fname $lname'. Credentials: $email / $password";}Cartalyst\Sentry\Facades\Native\Sentry::login($user, false); if (Cartalyst\Sentry\Facades\Native\Sentry::check()) {$currentUser = Cartalyst\Sentry\Facades\Native\Sentry::getUser();}} catch (Exception $e) {$failMessage = $e->getMessage();}$_SESSION['token'] = $client->getAccessToken();} else {$authUrl = $client->createAuthUrl(); } ?> <html> <head></head> <body> <?php if (isset($authUrl)): ?><a href='<?php echo $authUrl; ?>'>Log in with Google+</a><?php else: ?><div><?php echo (isset($failMessage)) ? $failMessage : null; ?></div> <div><?php echo (isset($createdMessage)) ? $createdMessage : null; ?></div> Logged in as <?php echo $currentUser->getLogin(); ?>. [<a href='?logout'>Log out</a>]<?php endif; ?> </body> </html>

大多數清單13中的代碼是一樣的,在清單12 。 主要區別在于,在完成Google身份驗證過程后,腳本將檢查是否已經存在具有相同電子郵件地址的Sentry 2帳戶,如果不存在,則會創建一個。 用戶帳戶出現在系統上之后,Sentry 2 login()方法用于手動進行身份驗證并將用戶登錄到應用程序。 還支持注銷工作流,該工作流將用戶從應用程序中注銷,并撤消Google API訪問令牌。

摘要

如這些示例所示,Sentry 2為PHP Web應用程序中的身份驗證和粒度訪問控制提供了功能全面的框架。 通過添加容易獲得的開源庫,可以將其與第三方社交網絡和身份驗證提供程序集成,從而以最小的開發工作量滿足各種常見用例。 下次您要構建Web應用程序時,自己嘗試一下,看看您的想法!


翻譯自: https://www.ibm.com/developerworks/opensource/library/se-sentry2/index.html

php身份證驗證

總結

以上是生活随笔為你收集整理的php身份证验证_PHP的身份验证和访问控制的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。