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

Tinh giản Authentication trong Ruby on Rails với Auth0: Hướng dẫn cho người mới

Từ custom-made đến plug-and-play authentication, Ruby developers có plenty choices ngày nay. Tuy nhiên, như bạn biết, building own solution có thể costly và dangerous. Nếu Devise là de facto standard cho most teams, alternative có thể simplify lives của most.

Bài này cover setup và use Auth0 trong Ruby on Rails application, bao gồm everything you need to get going properly, từ handling roles đến relying on multiple providers authenticate users.

Getting Started

Đây là what we need to get started:

  • Auth0 account
  • Ruby on Rails application (version 7.x onwards)

Auth0 là third-party authentication service với free tier cho up to 7,000 users. Đó plenty để get started, và pricing reasonable nếu cần advanced features.

Configuring Our Ruby App trong Auth0

Vì application sẽ rely on Auth0 authenticate users through redirects và calls, phải ensure it stays secure.

Trong Auth0 account, hãy create application within tenant. Bạn create multiple tenants in account để separate:

  • Domain names.
  • Different environments (development, production, etc).
  • Country hoặc region within which data stored.

Once created first tenant, bạn build application. That's where we start.

Head to "Settings" tab in application panel. Cần copy paste following và save to safe place:

  • Domain name: app-name.[eu,us,..].auth0.com
  • Client's ID
  • Client's Secret

Cũng phải fill in following Application URIs. Dùng these values cho local development setup:

  • Allowed Callback URLs: https://localhost:3000/auth/auth0/callback (URL Auth0 redirect to sau authentication).
  • Allowed Logout URLs: https://localhost:3000 (URL Auth0 redirect to sau logout).

Hãy configure our app.

Preparing Our Ruby on Rails Application

Bạn start với vanilla Ruby on Rails application dùng rails new command.

Hãy generate one relies on SQLite3 cho database và Tailwind cho CSS library. Skip mini-test installation và name application "Auth0 article":


Create User model với just a few attributes:


Đây build simple but efficient base cho application.

Adding Auth0 Gem to the App

Cần omniauth-auth0 và omniauth-rails_csrf_protection để dùng Auth0 trong Ruby on Rails application.


Configuring Auth0

Cần create tiny configuration file (config/auth0.yml) store credentials trong development environment.


Cũng rely on environment variables here bằng some erb:


Tất nhiên, rely on Ruby on Rails credentials ensures things stay more up-to-date.

File này dùng trong Auth0 initializer (config/initializers/auth0.rb), chúng ta now create:


Như bạn thấy, dùng Rails.application.config_for load content của YAML file as convenient hash. Chúng ta could replace this với any secret handling library, bao gồm Rails encrypted credentials storage.

Note following:

  • Provider name (:auth0)
  • Ba items từ YAML file, read và used through AUTH0_CONFIG hash.
  • callback_path key và value, matching one configured in Auth0 interface.
  • authorize_params và scope key inside it; we will come back to that later.

Cần create interface và routing elements cho authentication.

Setting Up Routes và UI với Tailwind

Trong example này, work với Ruby on Rails application dùng version 7.1 với TailwindCSS.

Dùng command sau:


Chúng ta add two controllers với index action, preparing test authentication process:


Với hai commands đó, following created:

  • Cả public_controller.rb và private_controller.rb controllers, với index action ready to use
  • Both related routes
  • Related views

Hãy add Auth0 controller handle callbacks và failures. Create controller file (bin/rails g controller auth0) và add following:


Then update routes dùng those three actions:


Và add Login và Logout buttons trong public và private views, respectively:


Bây giờ go to 'https://localhost:3000'. Dùng Login button và redirected to private page. There, tìm Logout button.

A couple of things missing, though:

  • Data từ user's profile
  • Identifying user và handling authorization

Working with Scopes và Data

Hãy take few steps back bring back initializer (config/initializers/auth0.rb):


Critical piece here là scope: openid profile. Điều này tells Auth0 we interested in few pieces of information, namely:

  • Provider name (Auth0)
  • uid: Unique identifier match user
  • info hash: Chứa name, URL to profile picture, và empty 'email' key
  • extra_info hash: Lại name và profile picture, nhưng cũng pair given và family names

Read more on scopes trong Auth0's documentation.

Thông tin trên valuable, và bạn should ensure, at least upon first login, copy data đó into table in your application.

Để do so, cần use content của request-response trong auth0_controller và, specifically, trong callback action:


Dùng breakpoint before redirect để dig into hash và experiment.

Thường want email address too. Để get it, update scope:


Sau reload application server và go through login steps, bạn need give application access to additional information.

Chúng ta now do something like this in callback action:


Điều này ensure we have local, up-to-date profile cho user.

A Word On Sessions

Session là special hash trong Ruby on Rails application. Nó có limited storage accessible từ controllers và views và unique to each visitor.

Chúng ta "open" và "close" sessions. Nếu cần specific dataset, decide session open. Nếu no data, then closed.

Remember following lines in Auth0 controller:


First one writes value in raw_info key of hash to session hash, second just clears up session hash.

Chúng ta then define following helper method in ApplicationHelper:


A Security Concern

Bây giờ dùng this as concern cho controllers. Idea là define controller require users logged in to access it, như private_controller.

Chúng ta write following concern file:


Chúng ta then use it in controllers like so:


Nếu visitor not logged in, but try open /private/index page, automatically redirected to site's root.

Integrating with Other Providers

Bạn rely on multiple providers through Auth0. Tuy nhiên, Google defined as default. Cho many companies, that's enough.

Nếu need more providers, head to Authentication menu cho related tenant in Auth0, then Social submenu, nơi setup additional providers.

Cũng worth noting bạn configure multi-factor authentication (MFA) với Auth0 too.

Process remains same except those configuration steps. Application only return visitor data prove visitor authenticated.

Opening Up Towards Authorization

Bây giờ authenticate users và send information to application through callback. Đã seen how get user's email out of hash và find relevant user in database.

From there, define authorization policies.

Pundit great choice define và use authorization policies, yet relies on checking user's role.

Dùng role attribute là easiest method. Bạn fill it khi create user in Rails console hoặc application's back-end interface, before user's first login attempt.

Hoặc get list of admins' emails và match user's email against list khi create user.


Và that's it!

What We've Covered

Trong article này, chúng ta set up:

  • Tenant và application trong Auth0
  • Auth0-related gems trong Ruby on Rails application
  • Routes và views trong application

Chúng ta then:

  • Reviewed concept of session và saw how to use it
  • Created base tooling check if user logged in
  • Added controller concern secure controllers behind login requirement
  • Saw how match users to their roles

Auth0 và other authentication providers giúp integrate state-of-the-art authentication trong Ruby on Rails application without writing much code. Thường much better option than relying on own implementation của authentication layer hoặc even dùng gems như Devise.

Happy coding!

P.S. Nếu bạn muốn đọc Ruby Magic posts ngay khi off the press, subscribe Ruby Magic newsletter và never miss a single post!

Tinh giản Authentication trong Ruby on Rails với Auth0: Hướng dẫn cho người mới

Thomas Riboulet

Tác giả khách Thomas là Consultant Backend và Cloud Infrastructure Engineer based in France. Hơn 13 năm, anh worked with startups và companies scale teams, products, và infrastructure. Anh cũng been published several times in France's GNU/Linux magazine và on his blog.

Tất cả bài viết của Thomas Riboulet