Ruby with Rack
The Clerk Ruby SDK provides a Rack middleware to integrate Clerk into your Rack-based application.
The Clerk Ruby SDK provides a range of backend utilities to simplify user authentication and management in your application.
- Add the following code to your application's
Gemfile
. - Run the following command to install the SDK:
The configuration object provides a flexible way to configure the SDK. When a configuration value is not explicitly provided, it will fall back to checking the corresponding environment variable. You must provide your Clerk Secret Key, which can be retrieved from the API keys page in the Clerk Dashboard.
The following example shows how to set up your configuration object:
For more information, see Faraday's documentation.
Add Clerk's Rack middleware
Add the Clerk middleware to your Rack application by updating your config.ru
file with the following code:
Access the clerk
object
Once you've added the middleware, you can access the clerk
object in your actions and views. The clerk
object provides access to the Ruby SDK's available methods.
The following example demonstrates a simple Rack application that protects all routes. If the user is authenticated, it returns the user's first name and ID. If the user is not authenticated, it returns a 401
status code.
Example: Reverification
The reverification feature provides an additional layer of security by requiring users to reverify their session before accessing sensitive routes.
There are two ways to handle reverification in a Rack application:
In your middleware
To handle reverification in your Rack middleware, use the Clerk::Rack::Reverification
middleware. It accepts an optional preset parameter to customize the reverification requirements and an optional routes
parameter to specify which routes should be protected.
In the following example, the reverification preset is set to LAX
and reverification is required for all routes that match the /*
pattern.
In your application logic
To handle reverification in your app logic,
- Use the
clerk.user_needs_reverification?
method to check if the user needs to reverify their session, which accepts an optional preset parameter to customize the reverification requirements. - Use the
clerk.user_reverification_rack_response
method to get the response.
The following example demonstrates a simple Rack application that requires authentication and reverification for all routes.
Feedback
Last updated on