Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Thành Thạo Action Policy trong Ruby on Rails: Hướng Dẫn Thực Tế Cho Authorization An Toàn

Để giữ app của bạn an toàn, bạn cần kiểm soát ai và cái gì có thể truy cập nó. Access control có thể phân loại thành authentication — "ai" được phép — và authorization — "cái gì" họ có thể truy cập.

Authentication là chủ đề cho ngày khác, nhưng khi nói đến user authorization, bạn nói chung có hai cách: dùng role-based hoặc resource-based strategy.

Trong series hai phần này, chúng ta sẽ deep dive vào việc dùng Action Policy gem cho một Ruby on Rails blog application.

Trong phần này, chúng ta sẽ cover basics của Action Policy.

Hãy bắt đầu!

Prerequisites

  • Ruby (chúng ta dùng version 3.2.2)
  • Rails (dùng version 7.0.7)
  • Một chút kinh nghiệm dùng Ruby

Hãy đi vào việc bằng cách đầu tiên định nghĩa resource-based authorization.

Resource-Based Authorization Là Gì?

Trong khi role-based authorization tập trung vào setting user permissions theo predefined user roles, resource-based authorization enforce access bằng cách setting rules trên actual resources trong ứng dụng. Mỗi resource được associate với một policy explicitly định nghĩa những gì user có thể làm trên resource đó.

Dù bài viết này tập trung vào resource-based authorization, biết differences giữa hai authorization strategies có nghĩa là bạn better equipped để biết cái nào làm được gì.

Khi Nào Dùng Role-Based Authorization

Bạn nên dùng role-based authorization cho:

  • Simple applications - Nếu bạn làm việc trên app với permissions system đơn giản và ít user roles, thì role-based authorization strategy có thể work cho bạn.
  • Well-defined user groups - Nếu app của bạn có well-defined user groups như "admins", "editors", "writers", v.v., hãy dùng role-based authorization vì nó handle access control ở user role level.

Khi Nào Dùng Resource-Based Authorization

Resource-based authorization great cho:

  • Dynamic hoặc complex access control - Khi authorization needs của ứng dụng evolve frequently hoặc được determined bởi dynamic conditions, thì resource-based authorization system làm better choice.
  • Fine-grained control - Hữu ích khi bạn cần allow hoặc deny access đến resources dựa trên multiple conditions (ví dụ, Rails helpdesk app nơi users submit support tickets dựa trên list of dynamic categories). Giả sử support staff được assign tickets by category, đây là scenario nơi resource-based authorization would really shine.
  • Object-oriented control - Vì resource-based authorization xảy ra ở object level, defining complex object-oriented rules dễ dàng hơn khi bạn dùng resource-based authorization techniques.

Đó nói, dù bạn chọn giữa role-based và resource-based authorization sẽ depend on unique characteristics của ứng dụng.

Hãy chuyển attention sang Action Policy gem.

Action Policy Gem cho Ruby và Rails

Action Policy là flexible, extensible, và performant authorization framework cho Ruby và Rails apps. Nó uses multiple caching strategies out of the box, making it very fast, đặc biệt nếu authorization rules của bạn require database queries.

Feature khác làm cho gem này ideal cho building resource-based rules là ability to be customized. Nó provides several Ruby classes và modules that can be combined in many ways. You can pretty much set fine-grained access control rules beyond Rails controller, anywhere in your app.

Check out Action Policy project homepage để learn more.

Bây giờ hãy go over Rails app chúng ta sẽ build hôm nay.

Tạo Rails App

Moving forward, chúng ta sẽ reference một Rails 7 blog application nơi users có thể Create, Read, Update, và Delete (CRUD) posts.

Chúng ta sẽ progressively define một action policy cho model Post mà offer resource-based access control. Bạn sẽ learn how to use Action Policy để make access control strategy này work.

Go ahead và generate new Rails application:


Note: Chúng ta sẽ dùng Pico CSS styles cho example app, nhưng bạn có thể dùng whatever you like.

