<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zdenek Papez on Medium]]></title>
        <description><![CDATA[Stories by Zdenek Papez on Medium]]></description>
        <link>https://medium.com/@zdenek-papez?source=rss-4aae8009b7d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Hx2iWx18uQW5_7mLM_rG-Q.png</url>
            <title>Stories by Zdenek Papez on Medium</title>
            <link>https://medium.com/@zdenek-papez?source=rss-4aae8009b7d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:03:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zdenek-papez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Boot Integration Tests Using AWS DynamoDB Local with Maven]]></title>
            <link>https://zdenek-papez.medium.com/spring-boot-integration-tests-using-aws-dynamodb-local-with-maven-7dba6ca2ccb9?source=rss-4aae8009b7d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dba6ca2ccb9</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Zdenek Papez]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 12:34:10 GMT</pubDate>
            <atom:updated>2023-11-03T08:33:58.210Z</atom:updated>
            <content:encoded><![CDATA[<p>This article shows a Maven project with Spring Boot REST API connected to AWS DynamoDB repository and explains how to configure such project to run integration tests using DynamoDB Local on random port.</p><p>Running integration tests on random port is particularly useful when running in continuous integration (CI), where multiple tests (code branches) might be running at the same time on the same machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Djp4b1cy7V9Yutawxu3Hbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Patrick Tomasso</a> on <a href="https://unsplash.com/photos/open-book-lot-Oaqk7qqNh_c?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>The article uses and covers:</h4><ul><li>Spring Boot Application (with one REST controller to read data from AWS DynamoDB)</li><li>Configuration of Maven project to include integration tests</li><li>Integration test using DynamoDB local started on random port</li></ul><p>For reference, see the <a href="https://github.com/zpapez/dynamodb-local-integration-test">whole sample project on GitHub</a>.</p><h3>Spring Boot Application</h3><p>Start with <a href="https://start.spring.io/">Spring Initializr</a> and add the necessary dependencies:</p><ul><li>Spring Web — our application itself is a REST API with one endpoint</li><li>Lombok — for some handy getters and setters</li></ul><p>The application will also need extra dependencies from AWS SDK for DynamoDB:</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;software.amazon.awssdk&lt;/groupId&gt;<br> &lt;artifactId&gt;dynamodb&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;software.amazon.awssdk&lt;/groupId&gt;<br> &lt;artifactId&gt;dynamodb-enhanced&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>Entity and Repository</h3><p>Let’s create a simple Country entity and a repository that reads all of them from the DB table.</p><pre>import lombok.Data;<br>import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;<br>import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;<br><br>@DynamoDbBean<br>@Data<br>public class CountryEntity {<br>    public static final String TABLE_NAME = &quot;Country&quot;;<br><br>    private String countryCode;<br>    private String countryDisplayName;<br><br>    @DynamoDbPartitionKey<br>    public String getCountryCode() {<br>        return countryCode;<br>    }<br>}</pre><pre>import java.util.List;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.stereotype.Component;<br>import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;<br><br>@Component<br>@RequiredArgsConstructor<br>public class CountryRepository {<br>    private final DynamoDbTable&lt;CountryEntity&gt; table;<br><br>    public List&lt;CountryEntity&gt; getAll() {<br>        return table.scan().items().stream().toList();<br>    }<br>}</pre><h3>Service and Controller</h3><p>Let’s create a service layer and connect it to a controller, that returns all items from the DynamoDB as a response to the endpoint api/v1/countries.</p><pre>import java.util.List;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.stereotype.Service;<br><br><br>@Service<br>@RequiredArgsConstructor<br>public class CountryService {<br><br>    private final CountryRepository repository;<br><br>    public List&lt;CountryEntity&gt; getAll() {<br>        return repository.getAll();<br>    }<br>}</pre><pre>import java.util.List;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/countries&quot;)<br>@RequiredArgsConstructor<br>public class CountryController {<br>    private final CountryService service;<br><br>    @GetMapping<br>    public List&lt;CountryEntity&gt; getAll() {<br>        return service.getAll();<br>    }<br>}</pre><h3>DynamoDB configuration</h3><p>In the DB configuration, first we need to define our DynamoDbTable that we can get from a dbClient using a table schema based on our existing bean CountryEntity.</p><p>You need to also prepare the DynamoDbClient bean, so that you are able to override its default endpoint. This is needed for two reasons:</p><ul><li>ability to run the application locally against a DynamoDB in Docker</li><li>ability to run integration test, where DynamoDB local will start on random port.</li></ul><p>See @Value(&quot;${zpapez.aws.dynamodb.endpoint:}&quot;) and endpointOverride() below. Its usage during local run and integration tests is explained later in the article.</p><pre>import java.net.URI;<br>import lombok.NoArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;<br>import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;<br>import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;<br>import software.amazon.awssdk.enhanced.dynamodb.TableSchema;<br>import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension;<br>import software.amazon.awssdk.regions.Region;<br>import software.amazon.awssdk.services.dynamodb.DynamoDbClient;<br><br>@Configuration<br>@NoArgsConstructor<br>@Slf4j<br>public class DynamoDbConfig {<br>    @Value(&quot;${zpapez.aws.dynamodb.endpoint:}&quot;)<br>    private String dynamodbEndpoint;<br>    @Value(&quot;${region:us-east-1}&quot;)<br>    private String region;<br><br>    @Bean<br>    public DynamoDbClient getDynamoDbClient() {<br>        var builder = DynamoDbClient<br>                .builder()<br>                .credentialsProvider(DefaultCredentialsProvider.create());<br><br>        if (dynamodbEndpoint != null &amp;&amp; !dynamodbEndpoint.isBlank()) {<br>            builder.region(Region.of(region))<br>                    .endpointOverride(URI.create(dynamodbEndpoint));<br>            log.info(&quot;DynamoDB Client initialized in region &quot; + region);<br>            log.warn(&quot;DynamoDB Client ENDPOINT overridden to &quot; + dynamodbEndpoint);<br>        }<br>        return builder.build();<br>    }<br><br>    @Bean<br>    public DynamoDbEnhancedClient getDynamoDbEnhancedClient(DynamoDbClient ddbc) {<br>        return DynamoDbEnhancedClient<br>                .builder()<br>                .extensions(VersionedRecordExtension.builder().build())<br>                .dynamoDbClient(ddbc)<br>                .build();<br>    }<br><br>    @Bean<br>    public DynamoDbTable&lt;CountryEntity&gt; getCountryLocaleTable(DynamoDbEnhancedClient dbClient) {<br>        return dbClient.table(CountryEntity.TABLE_NAME, TableSchema.fromBean(CountryEntity.class));<br>    }<br>}</pre><h4>Running application locally</h4><p>Run the DynamoDB Local in a Docker container, using image <a href="https://hub.docker.com/r/amazon/dynamodb-local">amazon/dynamodb-local</a> on port 8000.</p><p>Define local application properties to point to the local DB endpoint in application-local.yml :</p><pre>zpapez:<br>  aws:<br>    dynamodb:<br>      endpoint: &quot;http://localhost:8000&quot;</pre><p>Run the Application with local profile SPRING_PROFILES_ACTIVE=local .</p><h3>Integration tests</h3><h4>Maven setup</h4><p>This project uses a separate source folder for integration tests and Failsafe plugin to run them. You can <a href="https://www.baeldung.com/maven-integration-test">follow the steps mentioned in Baeldung arrticle to configure your maven project for integration testing</a> (see chapter 4 and 8).</p><p>Add DynamoDB Local dependency:</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br> &lt;artifactId&gt;DynamoDBLocal&lt;/artifactId&gt;<br> &lt;version&gt;1.23.0&lt;/version&gt;<br> &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>The DynamoDB Local uses the <a href="https://bitbucket.org/almworks/sqlite4java">SQLite4Java</a> library internally; thus, you also need to include the library files when running the test. Add a new build step to copy native libraries into a specific folder:</p><pre>&lt;plugin&gt;<br>  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>  &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;<br>  &lt;version&gt;3.6.0&lt;/version&gt;<br>  &lt;executions&gt;<br>   &lt;execution&gt;<br>    &lt;id&gt;copy&lt;/id&gt;<br>    &lt;phase&gt;test-compile&lt;/phase&gt;<br>    &lt;goals&gt;<br>     &lt;goal&gt;copy-dependencies&lt;/goal&gt;<br>    &lt;/goals&gt;<br>    &lt;configuration&gt;<br>     &lt;includeScope&gt;test&lt;/includeScope&gt;<br>     &lt;includeTypes&gt;so,dll,dylib&lt;/includeTypes&gt;<br>     &lt;outputDirectory&gt;${project.build.directory}/native-libs&lt;/outputDirectory&gt;<br>    &lt;/configuration&gt;<br>   &lt;/execution&gt;<br>  &lt;/executions&gt;<br> &lt;/plugin&gt;</pre><p>Configure that native-libs folder as a system property in integration tests:</p><pre>&lt;plugin&gt;&lt;!-- attach IT tests to verify phase --&gt;<br>  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>  &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;<br>  &lt;version&gt;3.1.2&lt;/version&gt;<br>  &lt;executions&gt;<br>   &lt;execution&gt;<br>    &lt;id&gt;integration-test&lt;/id&gt;<br>    &lt;goals&gt;<br>     &lt;goal&gt;integration-test&lt;/goal&gt;<br>    &lt;/goals&gt;<br>   &lt;/execution&gt;<br>  &lt;/executions&gt;<br>  &lt;configuration&gt;<br>   &lt;systemPropertyVariables&gt;<br>    &lt;sqlite4java.library.path&gt;${project.build.directory}/native-libs&lt;/sqlite4java.library.path&gt;<br>   &lt;/systemPropertyVariables&gt;<br>   &lt;argLine&gt;<br>    --add-opens java.base/java.time=ALL-UNNAMED<br>   &lt;/argLine&gt;<br>  &lt;/configuration&gt;<br> &lt;/plugin&gt;</pre><h4>JUnit 5 Extension for DynamoDB Local</h4><p>Configure our DynamoDB Local server start and stop in a JUnit 5 extension, so that you can reuse it in many integration tests.</p><p>Let the JUnit 5 extension implementBeforeAllCallback to start the server on random port new ServerSocket(0), and AfterAllCallback to stop the server at the end of the test class.</p><pre>package cz.zpapez.dynamodb;<br><br>import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;<br>import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;<br>import java.net.ServerSocket;<br>import lombok.Getter;<br>import org.junit.jupiter.api.extension.AfterAllCallback;<br>import org.junit.jupiter.api.extension.BeforeAllCallback;<br>import org.junit.jupiter.api.extension.ExtensionContext;<br><br><br>public class LocalDbCreationRule implements AfterAllCallback, BeforeAllCallback {<br>    private DynamoDBProxyServer server;<br><br>    @Getter<br>    private String port;<br><br>    public LocalDbCreationRule() {<br>        System.setProperty(&quot;aws.region&quot;, &quot;us-east-1&quot;);<br>        System.setProperty(&quot;aws.accessKeyId&quot;, &quot;test&quot;);<br>        System.setProperty(&quot;aws.secretAccessKey&quot;, &quot;test&quot;);<br>    }<br><br>    @Override<br>    public void beforeAll(ExtensionContext context) throws Exception {<br>        try (ServerSocket serverSocket = new ServerSocket(0)) {<br>            port = String.valueOf(serverSocket.getLocalPort());<br>        }<br>        server = ServerRunner.createServerFromCommandLineArgs(<br>                new String[]{&quot;-inMemory&quot;, &quot;-port&quot;, port});<br>        server.start();<br>    }<br><br><br>    @Override<br>    public void afterAll(ExtensionContext context) {<br>        this.stopUnchecked(server);<br>    }<br><br>    protected void stopUnchecked(DynamoDBProxyServer dynamoDbServer) {<br>        try {<br>            dynamoDbServer.stop();<br>        } catch (Exception e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><h4>Starting DynamoDB Local on random port</h4><p>In the integration test itsefl, use@RegisterExtension LocalDbCreationRule. In order to connect the DynamoDbClilent to the random port, where the DB started locally, you need to configure the port using DynamicPropertySource and set the property zpapez.aws.dynamodb.endpoint:</p><pre>@DynamicPropertySource<br>static void localDynamoDbProperties(DynamicPropertyRegistry registry) {<br>    String port = localDynamoDb.getPort();<br>    registry.add(&quot;zpapez.aws.dynamodb.endpoint&quot;, () -&gt;<br>            String.format(&quot;http://localhost:%s&quot;, port));<br>}</pre><p>This way you can finally complete the whole @SpringBootTest with MockMvc that is writing some test data to the local DynamoDB and calling the application’s REST API endpoint under test to retrieve it.</p><pre>package cz.zpapez.dynamodb;<br><br>import static org.hamcrest.Matchers.hasSize;<br>import static org.hamcrest.Matchers.is;<br>import org.junit.jupiter.api.AfterEach;<br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.extension.RegisterExtension;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.http.MediaType;<br>import org.springframework.test.context.DynamicPropertyRegistry;<br>import org.springframework.test.context.DynamicPropertySource;<br>import org.springframework.test.web.servlet.MockMvc;<br>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;<br>import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;<br>import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;<br><br><br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,<br>        classes = Application.class)<br>@AutoConfigureMockMvc<br>public class CountryControllerIT extends AbstractIntegrationTest {<br><br>    @Autowired<br>    private MockMvc mvc;<br><br>    @RegisterExtension<br>    static LocalDbCreationRule localDynamoDb = new LocalDbCreationRule();<br><br>    @DynamicPropertySource<br>    static void localDynamoDbProperties(DynamicPropertyRegistry registry) {<br>        String port = localDynamoDb.getPort();<br>        registry.add(&quot;zpapez.aws.dynamodb.endpoint&quot;, () -&gt;<br>                String.format(&quot;http://localhost:%s&quot;, port));<br>    }<br><br>    @Autowired<br>    private DynamoDbTable&lt;CountryEntity&gt; countryTable;<br><br>    @BeforeEach<br>    public void beforeEach() {<br>        countryTable.createTable();<br>    }<br><br>    @AfterEach<br>    public void afterEach() {<br>        countryTable.deleteTable();<br>    }<br><br>    @Test<br>    void itShouldGetListOfCountries() throws Exception {<br>        CountryEntity country1 = gson.fromJson(getResourceFileReader(&quot;/CountryControllerIT/itShouldGetListOfCountries/countryEntity1.json&quot;),<br>                CountryEntity.class);<br>        CountryEntity country2 = gson.fromJson(getResourceFileReader(&quot;/CountryControllerIT/itShouldGetListOfCountries/countryEntity2.json&quot;),<br>                CountryEntity.class);<br><br>        countryTable.putItem(country1);<br>        countryTable.putItem(country2);<br><br>        mvc.perform(get(&quot;/api/v1/countries&quot;)<br>                        .contentType(MediaType.APPLICATION_JSON))<br>                .andDo(print())<br>                .andExpect(status().isOk())<br>                .andExpect(content()<br>                        .contentTypeCompatibleWith(MediaType.APPLICATION_JSON))<br>                .andExpect(jsonPath(&quot;$&quot;, hasSize(2)))<br>                .andExpect(jsonPath(&quot;$.[0].countryCode&quot;, is(&quot;BR&quot;)))<br>                .andExpect(jsonPath(&quot;$.[0].countryDisplayName&quot;, is(&quot;Brazil&quot;)))<br><br>                .andExpect(jsonPath(&quot;$.[1].countryCode&quot;, is(&quot;US&quot;)))<br>                .andExpect(jsonPath(&quot;$.[1].countryDisplayName&quot;, is(&quot;United States&quot;)));<br>    }<br>}</pre><h3>Conclusion</h3><p>With the approach described in this article, you can run DynamoDB integration tests without a need of setting up any test infrastructure in AWS. Using the approach of starting the DynamDB Local on a random port, you don’t have to worry about running many of these tests from multiple branches in your CI pipeline.</p><p><a href="https://github.com/zpapez/dynamodb-local-integration-test">See the sample project on GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dba6ca2ccb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Amazon DocumentDB from dockerized Java with TLS enabled]]></title>
            <link>https://zdenek-papez.medium.com/accessing-amazon-documentdb-from-dockerized-java-with-tls-enabled-b87ab7c3aff5?source=rss-4aae8009b7d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b87ab7c3aff5</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-documentdb]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Zdenek Papez]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 17:08:14 GMT</pubDate>
            <atom:updated>2021-01-14T17:08:14.691Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a good set of documentation available when <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/documentdb-development.html">developing with Amazon DocumentDB</a>, including <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html#connect_programmatically-tls_enabled">connecting programmatically with TLS enabled</a>. There is a variety of languages covered there, including Java, but what I did not find was the steps to build a docker container where Java code would be able to connect to the Amazon DocumentDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sox1gxzzZ0MlzdGzvcMVJA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@helloitsammiel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">ammiel jr</a> on <a href="https://unsplash.com/s/photos/container?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Pre-requisites</h4><ul><li>Have <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/quick_start_cfn.html">a DocumentDB cluster ready</a>.</li><li>Read the instructions for <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html#java">Java connecting with TLS enabled</a> from the official AWS documentation.</li><li>Additionally, make sure you can connect to your cluster using the Main class from the sample above (from your IDE).</li></ul><p>For reference, see the <a href="https://github.com/zpapez/java-docker-rds">whole sample project on GitHub</a>.</p><h4>Dockerizing Java with RDS CA in keystore</h4><p>As described in the AWS documentation, <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html#java">Java code needs Amazon RDS CA certificate inside a trust store</a>. In short, we will create the trust store when building the Docker image, bake it into the image, so that later the Java code running in that container can use it.</p><h4>Creating a keystore JKS file</h4><p>AWS documentation in <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html#java">Java connecting with TLS enabled</a> provides a shell script that creates a trust store with the RDS CA certificate. We slightly modify that script to read the trust store password from an argument.</p><p><a href="https://github.com/zpapez/java-docker-rds/blob/main/import_rds_certs.sh">See import_rds_certs.sh</a></p><p>Let’s store the shell script next to the Dockerfile that will:</p><ol><li>Start from openjdk:12-alpine</li><li>Install curl, openssl, and perl needed by the shell script</li><li>Read a <a href="https://docs.docker.com/engine/reference/builder/#arg">docker argument</a></li><li>Run the shell script to create the trust store /certs/rds-truststore.jks baked inside the image</li></ol><pre>FROM openjdk:12-alpine</pre><pre># Install needed packages<br>RUN apk update \<br>        &amp;&amp; apk upgrade \<br>        &amp;&amp; apk --no-cache add curl openssl perl</pre><pre># add truststore needed for connection to DocumentDB cluster<br>COPY import_rds_certs.sh /certs/import_rds_certs.sh<br>ARG trustStorePassword<br>RUN /certs/import_rds_certs.sh $trustStorePassword</pre><h4>Configure Java application</h4><p>AWS documentation tells us to use the keystore in your program by setting the following system properties in your application before making a connection to the Amazon DocumentDB cluster.</p><pre>javax.net.ssl.trustStore: &lt;truststore&gt;<br>javax.net.ssl.trustStorePassword: &lt;truststorePassword&gt;</pre><p>You can use the JavaMain class showed in the AWS documentation to connect to the cluster.</p><p>See our modified <a href="https://github.com/zpapez/java-docker-rds/blob/main/src/main/java/cz/zpapez/javadockerrds/Main.java">Main.java</a> where we will set the SSL system properties using -D flags. Don’t forget to configure your cluster hostname, user, password, database, and collection in the code of Main.java. For running the jar from the docker, we will finalize the Dockerfile with:</p><pre>ENV TRUST_STORE_PASSWORD=$trustStorePassword</pre><pre># copy app<br>COPY build/libs/java-docker-rds.jar /java-docker-rds.jar</pre><pre>CMD java -Djavax.net.ssl.trustStore=/certs/rds-truststore.jks -Djavax.net.ssl.trustStorePassword=$TRUST_STORE_PASSWORD -jar java-docker-rds.jar</pre><p><a href="https://github.com/zpapez/java-docker-rds/blob/main/Dockerfile">See the complete </a><a href="https://github.com/zpapez/java-docker-rds/blob/main/Dockerfile">Dockerfile.</a></p><h4>Build the Docker image</h4><p>When building the image, we will provide the trustStorePassword in --build-arg.</p><pre>docker build --tag my-prj/service:0.0.0-local --build-arg trustStorePassword=somePassword .</pre><h4>Run the container</h4><p>Simply run using the image we have just built:</p><pre>docker run abcdef12345</pre><p>This should output the number of entries in your collection.</p><h3>Troubleshooting</h3><h4>At first, make it connect from your IDE</h4><p>When running into problems, first make sure you can run the Main.java from your IDE and connect to the cluster using -Djavax.net.ssl.trustStore and -Djavax.net.ssl.trustStorePassword. Notice, for that you will need to have the trust store JKS file locally on your laptop — use the <a href="https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html#java">shell script from AWS Documentation</a> to create it. It is better to troubleshoot and debug in your IDE, get familiar with the setup, and then proceed with the Docker container.</p><h4>UnrecoverableKeyException: Password verification failed</h4><p>Together with IOException: Keystore was tampered with, or password was incorrect usually means that you did not point javax.net.ssl.trustStore correctly to the JKS file. Remember that when running from your IDE, the path is on your disk. But when running in the Docker container, it is the path inside that container — /certs/rds-truststore.jks in our sample project.</p><h4>UnrecoverableKeyException: failed to decrypt safe contents entry</h4><p>javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption. In the stack trace, you will also see IOException: keystore password was incorrect and that it exactly it — you did not provide the correct password in javax.net.ssl.trustStorePassword.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b87ab7c3aff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Using Multiple OpenFeign Clients To Authenticate REST API Calls]]></title>
            <link>https://zdenek-papez.medium.com/spring-boot-using-multiple-openfeign-clients-to-authenticate-rest-api-calls-52c74285ce3f?source=rss-4aae8009b7d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c74285ce3f</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[openfeign]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Zdenek Papez]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 13:56:58 GMT</pubDate>
            <atom:updated>2020-11-23T13:56:58.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Boot application that is using OpenFeign client to connect to a 3rd party REST API is a well-known approach. But what if you need to call multiple APIs (like Jira, Slack, Google, …) with different users and authentication methods? This article shows how to set up Basic Authentication for Jira (Zephyr API in particular) and how to use a token for Slack API at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_zMdvjYYUuKeb2YqzkY0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cobblepot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kit Suman</a> on <a href="https://unsplash.com/s/photos/multiple-client?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>The article uses and covers:</h4><ul><li>Spring Boot Application (with one REST controller to process a request)</li><li>Configuration of OpenFeign client for Jira API (Basic Auth)</li><li>Configuration of OpenFeign client for Slack API (Bearer Token Auth)</li><li>Integration test verifying the correct Authorization headers (WireMock)</li></ul><p>For reference see the <a href="https://github.com/zpapez/spring-feign-clients">whole sample project on GitHub</a>.</p><h3>Spring Boot Application</h3><p>Start with <a href="https://start.spring.io/">Spring Initializr</a> and add the necessary dependencies:</p><ul><li>Spring Web — our application itself is a REST API with one endpoint</li><li>OpenFeign — to call Jira and Slack APIs</li><li>Lombok — for some handy getters and setters in DTO classes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOseYOz7Mj_obficmAcyaA.png" /><figcaption>Spring Initializr Dependencies</figcaption></figure><h3>Configure OpenFeign Client for Jira API</h3><p>In this section, we connect to Zephyr part of the Jira API. Let’s use <a href="https://getzephyr.docs.apiary.io/#reference/executionresource/get-list-of-execution/get-list-of-execution">Get list of executions endpoint</a> to showcase the functionality.</p><p>Define your zephyr.api.baseUrl in your application.yml like:</p><pre>zephyr:<br>  api:<br>    baseUrl: <a href="https://jira.my-company.com/jira/rest/zapi/latest">https://jira.my-company.com/jira/rest/zapi/latest</a></pre><p>Zephyr API uses basic authentication. To make your Feign Client provide the correct authorization header, use a configuration class where you define a bean of BasicAuthRequestInterceptor .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/379ca9de5bb48d8ba53379cfefad2634/href">https://medium.com/media/379ca9de5bb48d8ba53379cfefad2634/href</a></iframe><blockquote>Notice — do not mark the whole class as @Configuration . This would make the BasicAuthRequestInterceptor bean available in the whole Spring context and therefore it would be picked up by other Feign Clients. That would interact with the Slack Feign Client that we define next.</blockquote><p>In this article’s sample GitHub project, you can use JIRA_API_USERNAME and JIRA_API_PASSWORD environment variables to provide the credentials. (Notice — your Jira username is usually not your email.)</p><h3>Configure OpenFeign Client for Slack API</h3><p>As a second OpenFeign client let’s configure a client that is <a href="https://api.slack.com/messaging/sending">sending messages to Slack API</a>.</p><p>The Slack API base URL is https://slack.com/api and it uses token authentication. You can find your token in a <a href="https://api.slack.com/start/overview#creating">Slack application that you need to create</a> to start using the API. Token is visible in the configuration page of your application at https://api.slack.com/apps/YOUAR_APP_ID.</p><p>Use configuration to define a RequestInterceptor that adds Authorization header with Bearer token to all Slack requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d3368b650e16801616da1ce06e884d/href">https://medium.com/media/f5d3368b650e16801616da1ce06e884d/href</a></iframe><p>In this article’s sample GitHub project, you can use SLACK_AUTH_TOKEN environment variable to provide the token.</p><h3>Controller and Service</h3><p>Let’s just create a simple controller with GET endpoint at /api/v1/resource that will trigger a service that calls both Jira and Slack APIs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d16f3c3a5c891ef435f1eb8196af7625/href">https://medium.com/media/d16f3c3a5c891ef435f1eb8196af7625/href</a></iframe><p>If all environment variables are correctly set up and correct credentials are provided, this should work — but let’s test it also in an integration test.</p><h3>WireMock Integration Test verifying Authorization Headers</h3><p>When creating 3rd party API calls in our application, we can verify that proper endpoints with a proper request structure were called using <a href="http://wiremock.org/">WireMock</a>. Of course, we also mock responses from those APIs to verify our code (and business process) reacts accordingly.</p><p>Let’s create a JUnit 5 integration test using @SprinBootTest — see <a href="https://github.com/zpapez/spring-feign-clients/blob/main/src/test/java/cz/zpapez/springfeignclients/IntegrationTest.java">the complete integration test on GitHub</a>.</p><ol><li>Add WireMock dependecy in build.gradle <br>testImplementation ‘com.github.tomakehurst:wiremock:2.27.2’</li><li><a href="https://github.com/tomakehurst/wiremock/issues/684">With JUnit 5 we cannot use WireMock through </a><a href="https://github.com/tomakehurst/wiremock/issues/684">@Rule</a> , but we have to use an extension.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5ec9fe3dda181a69c0acd0009844cf/href">https://medium.com/media/cc5ec9fe3dda181a69c0acd0009844cf/href</a></iframe><p>This enables us to create multiple WireMock servers on random ports during the @BeforeAll.</p><pre>@BeforeAll<br><strong>public</strong> <strong>static</strong> <strong>void</strong> beforeAll(@WireMockInstance WireMockServer server1, @WireMockInstance WireMockServer server2) {<br>    <em>zephyrWiremockServer</em> = server1;<br>    <em>slackWiremockServer</em> = server2;<br>}</pre><p>3. Because WireMock servers start on random ports, we need to set up our Jira and Slack API base URLs on the fly. This is done using initializers in @ContextConfiguration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cc502dc14843433a6ea9882f1e93a85/href">https://medium.com/media/6cc502dc14843433a6ea9882f1e93a85/href</a></iframe><p>4. Define fake credentials used in your tests.</p><pre>@SpringBootTest(<br>  webEnvironment = SpringBootTest.WebEnvironment.<strong><em>RANDOM_PORT</em></strong>,<br>  properties = {<br>    &quot;zephyr.api.username=zephyrTestUser&quot;,<br>    &quot;zephyr.api.password=zephyrTestPassword&quot;,<br>    &quot;slack.app.oauth.accessToken=testFakeToken&quot;<br>  })</pre><p>5. Verify that all requests to Jira and Slack APIs had the proper Authorization headers in @AfterEach.</p><pre><em>zephyrWiremockServer</em>.verify(<em>anyRequestedFor</em>(<em>anyUrl</em>())<br>  .withBasicAuth(<strong>new</strong> BasicCredentials(&quot;zephyrTestUser&quot;, &quot;zephyrTestPassword&quot;)));</pre><pre><em>slackWiremockServer</em>.verify(<em>anyRequestedFor</em>(<em>anyUrl</em>())<br>  .withHeader(&quot;Authorization&quot;, <em>equalTo</em>(&quot;Bearer testFakeToken&quot;)));</pre><p>6. You should also verify that there was exactly one Authozitation header in your requests. There could be potentially multiple Authozitation headers and WireMock would match any of them. To assert that there is only one header that you expect is a bit tricky with WireMock, but can be achieved using addMockServiceRequestListener in @BeforeAll and later asserting it in @AfterEach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967df7adafdf2ce68e3af05eb9b5b144/href">https://medium.com/media/967df7adafdf2ce68e3af05eb9b5b144/href</a></iframe><p>7. Finally, create a test method where you call the controller, mock the Jira, and Slack API responses, and verify the response of your controller.<br><a href="https://github.com/zpapez/spring-feign-clients/blob/707dd17fd5cc3a93a7ffa031a8fa1de405e19c8c/src/test/java/cz/zpapez/springfeignclients/IntegrationTest.java#L102">https://github.com/zpapez/spring-feign-clients/blob/707dd17fd5cc3a93a7ffa031a8fa1de405e19c8c/src/test/java/cz/zpapez/springfeignclients/IntegrationTest.java#L102</a></p><h3>Troubleshooting</h3><h4>Turn on full logging of OpenFeign clients</h4><pre>@Configuration<br><strong>public</strong> <strong>class</strong> MyConfiguration {<br>  @Bean<br>  Logger.Level feignLoggerLevel() {<br>    <strong>return</strong> Logger.Level.<strong><em>FULL</em></strong>;<br>  }<br>}</pre><p>and in properties</p><pre>logging.level.cz.zpapez.springfeignclients.zephyr.ZephyrFeignClient: DEBUG<br>logging.level.cz.zpapez.springfeignclients.slack.SlackFeignClient: DEBUG</pre><p>This setup prints all requests including headers and also responses that are being sent. You can verify proper values in proper authorization headers by reading these logs.</p><h4>401 Unauthorized</h4><p>Double-check that you provide the correct credentials (like Jira username, not email) in the environment variables. Maybe also try to make the same request work usingcurl.</p><h4>No default constructor</h4><p>No default constructor found when running the @SpringBootTest with context configuration initializers @ContextConfiguration(initializers = AppIntegrationTestPropertyInitializer.<strong>class</strong>).</p><pre>Caused by: org.springframework.beans.BeanInstantiationException:<br>Failed to instantiate [cz.zpapez.springfeignclients.IntegrationTest$AppIntegrationTestPropertyInitializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException:<br>cz.zpapez.springfeignclients.IntegrationTest$AppIntegrationTestPropertyInitializer.&lt;init&gt;()</pre><p>The class specified as the initializer (implementing ApplicationContextInitializer) cannot be an inner class of the integration test class. Make sure that you define the property initializer class after the clossing } of the integration test class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c74285ce3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Istio Authorization Using OKTA User Groups in JWT Claims behind AWS Application Load Balancer]]></title>
            <link>https://zdenek-papez.medium.com/istio-authorization-using-okta-user-groups-in-jwt-claims-behind-aws-application-load-balancer-191f26779cad?source=rss-4aae8009b7d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/191f26779cad</guid>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[aws-load-balancer]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[okta]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Zdenek Papez]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 18:45:18 GMT</pubDate>
            <atom:updated>2020-04-22T18:45:18.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>Okta Authentication and Authorization for your AWS EKS</h3><p>When deploying services to Kubernetes cluster, Istio is often used for handling request routing and user authentication and authorization. In this article we present Istio configuration together with Okta and AWS Application Load Balancer (ALB) on top of Elastic Kubernetes Service. JSON Web Token (JWT) with custom user group claim issued by Okta is used for authorization. The ALB enforces Okta authentication and is able to check the health of cluster instances.</p><p>Together with <a href="https://medium.com/u/b69b9ebc6a51">Jakub Snor</a> and <a href="https://medium.com/u/95c607ffc254">Vladimir Valouch</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS3iJC4ARS0LrrObBBBFCg.png" /><figcaption>Okta Authentication and Authorization Overview</figcaption></figure><h3>Pre-requisites</h3><ul><li>kubectl <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">installed</a></li><li>running <a href="https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html">Kubernetes cluster in AWS</a></li></ul><h3>Istio Deployment</h3><p>We showcase the role-based access on the simple <a href="http://www.httpbin.org/">httpbin</a> application used in <a href="https://istio.io/docs/tasks/security/authorization/authz-jwt/">Istio samples</a>.</p><pre>kubectl create ns foo<br>kubectl apply -f &lt;(istioctl kube-inject -f samples/httpbin/httpbin.yaml) -n foo</pre><h3>Create New Application in Okta</h3><p>You can use Okta dev account to do the set up as well as your production Okta. Open the Admin dashboard and make sure you are using Classic UI as some options are not available in theDeveloper Console. The first thing you need to create is a new application. Go to Applications link in Applications drop-down menu and click the Add Application button. We are adding a custom application so click the Create New App button. Keep platform as Web and choose OpenID Connect Sign on method. Confirm by clicking on the Create button.</p><figure><img alt="Create new application in Okta" src="https://cdn-images-1.medium.com/max/1024/1*R7yBJcvmBCh_79qk78rSdw.png" /><figcaption>Create new application in Okta</figcaption></figure><p>On the next page, type in your application name and optionally upload its icon. Configure Login redirect URIs to some temporary value, for example http://localhost. We will change this value once we have an Application Load Balancer created. Confirm by clicking on the Save button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqFch0Gi7Mm6BAdBcETMew.png" /><figcaption>Configure new application in Okta</figcaption></figure><h3>Create AWS Application Load Balancer with Okta Auth</h3><p>We create an application load balancer using CloudFormation. <a href="https://gist.github.com/zpapez/5b28d3429cdd2113b4b99854c5bd10f6">See the whole CloudFormation template</a>. Below we describe important parts of the template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9877b5659e66aeabe7b7a86c72427e39/href">https://medium.com/media/9877b5659e66aeabe7b7a86c72427e39/href</a></iframe><p>It configures AWS::ElasticLoadBalancingV2::Listener to use Okta authentication in section AuthenticateOidcConfig.</p><p>It allows “health check” endpoint communication on endpoint /status/200. See the forward rule without Okta authentication in HealthCheckAllowRule.</p><p>An important part of the load balancer is the HealthCheckPath configuration of AWS::ElasticLoadBalancingV2::TargetGroup. We use /status/200 where httpbin responses with OK status. Later we will open this endpoint on the Istio level to be accessible without authentication.</p><p>In HttpPlainListener we also redirect traffic from HTTP to HTTPS.</p><h4>Parameters of the CloudFormation template</h4><ul><li>CertificateArn — find it in AWS Certificate Manager in details of your certificate.</li><li>authorizationEndpoint, issuer, tokenEndpoint, userInfoEndpoint — defaults of these are prepared, just replace dev-12345.okta.com with your Okta account.</li><li>clientId and clientSecret — find it Okta -&gt; Applications -&gt; your app -&gt; General tab -&gt; section Client Credentials.</li><li>VpcId, SubnetId, SubnetIdB, ELBSGId— use same VPC, subnets and security group that classic load balancer created by kubernetes cluster.</li><li>Instance1, Instance2 — point the target group to the same instances that classic load balancer created by kubernetes cluster points to.</li><li>TargetTransportPort — the port where istio-system exposes port 80, run kubectl get svc istio-ingressgateway -n istio-system to find it (usually 32252, 32280, …).</li></ul><h4>Configure Okta Application with the Load Balancer</h4><p>Once you have the ALB ready, you can configure your Okta application.</p><ol><li>In the Classic UI of Okta Admin, open the application list and click on your application.</li><li>Switch to General tab and edit it by clicking on Edit button.</li><li>Check Implicit (Hybrid) <em>Allowed grant type</em>.</li><li>Change <em>Login redirect URIs</em> to point to your load balancer. This value must be absolute URI and you can use either an A Record of your ALB or a CNAME you mapped to it. Do not forget to add the path /oauth2/idpresponse and to include a protocol (HTTPS).</li><li>Set Login initiated by to Either Okta or App.</li><li>Check both <em>Display application icon to users</em> and <em>Display application icon in the Okta Mobile app.</em></li><li>Set <em>Initiate login URI</em> to your entry point to the application. Confirm everything by clicking on the Save button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRcawvMspO0BJEz-r35tPw.png" /><figcaption>Configure your application in Okta</figcaption></figure><h3>Exposing Service in Istio</h3><p>We expose our httpbin service using Istio gateway.</p><h4>Gateway</h4><p><a href="https://istio.io/docs/tasks/traffic-management/ingress/ingress-control/#configuring-ingress-using-an-istio-gateway">Configure a gateway</a> on port 80 for HTTP traffic.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: networking.istio.io/v1beta1<br>kind: Gateway<br>metadata:<br>  name: httpbin-gateway<br>  namespace: foo<br>spec:<br>  selector:<br>    istio: ingressgateway<br>  servers:<br>  - hosts:<br>    - &#39;*&#39;<br>    port:<br>      name: http<br>      number: 80<br>      protocol: HTTP<br>EOF</pre><h4>Virtual Service</h4><p>Configure routes for traffic entering via the Gateway to go to our httpbin service on port 8000.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: networking.istio.io/v1beta1<br>kind: VirtualService<br>metadata:<br>  name: httpbin<br>  namespace: foo<br>spec:<br>  hosts:<br>  - &quot;*&quot;<br>  gateways:<br>  - httpbin-gateway<br>  http:<br>  - route:<br>    - destination:<br>        port:<br>          number: 8000<br>        host: httpbin.foo.svc.cluster.local<br>EOF</pre><h3>Intermediate Testing</h3><p>At this point you should be able to access your application through the load balancer DNS name. It should redirect you to the Okta login screen and upon successful login to the httpbin application.</p><p>If load balancer returns 504 Gateway Timeout, double-check that the target group shows that both instances are “healthy”.</p><p>You can use endpoint /headers to inspect what headers Okta added to your request. You can find your JWT token in x-amzn-oidc-accesstoken and you can <a href="http://www.jwt.io/">decode it</a>. Notice that so far there are no user groups present in your token. We will set it up in the next section and use it for Istio authorization.</p><h3>Okta Groups and Custom JWT Token Claims</h3><p>The application should be available to a managed set of users. We create an Okta group and add our users to this group to grant access to our application.</p><ol><li>In the Classic UI of Okta Admin, Go to Groups link in Directory drop-down menu.</li><li>Create a new group by clicking on Add Group button.</li><li>Name your group and optionally write down some description for it and confirm by clicking on Add Group button.</li><li>Open the group and add people to this group by clicking on Manage People button.</li><li>Assign your application to this group by clicking on Manage Apps.</li></ol><p>This completes the authentication part — only authenticated users can now access your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCuZkzi6KuhEZN_i_Qx_ig.png" /><figcaption>Add group in Okta</figcaption></figure><p>To do the authorization we are going to validate the JWT provided by Okta and verify the user is authorized to use our application. We will check that the user is indeed in the group that has access to our application. Before we can do that though, we need to ensure such information is included in one of JWT’s claims.</p><ol><li>In the Classic UI of Okta Admin, open the application list and click on your application.</li><li>Switch to Sign On tab.</li><li>Click on the Edit button in the <em>OpenID Connect ID Token</em> block.</li><li>Name your <em>Groups claim filter</em> and select Equals from the drop-down menu followed by the name of the group. Now this group is included in the JWT claim. You can also choose Matches regex followed by .* to include all the groups of the user.</li><li>Confirm your configuration by clicking the Save button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2ik258iZ26egi9OdxE5KA.png" /><figcaption>Configure Sign On of your application</figcaption></figure><blockquote>Verify — after the claims are set up, verify using the /headers endpoint that your JWT token in headerx-amzn-oidc-accesstoken now contains the groups.</blockquote><h3>Istio Okta Authorization</h3><h4>Request Authentication</h4><p>We configure RequestAuthentication in our namespace foo to verify that JWT token in the request is valid and issued by our Okta account.</p><p>Okta is using specific x-amzn-oidc-accesstoken header for the JWT token. We need to instruct Istio in fromHeaders to read the JWT token from the custom header, not from the default authentication header.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: security.istio.io/v1beta1<br>kind: RequestAuthentication<br>metadata:<br>  name: jwt-from-okta<br>  namespace: foo<br>spec:<br>  jwtRules:<br>  - issuer: &quot;<a href="https://dev-715794.okta.com/oauth2/default">https://dev-12345.okta.com/oauth2/default</a>&quot;<br>    jwksUri: &quot;<a href="https://dev-715794.okta.com/oauth2/default/v1/keys">https://dev-12345.okta.com/oauth2/default/v1/keys</a>&quot;<br>    forwardOriginalToken: true<br>    fromHeaders:<br>    - name: x-amzn-oidc-accesstoken<br>EOF</pre><blockquote>Notice — at this point Istio refuses invalid tokens, but it still allows traffic without any tokens. We will enforce tokens below using AuthorizationPolicy. <a href="https://istio.io/docs/tasks/security/authorization/authz-jwt/#allow-requests-with-valid-jwt-and-list-typed-claims">More in Istio documentation.</a></blockquote><h4>Authorization based on Okta Group</h4><p>Above we instructed RequestAuthentication to use x-amzn-oidc-accesstoken header. Therefore we can now access the JWT token claims in AuthorizationPolicy.</p><p>We open our “health check” endpoint /status/200 to everyone without JWT token. But for all other paths we require requestPrincipal from our Okta account. Additionally, we enforce that the user belongs to “httpbin” Okta group that we read from request.auth.claims[groups].</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: security.istio.io/v1beta1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: httpbin-allow-health-policy<br>  namespace: foo<br>spec:<br>  selector:<br>    matchLabels:<br>      app: httpbin<br>  action: ALLOW<br>  rules:<br>  - to:<br>    - operation:<br>       paths: [&quot;/status/200&quot;]<br>  - from:<br>    - source:<br>       requestPrincipals: [&quot;<a href="https://dev-715794.okta.com/oauth2/default/*">https://dev-12345.okta.com/oauth2/default/*</a>&quot;]<br>    when:<br>    - key: request.auth.claims[groups]<br>      values: [&quot;httpbin&quot;]<br>EOF</pre><blockquote>Notice — you should have RequestAuthentication and AuthorizationPolicy in the same namespace, otherwise the policy cannot correctly see the request.auth.claims that are filled from custom header x-amzn-oidc-accesstoken in the <em>RequestAuthentication.</em></blockquote><h3>Final Verification</h3><ul><li>Everyone (even without Okta) should be able to access /status/200.</li><li>If your Okta user belongs to group “httpbin”, you should be able to access httpbin.</li><li>If Okta user is not in group “httpbin”, you should get RBAC: Access denied.</li></ul><h4>Troubleshooting</h4><p><strong>504 Gateway Timeout</strong> — check that the target group monitoring shows both instances as healthy. Double-check, that target group communicates with instances on correct TargetTransportPort.</p><p><strong>Always getting RBAC: Access Denied</strong> — double-check that your JWT token includes custom claim groups and one of the groups is “httpbin”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191f26779cad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>