Skip to content

Instantly share code, notes, and snippets.

@wcpaez
Created August 9, 2022 03:25
Show Gist options
  • Save wcpaez/fe80336bc83853ae955ca53236331a46 to your computer and use it in GitHub Desktop.
Save wcpaez/fe80336bc83853ae955ca53236331a46 to your computer and use it in GitHub Desktop.
Rack middleware to set and process HttpOnly refresh_token cookie. Works for doorkeper endpoint /oauth/token
# Doorkeeper HttpOnly middleware
class HttpOnlyRefreshToken
OAUTH_PATH = '/oauth/token'.freeze
def initialize(app)
@app = app
end
def call(env)
if env['PATH_INFO'] == OAUTH_PATH
manage_cookie(env)
else
@app.call(env)
end
end
def manage_cookie(env)
handle_request(env)
handle_response(env)
end
def handle_request(env)
request = Rack::Request.new(env)
request_body = JSON.parse(request.body.read)
# Set refresh_token on body with value from cookie
# Bypass if you send the refresh_token in the body
request.update_param('refresh_token', request.cookies['refresh_token']) if request_body['refresh_token'].blank?
# Body read causes problems, needs rewind
request.env['rack.input'].rewind
end
def handle_response(env)
status, headers, body = @app.call(env)
if status == 200
Rack::Utils.set_cookie_header!(
headers,
'refresh_token',
cookie_config(body)
)
end
[status, headers, body]
end
def cookie_config(body)
parsed_body = JSON.parse(body.body)
{
value: parsed_body['refresh_token'],
path: OAUTH_PATH,
httponly: true,
expires: 1.week.from_now
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment