OAuth

suggest change

OAuth 2.0 (RFC 6749) is a protocol for delegated authorization. It lets a user allow your application to act on their behalf at another service without giving you their password. "Let this app read my GitHub repositories" and "Log in with Google" are both OAuth. The user logs in at the provider, approves the request, and your app gets an access token: a credential limited to certain permissions (scopes) and a limited lifetime.

OAuth defines four roles:

Role Example
Resource owner the user, Alice
Client your Ruby app
Authorization server GitHub's or Google's login and token endpoints
Resource server the API that accepts the access token, e.g. api.github.com

OAuth itself only says what the app may do. It doesn't say who the user is. OpenID Connect (OIDC) is a thin layer on top that adds an ID token, a signed JWT describing the user. "Log in with X" buttons use OIDC or a provider-specific profile API.

The current best practice, gathered in the OAuth 2.1 draft and RFC 9700, boils down to a short list of flows (grants):

Grant Use it for User involved
Authorization code + PKCE web apps, SPAs, mobile and desktop apps yes
Client credentials server-to-server calls, cron jobs no
Refresh token getting a new access token without asking the user again no
Device authorization TVs and CLIs without a browser yes, on another device
Implicit, password deprecated, don't use

The examples were run with Ruby 4.0, oauth2 2.0, omniauth 2.1, omniauth-oauth2 1.9, jwt 3.3, Sinatra 4.2, Puma 8 and rack-test 2.2:

gem install oauth2 omniauth omniauth-oauth2 jwt sinatra puma rack-test

So that every example can be run without registering an app at GitHub or Google, they talk to a small OAuth provider written in Sinatra, provider.rb, which is listed in full at the end of this article. Provider.boot! starts it on a random local port and returns its URL. Against a real provider you only change the URLs, the client id and the secret.

See Authentication for an overview of login methods, and Sessions for keeping a user logged in after OAuth has told you who they are.

Registering a client

Before writing any code you register your app with the provider (GitHub: Settings → Developer settings → OAuth Apps; Google: Cloud Console → Credentials). You get:

Keep the id and secret in environment variables (see Environment variables), never in the repository.

The authorization code flow by hand

The flow has two halves. In the front channel, the user's browser goes to the provider and comes back with a short-lived code. In the back channel, your server swaps that code for tokens, authenticating with its client secret. The access token never passes through the browser.

PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixie") ties the two halves together. The client makes up a random code_verifier, sends its SHA-256 hash (code_challenge) with the first request, and the verifier itself with the second. Someone who steals the code from a redirect can't use it without the verifier. PKCE is required for public clients and recommended for all.

The state parameter protects your callback from CSRF: you put a random value in the user's session and reject a callback whose state doesn't match. Without it, an attacker could make the victim's browser complete a login with the attacker's code and account.

Here is the whole flow with only net/http, so you can see every request (the HTTP client article covers Net::HTTP itself):

require 'net/http'
require 'securerandom'
require 'digest'
require 'base64'
require 'json'
require 'openssl'
require_relative 'provider'

AUTH_SERVER  = Provider.boot!
CLIENT_ID    = 'demo-app'
CLIENT_SECRET = 'demo-secret'
REDIRECT_URI = 'http://localhost:4567/callback'

# 1. Before redirecting the user, create a state value and a PKCE pair
state         = SecureRandom.urlsafe_base64(16)
code_verifier = SecureRandom.urlsafe_base64(48) # 64 chars, allowed: 43..128
code_challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(code_verifier), padding: false)
# A web app keeps state and code_verifier in the user's session

authorize_url = URI("#{AUTH_SERVER}/authorize")
authorize_url.query = URI.encode_www_form(
  response_type: 'code',
  client_id: CLIENT_ID,
  redirect_uri: REDIRECT_URI,
  scope: 'profile',
  state: state,
  code_challenge: code_challenge,
  code_challenge_method: 'S256'
)
puts authorize_url.to_s.sub(AUTH_SERVER, '<server>')

# 2. The user logs in at the provider. We play the browser and submit the login form.
form = URI.decode_www_form(authorize_url.query).to_h.merge('username' => 'alice', 'password' => 's3cret')
res = Net::HTTP.post_form(URI("#{AUTH_SERVER}/authorize"), form)
puts "#{res.code} -> #{res['location'][0, 60]}..."

