溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Laravel中Auth模塊的作用是什么

發(fā)布時(shí)間:2021-01-13 16:26:27 來(lái)源:億速云 閱讀:232 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹Laravel中Auth模塊的作用是什么,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

模塊組成

Auth模塊從功能上分為用戶認(rèn)證和權(quán)限管理兩個(gè)部分;從文件組成上,Illuminate\Auth\Passwords目錄下是密碼重置或忘記密碼處理的小模塊,Illuminate\Auth是負(fù)責(zé)用戶認(rèn)證和權(quán)限管理的模塊,Illuminate\Foundation\Auth提供了登錄、修改密碼、重置密碼等一系統(tǒng)列具體邏輯實(shí)現(xiàn);

下圖展示了Auth模塊各個(gè)文件的關(guān)系,并進(jìn)行簡(jiǎn)要說(shuō)明;

Laravel中Auth模塊的作用是什么

用戶認(rèn)證

HTTP本身是無(wú)狀態(tài),通常在系統(tǒng)交互的過(guò)程中,使用賬號(hào)或者Token標(biāo)識(shí)來(lái)確定認(rèn)證用戶;

配置文件解讀

return [
 'defaults' => [
 'guard' => 'web',
 ...
 ],
 'guards' => [ 
 'web' => [
  'driver' => 'session',
  'provider' => 'users',
 ],
 'api' => [ 
  'driver' => 'token', 
  'provider' => 'users',
 ],
 ],
 'providers' => [
 'users' => [
  'driver' => 'eloquent',
  'model' => App\User::class,
 ], 
 ],
], 
];

從下往上,理解;

  • providers是提供用戶數(shù)據(jù)的接口,要標(biāo)注驅(qū)動(dòng)對(duì)象和目標(biāo)對(duì)象;此處,鍵名users是一套provider的名字,采用eloquent驅(qū)動(dòng),modal是App\User::class;

  • guards部分針對(duì)認(rèn)證管理部分進(jìn)行配置;有兩種認(rèn)證方式,一種叫web,還有一種是api;web認(rèn)證是基于Session交互,根據(jù)sessionId獲取用戶id,在users這個(gè)provider查詢出此用戶;api認(rèn)證是基于token值交互,也采用users這個(gè)provider;

  • defaults項(xiàng)顯示默認(rèn)使用web認(rèn)證;

認(rèn)證

Session綁定認(rèn)證信息:

// $credentials數(shù)組存放認(rèn)證條件,比如郵箱或者用戶名、密碼
// $remember 表示是否要記住,生成 `remember_token`
public function attempt(array $credentials = [], $remember = false) 
 
public function login(AuthenticatableContract $user, $remember = false)
 
public function loginUsingId($id, $remember = false)

HTTP基本認(rèn)證,認(rèn)證信息放在請(qǐng)求頭部;后面的請(qǐng)求訪問(wèn)通過(guò)sessionId;

public function basic($field = 'email', $extraConditions = [])

只在當(dāng)前會(huì)話中認(rèn)證,session中不記錄認(rèn)證信息:

public function once(array $credentials = [])

public function onceUsingId($id)

public function onceBasic($field = 'email', $extraConditions = [])

認(rèn)證過(guò)程中(包括注冊(cè)、忘記密碼),定義的事件有這些:

事件名描述
Attempting嘗試驗(yàn)證事件
Authenticated驗(yàn)證通過(guò)事件
Failed驗(yàn)證失敗事件
Lockout失敗次數(shù)超過(guò)限制,鎖住該請(qǐng)求再次訪問(wèn)事件
Logi通過(guò)‘remember_token'成功登錄時(shí),調(diào)用的事件
Logout用戶退出事件
Registered用戶注冊(cè)事件

還有一些其他的認(rèn)證方法:

  • 檢查是否存在認(rèn)證用戶:Auth::check()

  • 獲取當(dāng)前認(rèn)證用戶:Auth::user()

  • 退出系統(tǒng):Auth::logout()

