Laravel authorization
Laravel authorization middleware
Trong Laravel authorization middleware, thường hay dùng session guard hoặc token guard. Session guard duy trì trạng thái các bạn trong mỗi lần request bằng cookie. Token guard xác thực các bạn bằng cách đánh giá token hợp lệ trong mỗi lần request.
Có 2 cách chính trong phân quyền, đó là Gates và Policies. Chúng ta sẽ tìm hiểu lần lượt 2 cách này.
Gate là các Closure được xác định nếu một các bạn được xác thực để thực hiện một hành động, nó được định nghĩa trong AppProvidersAuthServiceProvider dùng facade Gate.
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('update-post', function ($user, $post) {
return $user->id == $post->user_id;
});
}
Gate cũng có thể định nghĩa dùng dạng callback string giống như Controller:
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('update-post', 'PostPolicy@update');
}
Resource Gates Bạn có thể định nghĩa nhiều Gate dùng phương thức resource
Gate::resource('posts', 'PostPolicy');
Laravel authorization example
Policy là các class quản lý logic trong phân quyền liên quan đến một Model hoặc tài nguyên nào đó. Ví dụ, nếu ứng dụng của bạn là một blog, bạn có thể có một model Post và một policy là postpolicy để phân quyền các hành động các bạn như tạo hay cập nhật các bài viết. Một policy muốn dùng cần được đăng ký, AuthServiceProvider được đưa vào trong project Laravel chứa một thuộc tính policies để map Eloquent model với các policy tương ứng.
<?php namespace AppProviders; use AppPost; use AppPoliciesPostPolicy; use IlluminateSupportFacadesGate; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ Post::class => PostPolicy::class, ]; /** * Register any application authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); // } }