Sau đó quickly scaffold một Post resource mà chúng ta sẽ dùng throughout the rest of the tutorial:


Bây giờ run migration với rails db:migrate.

Setting up User Authentication

Bقدر này bài viết là về user authorization, có điều important chúng ta cần cover: user authentication. Without it, bất kỳ authorization policies nào chúng ta try to define later on sẽ useless. But there is no need to write authentication from scratch. Let's use Devise.

Installing Devise

Begin by adding Devise gem to your Gemfile:


Then install it và generate a User model:


Also, remember to add config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } to the app's development configuration.

Next up, let's implement a few basic user roles để test different user access scenarios cho Post resource.

Defining Basic User Roles

First, add role column to the user table. Run this command to generate a migration:


Note: Chúng ta dùng integer data type cho role, so we can use an enum — a quick and easy way to implement roles.

Now run migration với rails db:migrate, then open up User model và edit it:


With that done, let's shift our focus to installing Action Policy.

Setting up Action Policy cho Ruby và Rails

Open app's Gemfile và add line below:


Then run command bundle install to install Action Policy.

Finalize installation by running:


This should give us a base — ApplicationPolicy class under app/policies:


Basic Usage of Action Policy

Core foundation của Action Policy là một policy class, ApplicationPolicy, nơi bạn có thể define global configurations từ đó all policies can inherit. A good recommendation là place all policies under app/policies, và separate policies according to resources in your app. For example, nếu bạn có Post resource, corresponding policy should be PostPolicy, CommentPolicy would accompany a Comment resource, và so forth.

One more thing to consider khi working with Action Policy: rule definitions must happen within public methods in policy classes. Using a private method will raise an error.

Moving on, let's use this information to create a PostPolicy nơi chúng ta sẽ progressively build various levels of user access.

Creating Our First Policy

Create a new file named post_policy.rb under app/policies:


Here, we define a simple rule on the Post resource declaring that anyone can access a Post.

Associating Posts to Users

To work with this new post policy, we need to modify the Post resource we generated earlier so that it's associated with a logged-in user on creation (by adding a user_id column to the posts table):


Then run migration with rails db:migrate.

Next, we need to modify the posts controller to account for this change. First, let's add user_id to the allowed post_params:


Then modify the create action:


Next, let's secure the PostsController.

Implementing Authorization in Controllers

We need to modify the PostsController with a callback to only allow access to logged-in users:


Next, let's use the new Post policy to add some basic user access controls:


Here, we define an access rule on the posts controller's update và destroy actions. We specify that a post's author (or a user with the "author" role) can update a post, but only a post's author can delete a post.

Quick tip: Action Policy can reference the current_user provided by Devise và assign it to a user within the policy.

Next, we need to use the access rule in the posts controller like so:


With the access rule applied to the posts controller, our next course of action is to ensure the views are protected.

Protecting Views with Authorization

Trong screenshot dưới đây, một user với email <user2@example.com> và "reader" role đang logged in. Như bạn thấy, user này can view the post created by <user@example.com>, và they even have access to the edit and delete links cho post này. This is not ideal — the edit and delete links should only be available to the post's author.

Thành Thạo Action Policy trong Ruby on Rails: Hướng Dẫn Thực Tế Cho Authorization An Toàn

Our first task will be to remove access to these links for users that aren't authors of a post. Since we've already defined this access rule, we only need to apply it to the show view using Action Policy's nifty allowed_to? method:


With this rule applied, we can now refresh the post's show page and see what we get:

Thành Thạo Action Policy trong Ruby on Rails: Hướng Dẫn Thực Tế Cho Authorization An Toàn

The same user who had access is now limited in what they can do while on a post's view.

Kết Thúc

In the first part of this two-part series, we've learned some of the basics around the authorization gem Action Policy.

In the second and final part, we'll explore some more advanced use cases.

Happy coding!

P.S. Nếu bạn muốn đọc các bài Ruby Magic ngay khi chúng ra mắt, hãy subscribe newsletter Ruby Magic của chúng tôi và không bao giờ bỏ lỡ bất kỳ bài viết nào!