# 3. The browser follows the redirect to our callback with ?code=...&state=...
callback = URI.decode_www_form(URI(res['location']).query).to_h
raise 'state mismatch: possible CSRF' unless
  OpenSSL.secure_compare(callback['state'], state)

# 4. Exchange the code for tokens, server to server
token_uri = URI("#{AUTH_SERVER}/token")
req = Net::HTTP::Post.new(token_uri)
req.basic_auth(CLIENT_ID, CLIENT_SECRET)
req.set_form_data(grant_type: 'authorization_code', code: callback['code'],
                  redirect_uri: REDIRECT_URI, code_verifier: code_verifier)
res = Net::HTTP.start(token_uri.host, token_uri.port) { |http| http.request(req) }
tokens = JSON.parse(res.body)
puts "#{res.code} #{tokens.keys}"
puts "token_type=#{tokens['token_type']} expires_in=#{tokens['expires_in']} scope=#{tokens['scope']}"

# 5. Call the API with the access token
api = URI("#{AUTH_SERVER}/api/profile")
res = Net::HTTP.get_response(api, 'Authorization' => "Bearer #{tokens['access_token']}")
puts "#{res.code} #{res.body}"

# The code is single use: replaying it fails
res = Net::HTTP.start(token_uri.host, token_uri.port) { |http| http.request(req) }
puts "#{res.code} #{res.body}"
<server>/authorize?response_type=code&client_id=demo-app&redirect_uri=http%3A%2F%2Flocalhost%3A4567%2Fcallback&scope=profile&state=ojrhH0jbtjqns1TvqY_HCQ&code_challenge=0E3C9_QwAQxB7B7iG6me1mlrfbij-3CtP3ETs4XOjP8&code_challenge_method=S256
303 -> http://localhost:4567/callback?code=zki-Q75eKbxdA9cqD7v2oO7Y...
200 ["access_token", "token_type", "expires_in", "scope", "refresh_token"]
token_type=Bearer expires_in=3600 scope=profile
200 {"sub":"1001","email":"alice@example.com"}
400 {"error":"invalid_grant","error_description":"unknown or used code"}

The steps in a real web app:

  1. A GET /login handler generates state and code_verifier, stores them in the session, and redirects the browser to the authorize URL.
  2. The provider shows its login and consent page. You never see the password.
  3. The provider redirects to your redirect_uri with code and state. Your callback handler checks state against the session.
  4. The handler POSTs the code, the same redirect_uri and the code_verifier to the token endpoint, authenticating with HTTP Basic (client_id:client_secret).
  5. The JSON response has access_token, token_type (always Bearer in practice), expires_in in seconds, the granted scope and usually a refresh_token. The app sends the access token as Authorization: Bearer ....

If the user clicks "Deny", the provider redirects with ?error=access_denied&state=... instead of a code, so check for error in the callback too.

The oauth2 gem

The oauth2 gem wraps the token endpoint, error parsing, refreshing and authenticated requests. It is built on Faraday:

require 'oauth2'
require 'securerandom'
require 'digest'
require 'base64'
require_relative 'provider'

AUTH_SERVER = Provider.boot!

client = OAuth2::Client.new(
  'demo-app', 'demo-secret',
  site: AUTH_SERVER,
  authorize_url: '/authorize',
  token_url: '/token',
  auth_scheme: :basic_auth # send client credentials in the Authorization header
)
redirect_uri = 'http://localhost:4567/callback'

state    = SecureRandom.urlsafe_base64(16)
verifier = SecureRandom.urlsafe_base64(48)
challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)

url = client.auth_code.authorize_url(
  redirect_uri: redirect_uri, scope: 'profile', state: state,
  code_challenge: challenge, code_challenge_method: 'S256'
)
puts url.sub(AUTH_SERVER, '<server>')

# --- the user logs in; we simulate the browser as before ---
login = Faraday.post("#{AUTH_SERVER}/authorize",
                     URI.decode_www_form(URI(url).query).to_h.merge(username: 'alice', password: 's3cret'))
params = URI.decode_www_form(URI(login.headers['location']).query).to_h
raise 'state mismatch' unless OpenSSL.secure_compare(params['state'], state)

# --- back in our callback ---
token = client.auth_code.get_token(params['code'], redirect_uri: redirect_uri,
                                                   code_verifier: verifier)
