This quickstart is for developers familiar with Ruby on Rails who are looking for a quick intro into how they can add Approov into an existing project. Therefore this will guide you through the necessary steps for adding Approov with token binding to an existing Ruby on Rails API server.
- Why?
- How it Works?
- Requirements
- Approov Setup
- Approov Token Check
- Try the Approov Integration Example
To lock down your API server to your mobile app. Please read the brief summary in the Approov Overview at the root of this repo or visit our website for more details.
For more background, see the Approov Overview at the root of this repository.
The main functionality for the Approov token binding check is in the Approov Middleware class. Take a look at the verifyApproovToken()
and verifyApproovTokenBinding()
functions to see the simple code for the checks.
To complete this quickstart you will need both the Ruby on Rails and the Approov CLI tool installed.
- Ruby on Rails - Follow the official installation instructions from here
- Approov CLI - Follow our installation instructions and read more about each command and its options in the documentation reference
To use Approov with the Ruby on Rails API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Ruby on Rails API server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service.
Approov needs to know the domain name of the API for which it will issue tokens.
Add it with:
approov api -add your.api.domain.com
NOTE: By default a symmetric key (HS256) is used to sign the Approov token on a valid attestation of the mobile app for each API domain it's added with the Approov CLI, so that all APIs will share the same secret and the backend needs to take care to keep this secret secure.
A more secure alternative is to use asymmetric keys (RS256 or others) that allows for a different keyset to be used on each API domain and for the Approov token to be verified with a public key that can only verify, but not sign, Approov tokens.
To implement the asymmetric key you need to change from using the symmetric HS256 algorithm to an asymmetric algorithm, for example RS256, that requires you to first add a new key, and then specify it when adding each API domain. Please visit Managing Key Sets on the Approov documentation for more details.
Adding the API domain also configures the dynamic certificate pinning setup, out of the box.
NOTE: By default the pin is extracted from the public key of the leaf certificate served by the domain, as visible to the box executing the Approov CLI command and the Approov servers.
Approov tokens are signed with a symmetric secret. To verify tokens, we need to grab the secret using the Approov secret command and plug it into the Ruby on Rails API server environment to check the signatures of the Approov Tokens that it processes.
First, enable your Approov admin
role with:
eval `approov role admin`
For the Windows powershell:
set APPROOV_ROLE=admin:___YOUR_APPROOV_ACCOUNT_NAME_HERE___
Next, retrieve the Approov secret with:
approov secret -get base64
Open the .env
file and add the Approov secret to the var:
APPROOV_BASE64_SECRET=approov_base64_secret_here
Now, add to your Gemfile the dotenv-rails gem to automatically load the Approov secret:
gem 'dotenv-rails', '~> 2.7.6'
To check the Approov token we will use the jwt/ruby-jwt package, but you are free to use another one of your preference.
First, add the jwt
dependency to your Gemfile:
gem 'jwt', '~> 2.2.2'
Now, run the installer:
bundle install
Next, add the Approov Middleware class to your project at app/middlewares/approov_middleware.rb
:
class ApproovMiddleware
def initialize app
@app = app
if not ENV['APPROOV_BASE64_SECRET']
raise "Missing in the .env file the value for the variable: APPROOV_BASE64_SECRET"
end
@APPROOV_SECRET = Base64.decode64(ENV['APPROOV_BASE64_SECRET'])
end
def call env
# Make the code thread safe by duplicating the object
dup._call env
end
def _call env
# We return 401 with an empty body because we don't want to give clues
# to the attacker about why he is failing the request, and you can go
# even further and return a 400.
invalid_response = [401, {"Content-Type" => "application/json"}, []]
request = Rack::Request.new env
approov_token_claims = verifyApproovToken(request)
if not approov_token_claims
return invalid_response
end
if not verifyApproovTokenBinding(request, approov_token_claims)
return invalid_response
end
# Allow later reuse of the Approov token claims in request life cycle.
env["APPROOV_TOKEN_CLAIMS"] = approov_token_claims
return @app.call(env)
end
def verifyApproovToken request
begin
approov_token = request.get_header "HTTP_APPROOV_TOKEN"
if not approov_token
# You may want to add some logging here
# Rails.logger.debug 'Missing the Approov token header!'
return nil
end
options = { algorithm: 'HS256' }
approov_token_claims, header = JWT.decode approov_token, @APPROOV_SECRET, true, options
return approov_token_claims
rescue JWT::DecodeError => e
# You may want to add some logging here
# Rails.logger.debug e
return nil
rescue JWT::ExpiredSignature => e
# You may want to add some logging here
# Rails.logger.debug e
return nil
rescue JWT::InvalidIssuerError => e
# You may want to add some logging here
# Rails.logger.debug e
return nil
rescue JWT::InvalidIatError => e
# You may want to add some logging here
# Rails.logger.debug e
return nil
end
# You may want to add some logging here
# Rails.logger.debug 'Whoops, unknown failure when verifying the Approov token!'
return nil
end
def verifyApproovTokenBinding request, approov_token_claims
if not approov_token_claims['pay']
# You may want to add some logging here
# Rails.logger.debug 'Missing Approov token binding claim in the Approov token.'
return false
end
# We use the Authorization token, but feel free to use another header in
# the request. Beqar in mind that it needs to be the same header used in the
# mobile app to qbind the request with the Approov token.
token_binding_header = request.get_header 'HTTP_AUTHORIZATION'
if not token_binding_header
# You may want to add some logging here
# Rails.logger.debug 'Missing the token binding header in the request headers.'
return false
end
# We need to hash and base64 encode the token binding header, because that's
# how it was included in the Approov token on the mobile app.
token_binding_header_encoded = Digest::SHA256.base64digest token_binding_header
if not approov_token_claims['pay'] === token_binding_header_encoded
# You may want to add some logging here
# Rails.logger.debug 'Token binding not matching.'
return false
end
return true
end
end
NOTE: When the Approov token validation fails we return a
401
with an empty body, because we don't want to give clues to an attacker about the reason the request failed, and you can go even further by returning a400
.
Now, add the Approov Middleware to your Ruby on Rails application middleware configuration at config/application.rb:
# Inserted as the first middleware to protect your server from wasting
# resources in processing requests not having a valid Approov token. This
# increases availability for your users during peak time or in the event of a
# DoS attack.
config.middleware.insert_before ActionDispatch::HostAuthorization, ApproovMiddleware
A full working example for a simple Hello World server can be found at src/approov-protected-server/token-binding-check/hello.
The following examples below use cURL, but you can also use the Postman Collection to make the API requests. Just remember that you need to adjust the urls and tokens defined in the collection to match your deployment. Alternatively, the above README also contains instructions for using the preset dummy secret to test your Approov integration.
Generate a valid token example from the Approov Cloud service:
approov token -setDataHashInToken 'Bearer authorizationtoken' -genExample your.api.domain.com
Then make the request with the generated token:
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
--header 'Authorization: Bearer authorizationtoken' \
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
The request should be accepted. For example:
HTTP/1.1 200
...
{"message": "Hello, World!"}
Let's just remove the Authorization header from the request:
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
The above request should fail with an Unauthorized error. For example:
HTTP/1.1 401
...
{}
Make the request with the same generated token, but with another random authorization token:
curl -i --request GET 'https://your.api.domain.com/v1/shapes' \
--header 'Authorization: Bearer anotherauthorizationtoken' \
--header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'
The above request should also fail with an Unauthorized error. For example:
HTTP/1.1 401
...
{}
If you find any issue while following our instructions then just report it here, with the steps to reproduce it, and we will sort it out and/or guide you to the correct path.
If you wish to explore the Approov solution in more depth, then why not try one of the following links as a jumping off point: