Authentication between Lambda and Ruby on Rails

Ats
2 min readMar 23, 2024

--

This is the note for a simple authentication between AWS Lambda and Ruby on Rails.

Photo by rc.xyz NFT gallery on Unsplash

Background

I have AWS SAM and Ruby and Rails and they communicate from Lambda to Rails with HTTPS requests. I made a system to authorize the requests long ago, which I copied as what I used to work for before.

Then last week, I suddenly felt it was too complicated just for authentication. I took a few hours to understand how it worked completely. So I thought there would be an easier way to do the same thing. Then I started to investigate.

What I did

For Ruby on Rails

I just googled and found the authenticate_or_request_with_http_token method.

I’m ashamed to say I didn’t know this method existed. It has been provided by Ruby on Rails for a very long time. The method is quite simple and easy to understand. So I’ve decided to go with it. That’s the part of what it does exactly.

Based on that, the method checks the Bearer token in the header and sends the HTTP requests back if something is wrong. That’s all I want to do.

So these are the code lines in Ruby on Rails. I made a concern in controllers and shared it with the controllers which need to accept requests from AWS lambda.

module LambdaAuthenticatable
extend ActiveSupport::Concern

included do
before_action :authenticate
end

def authenticate
authenticate_or_request_with_http_token do |token, _|
ActiveSupport::SecurityUtils.secure_compare(token,ENV['TOKEN'])
end
end
end

For AWS SAM

I needed to set the Bearer token in the header of requests. It depends on which language you use in lambda. So I’ll skip to write details here. But I’ll share the way to set the token in the environment variable.

I followed the following article as my reference.

I modified it a little bit using parameter_overrides in samconfig.toml

I added a token in samconfig.toml and set the Env variable in template.yaml

[default.global.parameters]
parameter_overrides=[
"EnvVarName=xxxxxxx",
]
...
Parameters:
EnvVarName:
Type: String
...
Environment:
Variables:
AUTHORIZATION_TOKEN: !Ref EnvVarName

I know there are pros and cons to storing sensitive secrets in the GitHub repository. In my opinion, I’m not against that if you’re in a small team and the repository is secret.

I hadn’t investigated the authentication system from zero before because developers seldom touch the code lines once it’s built up. It’s always good to understand how it works.

That’s it!

--

--

Ats
Ats

Written by Ats

I like building something tangible like touch, gesture, and voice. Ruby on Rails / React Native / Yocto / Raspberry Pi / Interaction Design / CIID IDP alumni

No responses yet