puts token.class
puts "expires_in=#{token.expires_in} expired?=#{token.expired?} refresh?=#{!token.refresh_token.nil?}"
puts "scope=#{token.params['scope']}"

# AccessToken#get/post/... add the Authorization header for you
res = token.get('/api/profile')
puts "#{res.status} #{res.parsed.to_h}"

# Refresh: returns a new AccessToken (the provider rotates the refresh token)
fresh = token.refresh!
puts "new access token: #{fresh.token != token.token}, new refresh token: #{fresh.refresh_token != token.refresh_token}"

# The old refresh token was single use
begin
  token.refresh!
rescue OAuth2::Error => e
  puts "#{e.class}: #{e.code} - #{e.description}"
  puts "HTTP #{e.response.status}"
end

# Persist tokens between runs: to_hash / from_hash
saved = fresh.to_hash
puts saved.keys.inspect
restored = OAuth2::AccessToken.from_hash(client, saved)
puts restored.get('/api/profile').parsed['email']
<server>/authorize?client_id=demo-app&code_challenge=7aGlJPX2PiL-8iWhrmfsuARwtgDTzVgl0WW5Tc4pI0Y&code_challenge_method=S256&redirect_uri=http%3A%2F%2Flocalhost%3A4567%2Fcallback&response_type=code&scope=profile&state=-ZVBoPai_pHcn1G_cdRWQA
OAuth2::AccessToken
expires_in=3600 expired?=false refresh?=true
scope=profile
200 {"sub" => "1001", "email" => "alice@example.com"}
new access token: true, new refresh token: true
OAuth2::Error: invalid_grant - unknown refresh token
HTTP 400
[:token_type, :scope, :access_token, :refresh_token, :expires_at, :mode, :header_format, :param_name]
alice@example.com

The important pieces:

Storing and refreshing tokens

When your app calls the provider's API after login (not only to identify the user), store the tokens per user in the database. to_hash and OAuth2::AccessToken.from_hash round-trip a token. Encrypt the refresh token at rest: it is a long-lived password to the user's account at the provider. Rails' encrypts :refresh_token or ActiveSupport::MessageEncryptor do the job (see Cryptography).

Before each API call, refresh if the token is about to expire, and save the new token, because providers that rotate refresh tokens (like this one) invalidate the old one:

def api_token_for(user, client)
  token = OAuth2::AccessToken.from_hash(client, user.oauth_token)
  return token unless token.expires_at && token.expires_at < Time.now.to_i + 60

  token = token.refresh!
  user.update!(oauth_token: token.to_hash)
  token
rescue OAuth2::Error => e
  raise unless e.code == 'invalid_grant' # refresh token revoked or expired
  user.update!(oauth_token: nil)         # ask the user to connect again
  nil
end

If two requests refresh the same token at the same time, one of them loses with invalid_grant. Use a database lock (user.with_lock { ... }) around the refresh when that can happen.

Client credentials: machine to machine

When there is no user, for example a nightly job that calls a reporting API, the client authenticates as itself and gets a token directly. There is no redirect, no code and usually no refresh token. When the token expires you simply ask for a new one:

require 'oauth2'
require_relative 'provider'

AUTH_SERVER = Provider.boot!

# A background job authenticates as itself - there is no user involved
client = OAuth2::Client.new(ENV.fetch('CLIENT_ID', 'report-job'),
                            ENV.fetch('CLIENT_SECRET', 'job-secret'),
                            site: AUTH_SERVER, token_url: '/token',
                            auth_scheme: :basic_auth)

token = client.client_credentials.get_token(scope: 'reports:read')
puts "refresh token: #{token.refresh_token.inspect}, expires_at: #{token.expires_at.class}"
puts token.get('/api/reports').parsed.to_h

# Wrong secret: the token endpoint answers 401 invalid_client
bad = OAuth2::Client.new('report-job', 'wrong', site: AUTH_SERVER, token_url: '/token',
                         auth_scheme: :basic_auth)
begin
  bad.client_credentials.get_token
rescue OAuth2::Error => e
  puts "#{e.response.status} #{e.code}"
end

# Cache the token and fetch a new one shortly before it expires
class TokenCache
  def initialize(client, scope:, leeway: 60)
    @client, @scope, @leeway = client, scope, leeway
    @mutex = Mutex.new
  end

  def token
    @mutex.synchronize do
      if @token.nil? || @token.expires_at - @leeway < Time.now.to_i
        @token = @client.client_credentials.get_token(scope: @scope)
        puts '  (fetched a new token)'
      end
      @token
    end
  end