密碼處理

配置解讀

return [
 'defaults' => [
  'passwords' => 'users',
  ...
 ],
 
 'passwords' => [
  'users' => [
   'provider' => 'users',
   'table' => 'password_resets',
   'expire' => 60,
  ],
 ],
]

從下往上,看配置;

  • passwords數(shù)組是重置密碼的配置;users是配置方案的別名,包含三個(gè)元素:provider(提供用戶的方案,是上面providers數(shù)組)、table(存放重置密碼token的表)、expire(token過(guò)期時(shí)間)

  • default 項(xiàng)會(huì)設(shè)置默認(rèn)的 passwords 重置方案;

重置密碼的調(diào)用與實(shí)現(xiàn)

先看看Laravel的重置密碼功能是怎么實(shí)現(xiàn)的:

public function reset(array $credentials, Closure $callback) {
 // 驗(yàn)證用戶名、密碼和 token 是否有效
 $user = $this->validateReset($credentials);

 if (! $user instanceof CanResetPasswordContract) {
   return $user;
 } 
 
 $password = $credentials['password'];
 // 回調(diào)函數(shù)執(zhí)行修改密碼,及持久化存儲(chǔ)
 $callback($user, $password);
 // 刪除重置密碼時(shí)持久化存儲(chǔ)保存的 token
 $this->tokens->delete($user);

 return static::PASSWORD_RESET;
}

再看看Foundation\Auth模塊封裝的重置密碼模塊是怎么調(diào)用的:

// 暴露的重置密碼 API
public function reset(Request $request) {
 // 驗(yàn)證請(qǐng)求參數(shù) token、email、password、password_confirmation
 $this->validate($request, $this->rules(), $this->validationErrorMessages());
 // 調(diào)用重置密碼的方法,第二個(gè)參數(shù)是回調(diào),做一些持久化存儲(chǔ)工作
 $response = $this->broker()->reset(
  $this->credentials($request), function ($user, $password) {
  $this->resetPassword($user, $password);
  }
 );
 // 封裝 Response
 return $response == Password::PASSWORD_RESET
  ? $this->sendResetResponse($response)
  : $this->sendResetFailedResponse($request, $response);
}

// 獲取重置密碼時(shí)的請(qǐng)求參數(shù)
protected function credentials(Request $request) {
 return $request->only(
  'email', 'password', 'password_confirmation', 'token'
 );
}

// 重置密碼的真實(shí)性驗(yàn)證后,進(jìn)行的持久化工作
protected function resetPassword($user, $password) {
 // 修改后的密碼、重新生成 remember_token
 $user->forceFill([
  'password' => bcrypt($password),
  'remember_token' => Str::random(60),
 ])->save();
 // session 中的用戶信息也進(jìn)行重新賦值          
 $this->guard()->login($user);
}

“忘記密碼 => 發(fā)郵件 => 重置密碼” 的大體流程如下:

  • 點(diǎn)擊“忘記密碼”,通過(guò)路由配置,跳到“忘記密碼”頁(yè)面,頁(yè)面上有“要發(fā)送的郵箱”這個(gè)字段要填寫;

  • 驗(yàn)證“要發(fā)送的郵箱”是否是數(shù)據(jù)庫(kù)中存在的,如果存在,即向該郵箱發(fā)送重置密碼郵件;

  • 重置密碼郵件中有一個(gè)鏈接(點(diǎn)擊后會(huì)攜帶 token 到修改密碼頁(yè)面),同時(shí)數(shù)據(jù)庫(kù)會(huì)保存這個(gè) token 的哈希加密后的值;

  • 填寫“郵箱”,“密碼”,“確認(rèn)密碼”三個(gè)字段后,攜帶 token 訪問(wèn)重置密碼API,首頁(yè)判斷郵箱、密碼、確認(rèn)密碼這三個(gè)字段,然后驗(yàn)證 token是否有效;如果是,則重置成功;

