Hey there, fellow Ruby enthusiast! Ready to supercharge your app with some rock-solid authentication? Let's dive into integrating Auth0 into your Ruby project. Auth0 is a powerhouse when it comes to handling user authentication and authorization, and trust me, it'll make your life a whole lot easier.
Before we jump in, make sure you've got:
auth0
and jwt
gemsFirst things first, let's get our project off the ground:
mkdir auth0-ruby-api cd auth0-ruby-api bundle init
Now, crack open that Gemfile and add:
gem 'auth0' gem 'jwt'
Run bundle install
, and we're off to the races!
Head over to your Auth0 dashboard and create a new API. Jot down your API identifier and signing secret – we'll need those in a bit.
Let's create an Auth0 client:
require 'auth0' auth0_client = Auth0Client.new( client_id: ENV['AUTH0_CLIENT_ID'], client_secret: ENV['AUTH0_CLIENT_SECRET'], domain: ENV['AUTH0_DOMAIN'] )
Pro tip: Use environment variables for those sensitive credentials. Your future self will thank you!
Now, let's set up a simple Sinatra app to showcase our API:
require 'sinatra' require 'jwt' before do auth_header = request.env['HTTP_AUTHORIZATION'] if auth_header token = auth_header.split(' ').last begin @decoded_token = JWT.decode(token, ENV['AUTH0_API_SECRET'], true, { algorithm: 'HS256' }) rescue JWT::DecodeError halt 401, 'Invalid token' end else halt 401, 'No token provided' end end get '/api/protected' do 'If you're seeing this, you're authenticated!' end
To hit your shiny new endpoint, you'll need to include the access token in your request header:
require 'httparty' token = auth0_client.get_token response = HTTParty.get('http://localhost:4567/api/protected', headers: { 'Authorization' => "Bearer #{token}" } ) puts response.body
Always validate tokens on the server-side, and never trust the client. Also, keep your secrets secret – use environment variables or a secure key management system.
Don't forget to test! Here's a quick RSpec example to get you started:
require 'rspec' require 'rack/test' describe 'API' do include Rack::Test::Methods def app Sinatra::Application end it 'returns 401 without a token' do get '/api/protected' expect(last_response.status).to eq 401 end it 'returns 200 with a valid token' do header 'Authorization', "Bearer #{valid_token}" get '/api/protected' expect(last_response.status).to eq 200 end end
And there you have it! You've just built a robust Auth0 API integration in Ruby. Remember, this is just scratching the surface – Auth0 has a ton of features to explore.
Keep coding, stay curious, and may your tokens always be valid! 🚀
For more in-depth info, check out the Auth0 Ruby SDK docs and the JWT gem documentation.