end

cache = TokenCache.new(client, scope: 'reports:read')
3.times { |i| puts "call #{i}: #{cache.token.get('/api/reports').status}" }
refresh token: nil, expires_at: Integer
{"reports" => ["daily", "weekly"], "scope" => "reports:read"}
401 invalid_client
  (fetched a new token)
call 0: 200
call 1: 200
call 2: 200

Fetching a token for every API call doubles the number of requests and can hit the provider's rate limits, so cache it until shortly before expires_at. The Mutex keeps threads in a multi-threaded server such as Puma from all fetching at once.

OpenID Connect: who is the user?

With OIDC you add openid to the scopes and a random nonce to the authorize URL. The token response then contains an id_token: a JWT signed by the provider with claims about the user. Before trusting it you must verify:

The jwt gem does all of this except the nonce check. Its jwks: option accepts a lambda, which is called again with kid_not_found: true when the token is signed with a key it hasn't seen. That's how key rotation at the provider is handled:

require 'oauth2'
require 'jwt'
require 'securerandom'
require_relative 'provider'

ISSUER = Provider.boot!
CLIENT_ID = 'demo-app'
client = OAuth2::Client.new(CLIENT_ID, 'demo-secret', site: ISSUER,
                            authorize_url: '/authorize', token_url: '/token',
                            auth_scheme: :basic_auth)
redirect_uri = 'http://localhost:4567/callback'

state = SecureRandom.urlsafe_base64(16)
nonce = SecureRandom.urlsafe_base64(16) # stored in the session, like state
url = client.auth_code.authorize_url(redirect_uri: redirect_uri, scope: 'openid profile',
                                     state: state, nonce: nonce)

# (user logs in - simulated)
login = Faraday.post("#{ISSUER}/authorize",
                     URI.decode_www_form(URI(url).query).to_h.merge(username: 'alice', password: 's3cret'))
code = URI.decode_www_form(URI(login.headers['location']).query).to_h['code']

token = client.auth_code.get_token(code, redirect_uri: redirect_uri)
id_token = token.params['id_token']
puts "id_token: #{id_token[0, 40]}..."

# Fetch the provider's public keys; refetch when an unknown kid shows up (key rotation)
jwks_loader = lambda do |options|
  @jwks = nil if options[:kid_not_found] && @jwks_fetched_at.to_i < Time.now.to_i - 300
  @jwks ||= begin
    @jwks_fetched_at = Time.now
    JWT::JWK::Set.new(JSON.parse(Faraday.get("#{ISSUER}/.well-known/jwks.json").body))
  end
end

claims, header = JWT.decode(id_token, nil, true,
                            algorithms: ['RS256'], jwks: jwks_loader,
                            iss: ISSUER, verify_iss: true,
                            aud: CLIENT_ID, verify_aud: true,
                            required_claims: %w[sub exp iat])
raise 'nonce mismatch: replayed ID token' unless OpenSSL.secure_compare(claims['nonce'], nonce)

puts "header: #{header}"
puts "user: sub=#{claims['sub']} email=#{claims['email']}"

# A token issued for another client is rejected
begin
  JWT.decode(id_token, nil, true, algorithms: ['RS256'], jwks: jwks_loader,
                                  aud: 'some-other-app', verify_aud: true)
rescue JWT::DecodeError => e
  puts "#{e.class}: #{e.message}"
end
id_token: eyJraWQiOiJrZXktMSIsImFsZyI6IlJTMjU2In0....
header: {"kid" => "key-1", "alg" => "RS256"}
user: sub=1001 email=alice@example.com
JWT::InvalidAudError: Invalid audience. Expected some-other-app, received demo-app

The JWT article explains the claims, algorithms and JWT::DecodeError subclasses in detail.

Use the ID token's sub (together with the issuer) as the stable user id, not the email address: users can change their email at the provider, and some providers allow unverified emails. If you need more profile data than the ID token carries, call the provider's userinfo_endpoint with the access token.

When the ID token came directly from the provider's token endpoint over TLS, as here, the signature check is defense in depth. It becomes essential when the ID token reaches you any other way, for example from a mobile app that logged in and sends the token to your API.

Log in with a provider using OmniAuth