權(quán)限管理

權(quán)限管理是依靠?jī)?nèi)存空間維護(hù)的一個(gè)數(shù)組變量abilities來(lái)維護(hù),結(jié)構(gòu)如下:

$abilities = array(
 '定義的動(dòng)作名,比如以路由的 as 名(common.dashboard.list)' => function($user) {
  // 方法的參數(shù),第一位是 $user, 當(dāng)前 user, 后面的參數(shù)可以自行決定
  return true; // 返回 true 意味有權(quán)限, false 意味沒有權(quán)限
 },
 ......
);

但只用 $abilities,會(huì)使用定義的那部分代碼集中在一起太煩索,所以有policy策略類的出現(xiàn);

policy策略類定義一組實(shí)體及實(shí)體權(quán)限類的對(duì)應(yīng)關(guān)系,比如以文章舉例:

有一個(gè) Modal實(shí)體類叫 Post,可以為這個(gè)實(shí)體類定義一個(gè)PostPolicy權(quán)限類,在這個(gè)權(quán)限類定義一些動(dòng)作為方法名;

class PostPolicy {
 // update 權(quán)限,文章作者才可以修改
 public function update(User $user, Post $post) {
  return $user->id === $post->user_id;
 }
}

然后在ServiceProvider中注冊(cè),這樣系統(tǒng)就知道,如果你要檢查的類是Post對(duì)象,加上你給的動(dòng)作名,系統(tǒng)會(huì)找到PostPolicy類的對(duì)應(yīng)方法;

protected $policies = [
 Post::class => PostPolicy::class,
];

怎么調(diào)用呢?

對(duì)于定義在abilities數(shù)組的權(quán)限:

  • 當(dāng)前用戶是否具備common.dashboard.list權(quán)限:Gate::allows('common.dashboard.list')

  • 當(dāng)前用戶是否具備common.dashboard.list權(quán)限:! Gate::denies('common.dashboard.list')

  • 當(dāng)前用戶是否具備common.dashboard.list權(quán)限:$request->user()->can('common.dashboard.list')

  • 當(dāng)前用戶是否具備common.dashboard.list權(quán)限:! $request->user()->cannot('common.dashboard.list')

  • 指定用戶是否具備common.dashboard.list權(quán)限:Gate::forUser($user)->allows('common.dashboard.list')

對(duì)于policy策略類調(diào)用的權(quán)限:

  • 當(dāng)前用戶是否可以修改文章(Gate 調(diào)用):Gate::allows('update', $post)

  • 當(dāng)前用戶是否可以修改文章(user 調(diào)用):$user->can('update', $post)

  • 當(dāng)前用戶是否可以修改文章(用幫助函數(shù)):policy($post)->update($user, $post)

  • 當(dāng)前用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorize('update', $post);

  • 當(dāng)前用戶是否可以修改文章(Controller 類同名方法中調(diào)用):$this->authorize($post);

  • 指定用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorizeForUser($user, 'update', $post);

有用的技巧

獲取當(dāng)前系統(tǒng)注冊(cè)的權(quán)限,包括兩部分abilities和policies數(shù)組內(nèi)容,代碼如下:

$gate = app(\Illuminate\Contracts\Auth\Access\Gate::class);
$reflection_gate = new ReflectionClass($gate);

$policies = $reflection_gate->getProperty('policies');
$policies->setAccessible(true);
// 獲取當(dāng)前注冊(cè)的 policies 數(shù)組
dump($policies->getValue($gate));
                          
$abilities = $reflection_gate->getProperty('abilities');          
$abilities->setAccessible(true);
// 獲取當(dāng)前注冊(cè)的 abilities 數(shù)組
dump($abilities->getValue($gate));

關(guān)于Laravel中Auth模塊的作用是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI