Secure a Micronaut app with Google

Learn how to create Micronaut app and secure it with Google and provide authentication with OpenID Connect

Authors: Sergio del Amo

Micronaut Version: 1.2.0.RC1

1 Getting Started

In this guide we are going to create a Micronaut app written in Java.

1.1 What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

1.2 Solution

We recommend you to follow the instructions in the next sections and create the app step by step. However, you can go right to the completed example.

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the App

Create an app using the Micronaut Command Line Interface.

mn create-app example.micronaut.complete

The previous command creates a micronaut app with the default package example.micronaut in a folder named complete.

By default, create-app generates a Java Micronaut app and it uses Gradle build system. However, you could use other build tool such as Maven or other programming languages such as Groovy or Kotlin.

If you are using Java or Kotlin and IntelliJ IDEA make sure you have enabled annotation processing.

annotationprocessorsintellij

2.1 Views

Although Micronaut is primarily designed around message encoding / decoding, there are occasions where it is convenient to render a view on the server side.

To use the view rendering features, add the following dependency on your classpath. For example, in build.gradle

build.gradle
dependencies {
  ...
  ..
    compile "io.micronaut:micronaut-views"
}

To use Thymeleaf Java template engine, add the thymeleaf dependency:

build.gradle
dependencies {
  ...
  ..
    runtime "org.thymeleaf:thymeleaf:3.0.11.RELEASE"
}

2.2 OAuth 2.0

Visit https://console.developers.google.com and create a new project:

google 1

You will also need to create OAuth 2.0 credentials for the project since Google does not do that automatically. From the sidebar, click the Credentials tab, the click Create credentials and choose OAuth client ID from the dropdown.

google 2

The Google Console will prompt for some information about your application such as the product name, a home page and a logo. On the next page, select Web Application type, and enter the redirect URL where the Micronaut app we will build next will wait for the callback.

google 4

You will then receive a client ID and secret.

google 3

To use OAuth 2.0 integration in your Micronaut App, add the next dependency:

gradle.properties
micronautVersion=1.2.0.RC1
build.gradle
dependencies {
  ...
  ..
    compile "io.micronaut.configuration:micronaut-security-oauth2"
}

Add also JWT Micronaut’s JWT support dependencies:

build.gradle
dependencies {
  ...
  ..
    annotationProcessor "io.micronaut:micronaut-security"
    compile "io.micronaut:micronaut-security-jwt"
}

Add the following Oauth2 Configuration:

src/main/resources/application.yml
micronaut:
  application:
    name: complete
  security:
    enabled: true (1)
    oauth2:
      enabled: true
      clients:
        google: (2)
          client-id: '${OAUTH_CLIENT_ID}'  (3)
          client-secret: '${OAUTH_CLIENT_SECRET}' (4)
          openid:
            issuer: 'https://accounts.google.com' (5)
    token:
      jwt:
        enabled: true (6)
        cookie:
          enabled: true (7)
        signatures:
          secret:
            generator: (8)
              secret: pleaseChangeThisSecretForANewOne (9)
endpoints:
      logout:
        enabled: true (10)
        get-allowed: true (11)
1 Enable security
2 The provider identifier should match the last part of the url you entered as a redirect url /oauth/callback/google
3 Client Secret. See previous screenshot.
4 Client ID. See previous screenshot.
5 issuer url. It allows micronaut to discover the configuration of the OpenID Connect server.
6 ID Token is a JWT token. We need to enable Micronaut’s JWT support to validate it.
7 Once validated, we are going to save the ID Token in a Cookie. To read in subsequent requests, enable Cookie Token Reader.
8 You can create a SecretSignatureConfiguration named generator via configuration as illustrated above. The generator signature is used to sign the issued JWT claims.
9 Change this by your own secret and keep it safe (do not store this in your VCS)
10 Enable Logout Controller
11 Accept GET request to the /logout endpoint.

The previous configuration uses several placeholders. You will need to setup OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OIDC_ISSUER_DOMAIN and OIDC_ISSUER_AUTHSERVERID environment variables.

export OAUTH_CLIENT_ID=XXXXXXXXXX
export OAUTH_CLIENT_SECRET=YYYYYYYYYY