In a Rack, Sinatra or Rails app you rarely write the callback logic yourself. OmniAuth is Rack middleware with a strategy gem per provider: omniauth-github, omniauth-google-oauth2, omniauth-microsoft_graph, omniauth_openid_connect and many more. Each one handles state, PKCE, the token exchange and fetching the profile, and hands your app a normalized hash.

With GitHub the whole setup is:

use OmniAuth::Builder do
  provider :github, ENV.fetch('GITHUB_CLIENT_ID'), ENV.fetch('GITHUB_CLIENT_SECRET'),
           scope: 'read:user,user:email'
end

OmniAuth adds two routes per provider:

For a provider without a ready-made gem, subclass OmniAuth::Strategies::OAuth2 from omniauth-oauth2. Here is a complete Sinatra app with a strategy for our test provider:

# app.rb - "Log in with Demo" using OmniAuth
require 'sinatra/base'
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Demo < OmniAuth::Strategies::OAuth2
      option :name, 'demo'
      option :client_options, { authorize_url: '/authorize', token_url: '/token',
                                auth_scheme: :basic_auth }
      option :authorize_params, { scope: 'profile' }
      option :pkce, true

      uid  { raw_info['sub'] }
      info { { email: raw_info['email'] } }

      def raw_info
        @raw_info ||= access_token.get('/api/profile').parsed
      end

      # redirect_uri must match the registered one exactly - no query string
      def callback_url = full_host + callback_path
    end
  end
end

class App < Sinatra::Base
  enable :sessions
  set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
  set :host_authorization, { permitted_hosts: [] }

  use OmniAuth::Builder do
    provider :demo, ENV.fetch('DEMO_CLIENT_ID', 'demo-app'),
             ENV.fetch('DEMO_CLIENT_SECRET', 'demo-secret'),
             client_options: { site: ENV.fetch('DEMO_SITE') }
  end

  helpers do
    def csrf_token = Rack::Protection::AuthenticityToken.token(session)
  end

  get '/' do
    if session[:user]
      "Hello #{session[:user]['email']} <form method=post action=/logout>...</form>"
    else
      # OmniAuth 2 only starts the flow on POST, with a CSRF token
      %(<form method="post" action="/auth/demo">
        <input type="hidden" name="authenticity_token" value="#{csrf_token}">
        <button>Log in with Demo</button></form>)
    end
  end

  get '/auth/:provider/callback' do
    auth = request.env['omniauth.auth'] # an OmniAuth::AuthHash
    session.clear # new session id after login: prevents session fixation
    session[:user] = { 'provider' => auth.provider, 'uid' => auth.uid,
                       'email' => auth.info.email }
    # auth.credentials.token / refresh_token / expires_at - store if you call the API later
    redirect '/'
  end

  get '/auth/failure' do
    status 401
    "Login failed: #{Rack::Utils.escape_html(params[:message])}"
  end
end

And a rack-test script that clicks through the login (the user's visit to the provider is simulated with Faraday, because rack-test only talks to our app):

ENV['RACK_ENV'] = 'test' # in development OmniAuth raises errors instead of redirecting
require_relative 'provider'
ENV['DEMO_SITE'] = Provider.boot!
require_relative 'app'
require 'rack/test'
require 'faraday'
OmniAuth.config.logger = Logger.new(nil)

include Rack::Test::Methods
def app = App

get '/'
token = last_response.body[/value="([^"]+)"/, 1]
post '/auth/demo', authenticity_token: token
location = last_response.headers['location']
puts "#{last_response.status} -> #{location.sub(ENV['DEMO_SITE'], '<provider>')[0, 70]}..."
query = URI.decode_www_form(URI(location).query).to_h
puts query.keys.inspect

# The user logs in at the provider (outside our app)
login = Faraday.post("#{ENV['DEMO_SITE']}/authorize",
                     query.merge('username' => 'alice', 'password' => 's3cret'))
callback = login.headers['location']
puts "provider redirects to: #{callback[0, 55]}..."

get callback
puts "callback: #{last_response.status} -> #{last_response.headers['location']}"
get '/'
puts last_response.body[/Hello \S+/]

# Starting the flow without the CSRF token is refused
clear_cookies
post '/auth/demo'
puts "no token: #{last_response.status} -> #{last_response.headers['location']}"

