Skip to content

Latest commit

 

History

History
297 lines (200 loc) · 11.9 KB

APPROOV_TOKEN_QUICKSTART.md

File metadata and controls

297 lines (200 loc) · 11.9 KB

Approov Token Quickstart

This quickstart is for developers familiar with Java 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 to an existing Java Spring API server.

TOC - Table of Contents

Why?

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.

TOC

How it works?

For more background, see the Approov Overview at the root of this repo.

The main functionality for the Approov token check is in the file ApproovAuthentication.java. Take a look at the verifyApproovToken() function to see the simple code for the check.

TOC

Requirements

To complete this quickstart you will need both Java, Java Spring, and the Approov CLI tool installed.

TOC

Approov Setup

To use Approov with the Java Spring API server we need a small amount of configuration. First, Approov needs to know the API domain that will be protected. Second, the Java Spring API server needs the Approov Base64 encoded secret that will be used to verify the tokens generated by the Approov cloud service.

Configure API Domain

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 issuing the Approov CLI command and the Approov servers.

Approov Secret

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 Java Spring 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

Set the Approov Secret

Open the .env file and add the Approov secret to the var:

APPROOV_BASE64_SECRET=approov_base64_secret_here

TOC

Approov Token Check

To perform the token check in your project you will need to add the Approov and Jwt packages.

The JWT Package

To check the Approov token we will use the jwtk/jjwt package.

Add to your build.gradle dependencies:

dependencies {

    // omitted..

    implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
    runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2',
        'io.jsonwebtoken:jjwt-jackson:0.11.2'
}

The Approov Package

From this repo add the package com.criticalblue.approov.jwt.authentication to your current project by copying the entire authentication folder into your project.

Next, use it from the class in your project that extends the WebSecurityConfigurerAdapter. For example:

package com.yourcompany.projectname;

import com.criticalblue.approov.jwt.authentication.*;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static ApproovConfig approovConfig = ApproovConfig.getInstance();

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedMethods(Arrays.asList("GET"));
        configuration.addAllowedHeader("Authorization");
        configuration.addAllowedHeader("Approov-Token");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/error");
    }

    @Configuration
    // @IMPORTANT Approov token check must be at Order 1. Any other type of
    //            Authentication (User, API Key, etc.) for the request should go
    //            after with @Order(2)
    @Order(1)
    public static class ApproovWebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.cors();

            http
                .httpBasic().disable()
                .formLogin().disable()
                .logout().disable()
                .csrf().disable()
                // @APPROOV The Approov Token check is triggered here.
                .authenticationProvider(new ApproovAuthenticationProvider(approovConfig))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            http
                .securityContext()
                // @APPROOV The Approov Token check is configured here.
                .securityContextRepository(new ApproovSecurityContextRepository(approovConfig))
                .and()
                    .exceptionHandling()
                    // @APPROOV The Approov Token check is done here
                    .authenticationEntryPoint(new ApproovAuthenticationEntryPoint())
                .and()
                    // @APPROOV This matcher will require the Approov token for
                    // all API endpoints.
                    .antMatcher("/")
                        .authorizeRequests()
                        .antMatchers(HttpMethod.GET, "/**").authenticated();
        }
    }
}

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 a 400.

A full working example for a simple Hello World server can be found at /servers/hello/src/approov-protected-server/token-check.

To see the code difference between the token check and no token check on the Hello servers use the git diff command from the root of this repo:

git diff --no-index ./servers/hello/src/unprotected-server/src/main/java/com/criticalblue/approov/jwt/ ./servers/hello/src/approov-protected-server/token-check/src/main/java/com/criticalblue/approov/jwt/

TOC

Test your Approov Integration

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.

With Valid Approov Tokens

Generate a valid token example from the Approov Cloud service:

approov token -genExample your.api.domain.com

Then make the request with the generated token:

curl -i --request GET 'https://your.api.domain.com' \
  --header 'Approov-Token: APPROOV_TOKEN_EXAMPLE_HERE'

The request should be accepted. For example:

HTTP/1.1 200 OK

...

{"message": "Hello, World!"}

With Invalid Approov Tokens

Generate an invalid token example from the Approov Cloud service:

approov token -type invalid -genExample your.api.domain.com

Then make the request with the generated token:

curl -i --request GET 'https://your.api.domain.com' \
  --header 'Approov-Token: APPROOV_INVALID_TOKEN_EXAMPLE_HERE'

The above request should fail with an Unauthorized error. For example:

HTTP/1.1 401 Unauthorized

...
{}

TOC

Issues

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.

TOC

Useful Links

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:

TOC