We want to use an Authorization Code grant type flow which it is described in the following diagram:

diagramm

2.3 Home

Create a controller to handle the requests to /. You are going to display the email of the authenticated person if any. Annotate the controller endpoint with @View since we are going to use a Thymeleaf template.

src/main/java/example/micronaut/HomeController.java
package example.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.views.View;

import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {

    @Secured(SecurityRule.IS_ANONYMOUS)
    @View("home")
    @Get
    public Map<String, Object> index() {
        return new HashMap<>();
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 Annotate with io.micronaut.security.Secured to configure secured access. The SecurityRule.IS_ANONYMOUS expression will allow access without authentication.
3 Use View annotation to specify which template would you like to render the response against.
4 The @Get annotation is used to map the index method to GET / requests.

Create a thymeleaf template:

src/main/resources/views/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
<h1>Micronaut - Google example</h1>

<h2 th:if="${security}">username: <span th:text="${security.attributes.get('email')}"></span></h2>
<h2 th:unless="${security}">username: Anonymous</h2>

<nav>
    <ul>
        <li th:unless="${security}"><a href="/oauth/login/google">Enter</a></li>
        <li th:if="${security}"><a href="/logout">Logout</a></li>
    </ul>
</nav>
</body>
</html>

Also, note that we return an empty model in the controller. However, we are accessing security in the thymeleaf template.

2.4 Running the Application

To run the application use the ./gradlew run command which will start the application on port 8080.

video

2.5 Custom ID token claims validation

Imagine you want to allow sign-in with Google but only to users' in your organization.

Google OAuth consent screen settings allows you to do that:

google 5

However, we could also achieve this programmatically. Google id token contains a claim named hd which stands for hosted domain.

We can create a configuration object:

src/main/java/example/micronaut/ApplicationConfiguration.java
package example.micronaut;

public interface ApplicationConfiguration {

    String getHostedDomain();
}

Backed by a @ConfigurationProperties annotated class:

src/main/java/example/micronaut/ApplicationConfigurationProperties.java
package example.micronaut;

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.context.annotation.Requires;

@Requires(property = "app.hosted-domain")
@ConfigurationProperties("app")
public class ApplicationConfigurationProperties implements ApplicationConfiguration {

    private String hostedDomain;

    public void setHostedDomain(String hostedDomain) {
        this.hostedDomain = hostedDomain;
    }

    @Override
    public String getHostedDomain() {
        return hostedDomain;
    }
}

and then implement a OpenIdClaimsValidator bean. Micronaut validates the id token against every bean of type OpenIdClaimsValidator. If the id token hd claim does not match the value configured, it is considered invalid.

src/main/java/example/micronaut/HostedDomainClaimValidator.java
package example.micronaut;

import io.micronaut.context.annotation.Requires;
import io.micronaut.security.oauth2.client.OpenIdProviderMetadata;
import io.micronaut.security.oauth2.configuration.OauthClientConfiguration;
import io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims;
import io.micronaut.security.oauth2.endpoint.token.response.validation.OpenIdClaimsValidator;

import javax.inject.Singleton;

@Requires(beans = ApplicationConfiguration.class)
@Singleton
public class HostedDomainClaimValidator implements OpenIdClaimsValidator {

    public static final String HOSTED_DOMAIN_CLAIM = "hd";

    private final String hostedDomain;

    public HostedDomainClaimValidator(ApplicationConfiguration applicationConfiguration) {
        this.hostedDomain = applicationConfiguration.getHostedDomain();
    }

    @Override
    public boolean validate(OpenIdClaims claims, OauthClientConfiguration clientConfiguration, OpenIdProviderMetadata providerMetadata) {
        Object hd = claims.get(HOSTED_DOMAIN_CLAIM);
        return hd instanceof String && ((String) hd).equalsIgnoreCase(hostedDomain);
    }
}

Add to src/main/resources/application.yaml

app:
  hosted-domain: 'objectcomputing.com'

if you start the app, you will only be able to sign in with a Google Account within OCI organization.

3 Learn More

Read Micronaut OAuth 2.0 documentation to learn more.