# An attacker's callback link: the state doesn't match the one in this session
get '/'
post '/auth/demo', authenticity_token: last_response.body[/value="([^"]+)"/, 1]
get '/auth/demo/callback', code: 'attackers-code', state: 'guess'
follow_redirect!
puts "forged callback: #{last_response.status} #{last_response.body}"
302 -> <provider>/authorize?client_id=demo-app&code_challenge=AUcHX5sLZvDjoXO...
["client_id", "code_challenge", "code_challenge_method", "redirect_uri", "response_type", "scope", "state"]
provider redirects to: http://example.org/auth/demo/callback?code=bvIBWuA7IIyM...
callback: 302 -> http://example.org/
Hello alice@example.com
no token: 302 -> /auth/failure?message=authenticity_error&strategy=demo
forged callback: 401 Login failed: csrf_detected

Things to notice:

Calling an API as a resource server

The other side of OAuth is your own API accepting tokens from a provider. There are two common designs:

Either way, answer 401 with a WWW-Authenticate: Bearer error="invalid_token" header when the token is missing, expired or invalid, and 403 with error="insufficient_scope" when it is valid but lacks the scope. The /api/profile route of the provider shows both. The JWT article has a complete Sinatra API that does the local-verification variant.

Security checklist

A tiny OAuth provider

This is provider.rb, used by all examples above. It implements the authorization code grant with PKCE, refresh token rotation, client credentials, OIDC ID tokens signed with RS256, a JWKS endpoint and two protected API routes, with everything kept in memory. It's useful for tests and for learning how the server side works, but for real deployments use a maintained server: Doorkeeper (with doorkeeper-openid_connect) for Rails, rodauth-oauth, or a hosted identity provider such as Keycloak, Auth0 or Okta.

# provider.rb - a tiny OAuth 2.0 / OpenID Connect provider for local experiments
require 'sinatra/base'
require 'puma'
require 'securerandom'
require 'digest'
require 'base64'
require 'json'
require 'jwt'

class Provider < Sinatra::Base
  CLIENTS = {
    'demo-app' => { secret: 'demo-secret',
                    redirect_uris: %w[http://localhost:4567/callback
                                      http://example.org/auth/demo/callback] },
    'report-job' => { secret: 'job-secret', redirect_uris: [] }
  }
  USERS  = { 'alice' => { password: 's3cret', sub: '1001', email: 'alice@example.com' } }
  CODES  = {}  # code => grant details
  TOKENS = {}  # access token => { sub:, scope:, expires_at: }
  REFRESH = {} # refresh token => { sub:, scope:, client_id: }
  KEY = OpenSSL::PKey::RSA.new(2048)
  JWK = JWT::JWK.new(KEY, kid: 'key-1')

  set :host_authorization, { permitted_hosts: [] }
  set :issuer, 'http://localhost' # replaced with the real URL at boot

  helpers do
    def oauth_error(status, error, desc = nil)
      halt status, { 'content-type' => 'application/json' },
           { error: error, error_description: desc }.compact.to_json
    end

    def authenticate_client!
      id, secret = if env['HTTP_AUTHORIZATION']&.start_with?('Basic ')
                     Base64.decode64(env['HTTP_AUTHORIZATION'][6..]).split(':', 2)
                   else
                     [params[:client_id], params[:client_secret]]
                   end
      client = CLIENTS[id]
      oauth_error 401, 'invalid_client' unless client &&
        Rack::Utils.secure_compare(client[:secret], secret.to_s)
      id
    end

    def issue_tokens(sub:, scope:, client_id:, nonce: nil)
      access = SecureRandom.urlsafe_base64(32)
      TOKENS[access] = { sub: sub, scope: scope, expires_at: Time.now + 3600 }
      body = { access_token: access, token_type: 'Bearer', expires_in: 3600, scope: scope }
      if sub
        refresh = SecureRandom.urlsafe_base64(32)
        REFRESH[refresh] = { sub: sub, scope: scope, client_id: client_id }
        body[:refresh_token] = refresh
      end
      if sub && scope.split.include?('openid')
        now = Time.now.to_i
        claims = { iss: settings.issuer, sub: sub, aud: client_id, iat: now,
                   exp: now + 300, nonce: nonce,
                   email: USERS.values.find { _1[:sub] == sub }[:email] }.compact
        body[:id_token] = JWT.encode(claims, KEY, 'RS256', kid: JWK[:kid])
      end
      content_type :json
      headers 'cache-control' => 'no-store'
      body.to_json
    end
  end

  # Step 1: the user's browser lands here. A real provider shows a login + consent page.
  get '/authorize' do
    client = CLIENTS[params[:client_id]]
    halt 400, 'unknown client' unless client
    halt 400, 'bad redirect_uri' unless client[:redirect_uris].include?(params[:redirect_uri])
    "<form method=post>Log in to grant #{Rack::Utils.escape_html(params[:client_id])} " \
      "access to: #{Rack::Utils.escape_html(params[:scope])} ...</form>"
  end

  # Step 2: the login form is submitted; on success redirect back with a code
  post '/authorize' do
    client = CLIENTS[params[:client_id]]
    halt 400, 'bad redirect_uri' unless client&.dig(:redirect_uris)&.include?(params[:redirect_uri])
    user = USERS[params[:username]]
    halt 401, 'wrong username or password' unless user && user[:password] == params[:password]

    code = SecureRandom.urlsafe_base64(24)
    CODES[code] = params.slice('client_id', 'redirect_uri', 'scope', 'nonce',
                               'code_challenge', 'code_challenge_method')
                        .merge('sub' => user[:sub], 'expires_at' => Time.now + 60)
    query = URI.encode_www_form({ code: code, state: params[:state] }.compact)
    redirect "#{params[:redirect_uri]}?#{query}"
  end

  post '/token' do
    client_id = authenticate_client!
    case params[:grant_type]
    when 'authorization_code'
      grant = CODES.delete(params[:code]) # single use
      oauth_error 400, 'invalid_grant', 'unknown or used code' unless grant
      oauth_error 400, 'invalid_grant', 'code expired' if grant['expires_at'] < Time.now
      oauth_error 400, 'invalid_grant', 'client mismatch' if grant['client_id'] != client_id
      oauth_error 400, 'invalid_grant', 'redirect_uri mismatch' if grant['redirect_uri'] != params[:redirect_uri]
      if grant['code_challenge']
        verifier  = params[:code_verifier].to_s
        challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
        oauth_error 400, 'invalid_grant', 'PKCE verification failed' unless
          Rack::Utils.secure_compare(challenge, grant['code_challenge'])
      end
      issue_tokens(sub: grant['sub'], scope: grant['scope'], client_id: client_id,
                   nonce: grant['nonce'])
    when 'refresh_token'
      old = REFRESH.delete(params[:refresh_token]) # rotation: each refresh token works once
      oauth_error 400, 'invalid_grant', 'unknown refresh token' unless old && old[:client_id] == client_id
      issue_tokens(sub: old[:sub], scope: old[:scope], client_id: client_id)
    when 'client_credentials'
      issue_tokens(sub: nil, scope: params[:scope].to_s, client_id: client_id)
    else
      oauth_error 400, 'unsupported_grant_type'
    end
  end

  # A protected API (the "resource server")
  get '/api/profile' do
    token = env['HTTP_AUTHORIZATION'].to_s[/\ABearer (.+)\z/, 1]
    info = TOKENS[token]
    unless info && info[:expires_at] > Time.now
      headers 'www-authenticate' => 'Bearer error="invalid_token"'
      oauth_error 401, 'invalid_token'
    end
    oauth_error 403, 'insufficient_scope' unless info[:scope].split.include?('profile')
    user = USERS.values.find { _1[:sub] == info[:sub] }
    content_type :json
    { sub: user[:sub], email: user[:email] }.to_json
  end

  get '/api/reports' do
    info = TOKENS[env['HTTP_AUTHORIZATION'].to_s.delete_prefix('Bearer ')]
    oauth_error 401, 'invalid_token' unless info
    content_type :json
    { reports: %w[daily weekly], scope: info[:scope] }.to_json
  end

  get '/.well-known/jwks.json' do
    content_type :json
    JWT::JWK::Set.new([JWK]).export.to_json
  end

  def self.boot!
    server = Puma::Server.new(self)
    port = server.add_tcp_listener('127.0.0.1', 0).addr[1]
    set :issuer, "http://127.0.0.1:#{port}"
    server.run
    settings.issuer
  end
end

Things a real provider adds: persistent storage, a login and consent page, hashed client secrets, scope validation against what each client may request, PKCE required for public clients, short-lived codes bound to the user's session, /.well-known/openid-configuration, token revocation and introspection endpoints, and rate limiting on /token.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents