<?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 James Powell on Medium]]></title>
        <description><![CDATA[Stories by James Powell on Medium]]></description>
        <link>https://medium.com/@jamespowell99?source=rss-93747b07fb72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2vlYydWigRjAJkUc</url>
            <title>Stories by James Powell on Medium</title>
            <link>https://medium.com/@jamespowell99?source=rss-93747b07fb72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:20:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jamespowell99/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[Authentication and Authorisation using OIDC and OAuth 2. Part 3]]></title>
            <link>https://medium.com/@jamespowell99/authentication-and-authorisation-using-oidc-and-oauth-2-part-3-f747ba98e9b7?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/f747ba98e9b7</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 08:49:45 GMT</pubDate>
            <atom:updated>2023-06-27T20:14:45.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJWlDXIuBFCi87qywgwDBw.jpeg" /></figure><h3>Part 3: A confidential client — traditional server side application</h3><h3>Introduction</h3><p>This is the third article in this series. <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a> was an introduction to the world of Authentication and Authorisation. <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> created and demonstrated all the components involved in providing security where the client is ‘public’ and cannot store secrets securely. This article builds on that and creates a similar arrangement, this time where the client is ‘confidential’.</p><p>In this example, the client itself is a traditional web application in the form of a Spring Boot application that serves HTML content as ‘Server Side Rendered’ pages, meaning the server itself creates the HTML that will be returned to, and ultimately be displayed in the user’s browser. These types of applications typically involve a HTTP session to maintain user state, the server application will return a Set-Cookie HTTP header to store the session identifier in the user’s browser as a cookie — this cookie will then be returned on each HTTP request the browser makes, allowing the application to lookup any data associated with the session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*8hraiKDL7rCvWBek.png" /></figure><p>This article aims to do the following</p><ul><li>Re-use the Keycloak instance set up in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> as the Authorisation Server.</li><li>Create a new ‘confidential’ OAuth client in Keycloak.</li><li>Create a Spring Boot traditional Web Application to act as the OAuth client.</li><li>Show how all the moving parts are wired together to provide authentication and authorisation via OIDC / OAuth2.</li></ul><h3>Creating a Keycloak confidential client</h3><p>With the same Keycloak instance running in Docker and configured as it was in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> of this series, we will now create a new OAuth client in Keycloak for this scenario. Note that this time, the client will be of type ‘confidential’, rather than ‘public’.</p><p><strong>Create Oauth Client</strong></p><p>To create a client, ensuring that the lydtech realm is selected in the Keycloak admin console at <a href="http://localhost:8080/admin">http://localhost:8080/admin</a>, navigate to ‘Clients’ and click ‘Create Client’. You will have 3 pages to complete.</p><p>Under ‘General Settings’, Client Type needs to be ‘OpenID Connect’. Choose an appropriate clientID — ‘lydtech-confidential-client’ in this case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X1DZzuFB422G3sSg.png" /></figure><p>Next under ‘Capability config’, ensure the following:</p><ol><li>Ensure ‘Client authentication’ is enabled. This is what makes this client ‘confidential’, rather than ‘public’.</li><li>For authentication flows, ensure only ‘Standard flow’ is selected — this is the ‘Authorisation Code’ flow that we focused on in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>. ‘Direct access grants’ will be enabled by default, but we do not want this; this is effectively a ‘Password’ grant type which is discouraged, and deprecated in OAuth 2.1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p4ByP8CQLWIq6cnC.png" /></figure><p>Finally, under ‘Login Settings’ we only need to provide a URL for ‘Valid redirect URIs’ — anything for localhost:8082 is fine in our case (our Spring Boot app will be running on localhost:8082), so enter http://localhost:8082/*. We do not need to set a value for ‘Web origins’ - in this example, there will be no cases of Javascript in the browser calling any Keycloak endpoints directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xWHMgjqxDbcsSs7R.png" /></figure><p>We will test this new client once we’ve created the Spring Boot application.</p><p>Now that the client has been created. There is one notable difference as a result of the fact that this is a ‘confidential’ client. Note the additional ‘Credentials’ tab when viewing the client in the Keycloak admin area. From this tab, you can get the value of the client_secret that the Spring Boot application will need to pass across to the Authorisation Server for every call to /token as we will see later. For now, just be aware of where this value is made available from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dci4rKnFd5qYSEyq.png" /></figure><p>As a final step, in order to user Spring’s oauth2 client support, we must tell Keycloak to add the Realm Roles to the response of the /userInfo endpoint. To do this, navigate to Client Scopes-&gt;roles-&gt;Mappers-&gt;realm roles. Enable the Add to userinfo button as per the screenshot below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O5U9FFwZDH_GpFf9.png" /></figure><h3>Creating a Spring Boot application</h3><p><strong>Create the project</strong></p><p>Now that we have a client configured in the Authorisation Server, we can create our Spring Boot application which will act as the OAuth client. We will follow the approach from the <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> article and add 3 endpoints to demonstrate Authorisation in play.</p><p>Visit <a href="https://start.spring.io/">start.spring.io</a> to create the template for the application. Use settings such as those in the image below but be sure to include the following dependencies:</p><ul><li>Spring Web — Needed to provide the Web components</li><li>Lombok — Helps to reduce boilerplate code</li><li>OAuth2 Client — pulls in the required dependencies to configure the service as an OAuth client</li><li>Thymeleaf — A templating engine for generating HTML</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LxWgg1Z5Kedk6yH-.png" /></figure><p>Click Generate to download a zip file containing the project, unzip this project in a suitable directory and open it in your favourite IDE.</p><p><strong>Create Controller</strong></p><p>Similar to our public client example from <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a>, we will introduce 3 areas in our application in order to demonstrate authorisation. The resulting endpoints are as follows:</p><ul><li>‘/’ — the home page. This is public and does not require any authentication to be able to access</li><li>‘/users’ — is an area that is available to authenticated users and admin users</li><li>‘/admin’ — is an area only available to authenticated admin users</li></ul><p>Complete <a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/blob/main/src/main/java/dev/lydtech/security/simpleconfidentialclient/controllers/MyController.java">controllers/MyController.java</a> file available in the Github repository</p><pre>package dev.lydtech.security.simpleconfidentialclient.controllers;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.security.core.AuthenticatedPrincipal;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.ui.Model;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import java.security.Principal;<br><br>@Controller<br>@Slf4j<br>@RequestMapping(&quot;/&quot;)<br>public class MyController {<br><br>    @GetMapping(path = &quot;/&quot;)<br>    public String index(Model model) {<br>        // Need to look up principal here. By including it as a method param, Spring will redirect to login (which isn&#39;t required for this endpoint)<br>        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();<br>        if (principal instanceof AuthenticatedPrincipal user) {<br>            model.addAttribute(&quot;username&quot;, user.getName());<br>        }<br>        return &quot;public&quot;;<br>    }<br><br>    @GetMapping(path = &quot;/users&quot;)<br>    public String users(Principal principal, Model model) {<br>        model.addAttribute(&quot;username&quot;, principal.getName());<br>        return &quot;users&quot;;<br>    }<br><br>    @GetMapping(path = &quot;/admin&quot;)<br>    public String admin(Principal principal, Model model) {<br>        model.addAttribute(&quot;username&quot;, principal.getName());<br>        return &quot;admin&quot;;<br>    }<br>}</pre><p>Some key points to highlight in this class:</p><ol><li>The class is annotated with @Controller and @RequestMapping to allow it to act as a Controller</li><li>@GetMapping is used for each of the 3 endpoints. Each of the endpoints has a Model parameter and, using the MVC pattern, objects are attached to the model to be displayed in the appropriate view. Each method returns a string which is the name of the View it maps to. The 2 secured endpoints (/users and /admin) have a second method parameter of type java.security.Principal — this will contain details of the authenticated user.</li><li>Note that the unauthenticated endpoint (/home) does not include a Principal parameter — it does return details of any associated Principal, but it must look this up otherwise Spring redirects unauthenticated users to the login page before they can even see the home page</li></ol><p><strong>Create the Views</strong></p><p>Thymeleaf is used as the templating engine to create HTML. The full template files required are available in the <a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/tree/main/src/main/resources/templates">GitHub repository</a>. All 4 must be copied into src/main/resources/templates, as per Spring Boot convention:</p><ul><li><a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/tree/main/src/main/resources/templates/layout.html">layout.html</a></li><li><a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/tree/main/src/main/resources/templates/public.html">public.html</a></li><li><a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/tree/main/src/main/resources/templates/admin.html">admin.html</a></li><li><a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/tree/main/src/main/resources/templates/users.html">users.html</a></li></ul><p>Excerpts from key template files are shown below:</p><p><em>public.html</em></p><pre>&lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;jumbotron text-center&quot;&gt;<br>        &lt;h1&gt;Sample App&lt;&lt;h1&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        &lt;div class=&quot;well&quot;&gt;<br>            &lt;a th:href=&quot;@{/admin}&quot;&gt;Admin Area&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;well&quot;&gt;<br>            &lt;a th:href=&quot;@{/users}&quot;&gt;User Area&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;well&quot; th:if=&quot;${username != null}&quot;&gt;<br>            &lt;p&gt;You are logged in as &lt;span th:text=&quot;${username}&quot;&gt;--name--&lt;/span&gt;&lt;/p&gt;<br>            &lt;a href=&quot;/logout&quot;&gt;Logout&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;well&quot; th:if=&quot;${username == null}&quot;&gt;<br>            &lt;p&gt;You are not logged in &lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p><em>admin.html / users.html</em></p><p>These views represent the secured pages. They are very similar to one another so only the admin page has been included below. A simple header is displayed to show which page this is and the username is displayed (which was set on the Model component by the Controller above). Both pages also display a logout option because in order to see this page, the user must be authenticated</p><pre>&lt;div id=&quot;container&quot;&gt;<br>    &lt;div class=&quot;jumbotron text-center&quot;&gt;<br>        &lt;h1&gt;Sample App&lt;/h1&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        &lt;div class=&quot;well&quot;&gt;<br>            &lt;h1&gt;<br>                Admin Area<br>            &lt;/h1&gt;<br>            &lt;p&gt;Hello, &lt;span th:text=&quot;${username}&quot;&gt;--name--&lt;/span&gt;.&lt;/p&gt;<br>            &lt;div&gt;<br>                &lt;a href=&quot;/logout&quot;&gt;Logout&lt;/a&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>Configure Security</strong></p><p>To configure the security of this application, we add a Spring Configuration class as follows. Complete <a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/blob/main/src/main/java/dev/lydtech/security/simpleconfidentialclient/SecurityConfig.java">SecurityConfig.java</a> file available in the Github repository</p><pre>package dev.lydtech.security.simpleconfidentialclient;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.core.GrantedAuthority;<br>import org.springframework.security.core.authority.SimpleGrantedAuthority;<br>import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;<br>import org.springframework.security.core.session.SessionRegistryImpl;<br>import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;<br>import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;<br>import org.springframework.security.oauth2.core.oidc.OidcUserInfo;<br>import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;<br>import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;<br>import java.net.URI;<br>import java.util.Collection;<br>import java.util.HashSet;<br>import java.util.Map;<br>import java.util.Set;<br>import static org.springframework.security.config.Customizer.withDefaults;<br><br>@Configuration<br>@EnableWebSecurity<br>class SecurityConfig {<br><br>    @Bean<br>    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {<br>        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());<br>    }<br><br>    @Bean<br>    OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler(ClientRegistrationRepository clientRegistrationRepository) {<br>        OidcClientInitiatedLogoutSuccessHandler successHandler = new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);<br>        successHandler.setPostLogoutRedirectUri(URI.create(&quot;http://localhost:8082&quot;).toString());<br>        return successHandler;<br>    }<br><br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http, OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler) throws Exception {<br>        http.authorizeHttpRequests(authorise -&gt;<br>                authorise<br>                        .requestMatchers(&quot;/&quot;)<br>                        .permitAll()<br>                        .requestMatchers(&quot;/admin*&quot;)<br>                        .hasRole(&quot;admin&quot;)<br>                        .requestMatchers(&quot;/users*&quot;)<br>                        .hasAnyRole(&quot;user&quot;, &quot;admin&quot;)<br>                        .anyRequest()<br>                        .authenticated());<br>        http.oauth2Login(withDefaults())<br>                .logout(logout -&gt;<br>                        logout.logoutSuccessHandler(oidcLogoutSuccessHandler));<br>        return http.build();<br>    }<br>...</pre><p>Note the following:</p><ol><li>The class is annotated with @Configuration and @EnableWebSecurity</li><li>A SessionAuthenticationStrategy is registered with a default implementation to manage sessions and authenticated principals.</li><li>An OidcClientInitiatedLogoutSuccessHandler Bean is configured which will allow user-initiated logouts to force a logout in Keycloak, via the browser.</li><li>Adds Authorisation config to allow</li></ol><ul><li>Public access to home (‘/’)</li><li>Admin only access to anything under ‘/admin’</li><li>User and admin access to /users</li></ul><p>5. Registers the OidcClientInitiatedLogoutSuccessHandler instance as a logout success handler in Spring Security.</p><p>There is also one more Bean registered in this config file which is included below. It performs a similar function to the class in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> that extracts realm roles (this time from the /userinfo response) and creates Granted Authorities to attach to the resulting Principal</p><pre>    @Bean<br>    public GrantedAuthoritiesMapper userAuthoritiesMapper() {<br>        return (authorities) -&gt; {<br>            Set&lt;GrantedAuthority&gt; mappedAuthorities = new HashSet&lt;&gt;();<br>            authorities.forEach(authority -&gt; {<br>                if (authority instanceof OidcUserAuthority oidcUserAuthority) {<br>                    OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();<br>                    // Map the claims found in idToken and/or userInfo<br>                    // to one or more GrantedAuthority&#39;s and add it to mappedAuthorities<br>                    Map&lt;String, Object&gt; realmAccess = userInfo.getClaim(&quot;realm_access&quot;);<br>                    Collection&lt;String&gt; realmRoles;<br>                    if (realmAccess != null<br>                            &amp;&amp; (realmRoles = (Collection&lt;String&gt;) realmAccess.get(&quot;roles&quot;)) != null) {<br>                        realmRoles<br>                                .forEach(role -&gt; mappedAuthorities.add(new SimpleGrantedAuthority(&quot;ROLE_&quot; + role)));<br>                    }<br>                }<br>            });<br>            return mappedAuthorities;<br>        };<br>    }</pre><p><strong>Add properties</strong></p><p>Finally, lets add the required properties for Spring Boot to configure everything correctly. Replace the contents of src/main/resources/application.properties with <a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/blob/main/src/main/resources/application.properties">application.properties</a> explained in the extracts below</p><p>Use port 8082 for this application</p><pre>server.port=8082</pre><p>Configure the Spring Security oauth client settings with the correct client-id and secret (set the client-secret to the secret value of the Oauth client in Keycloak as configured earlier). Also indicate that the authorization_code grant type should be used and only the openid and profile scopes are required for now</p><pre>spring.security.oauth2.client.registration.keycloak.client-id=lydtech-confidential-client<br>spring.security.oauth2.client.registration.keycloak.client-secret=&lt;REPLACE_ME&gt;<br>spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code<br>spring.security.oauth2.client.registration.keycloak.scope=openid,profile</pre><p>Configure the issuer-uri and the user-name-attribute to be extracted from the JWTs preferred_username field</p><pre>spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/lydtech<br>spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username</pre><p>Set the logging level of all Spring Security classes to trace, this is very useful for showing what goes on at each step</p><pre>logging.level.org.springframework.security=trace</pre><h3>Testing the end result</h3><p><strong>Start the applications</strong></p><p>Ensure Keycloak is running in Docker. Run the Spring Boot application using the command ./mvnw spring-boot:run or running the SimpleConfidentialClientApplication in your IDE</p><p><strong>Test public home page</strong></p><p>Access <a href="http://localhost:8082/">http://localhost:8082</a> in a browser. You should see a screen similar to the one below. Note that you are not logged in but are still allowed to access this page, as per the configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lYXz54cIYajhKv4v.png" /></figure><p><strong>Test admin user access</strong></p><p>Click the ‘user Area’ link or access <a href="http://localhost:8082/users">http://localhost:8082/users</a> in a browser. Note that you are immediately redirected to the Keycloak login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xB2_nYiRs1E3JG9g.png" /></figure><p>Log in using the admin@example.com user and observe that you are redirected to the /users page as per the image below. The username is shown on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*opQ1ZXCloaNyOeMJ.png" /></figure><p>Head back to <a href="http://localhost:8082/">http://localhost:8082</a> and see that the message has now changed to show that you are logged in as the admin user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OtYMLluKEI5_hoOq.png" /></figure><p>Finally, head to <a href="http://localhost:8082/admin">http://localhost:8082/admin</a> or follow the ‘Admin Area’ link and observe that you are shown the admin page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jUiNlU-8gsBzL23E.png" /></figure><p><strong>Testing a non Admin user</strong></p><p>Click the Logout link. You will be redirected back to the home page. Click the ‘Admin Area’ link but this time log in as the user@example.com non admin user. Observe that you are not allowed to access this page because you lack the ‘admin’ role. The error page needs configuring in Spring Boot but you can see that access was denied via a HTTP 403 response code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rMS_a3gTa48f1uFQ.png" /></figure><h3>Following the Authorisation Code flow</h3><p>In the same way as we did for the public client scenario, let’s follow the steps of the Authorisation Code flow. The sequence diagram below depicts this flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1xOwZneyaYCrnjtj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*QrMnA2aix8ezm7OGUQmcKA.png" /><figcaption><strong>Initial GET request to page</strong></figcaption></figure><p><strong>Request</strong></p><p>Initially, the user’s browser makes a request to visit the /users page. Note there are no significant query params or HTTP headers present here. Also note that there is no session cookie sent across — this is the very first call to the application from the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ViYP06SJLAMII5RtsIna3g.png" /></figure><p><strong>Response</strong></p><p>Spring Security determines that there is no authenticated user (in fact there is no actual session at this point), and therefore issues a HTTP redirect to the Authorisation Server’s /authorize endpoint. The response will also set a session cookie containing the newly created session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-4UhJqFcNPKRFhKElbQLA.png" /></figure><p>Note there is actually one more call involved here via a redirect but for brevity this has been omitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*0rLqJ-4xI_VPUlvdpGrhvA.png" /><figcaption><strong>Authorisation Request</strong></figcaption></figure><p><strong>Request</strong></p><p>The browser now follows the redirect to the Authorisation server’s /authorize endpoint, i.e. step 1 of the 2-part Authorisation Code Grant type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0fKBJKcpVImQ4E4vn9tCA.png" /></figure><p><strong>Response</strong></p><p>The response from Keycloak is a HTML page containing a login page with a username &amp; password field and a ‘Log in’ button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*IAy1eC_vFTgkvK0HWug7JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*jIK-_n3ztHlQiZ9QoF7G0w.png" /><figcaption><strong>User authenticates with Keycloak</strong></figcaption></figure><p><strong>Request</strong></p><p>The user types in their username &amp; password then clicks Log In</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpPLUqLdTBvSPLrgpeFvGw.png" /></figure><p><strong>Response</strong></p><p>Upon a successful log in, Keycloak redirects back to our application as we requested via the redirect_uri</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTywviPY51ASPcomwDrF-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*qRa7uNwgdHBbhVfdworutA.png" /><figcaption><strong>Redirect back to app following successful authentication</strong></figcaption></figure><p><strong>Request</strong></p><p>The browser follows the redirect back to the Spring Boot application, to an endpoint that is made available by Spring security for the purpose of processing these callbacks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmtepiezkKjQwbsMfgs7dg.png" /></figure><p><strong>Response</strong></p><p>The eventual response will redirect the browser back to the page the user wanted in the first place (/users in this case). This only happens after an OAuth token has been successfully generated (see step 5 below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAvJcRc_nfPFvypB0dbg_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*-GqZFp7GCD-IyGAly1pugg.png" /><figcaption><strong>Token request</strong></figcaption></figure><p><strong>Request</strong></p><p>The Spring Boot application makes the /token call to the Authorisation Server in order to exchange the authorisation code for an access token, i.e. step 2 of the 2-part Authorisation Code Grant type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01y0XolDZ5Ck0Hjx8yJVhw.png" /></figure><p><strong>Response</strong></p><p>This includes an access token, refresh token and (because we requested the oidc scope) an ID token (all in the form of JWT tokens). Note the access tokens have been truncated for readability. They are included in full below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_ivUBupzD-CLgcUNi0nvg.png" /></figure><p>Note you could copy any of these tokens into <a href="https://jwt.io/">jwt.io</a> to view the full contents.</p><p>access_token</p><pre>eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqanoyd0ZEVXhzUGdZYWowcV9FbzUtdEgxWlAzMldwMldNdDltY3RCal9RIn0.eyJleHAiOjE2ODU5ODQ0NjUsImlhdCI6MTY4NTk4NDE2NSwiYXV0aF90aW1lIjoxNjg1OTg0MTY1LCJqdGkiOiJlMTgwN2E5MS0xMDk3LTRmZGEtYjQ3Yi1lNGFmNDk0MmIwNzkiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL2x5ZHRlY2giLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiYmRiOWY5ZWYtOWJlNy00Mzc2LTk5NjQtYzQwYzQzOTRkZjQ3IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoibHlkdGVjaC1jb25maWRlbnRpYWwtY2xpZW50Iiwibm9uY2UiOiI0bXlwZHJieDZ6UUVGN1ZfYmtlYWhoV0l6dldfaE1IdXR1ZlRTODAzRjZNIiwic2Vzc2lvbl9zdGF0ZSI6ImY2ZmE4YTk5LTI0MWYtNGQ2YS04Y2JlLWI4MzhmNmY1MDVjNyIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLWx5ZHRlY2giLCJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIiwidXNlciJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoib3BlbmlkIGVtYWlsIHByb2ZpbGUiLCJzaWQiOiJmNmZhOGE5OS0yNDFmLTRkNmEtOGNiZS1iODM4ZjZmNTA1YzciLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwibmFtZSI6IkpvaG4gSm9zZXBoIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidXNlckBleGFtcGxlLmNvbSIsImdpdmVuX25hbWUiOiJKb2huIiwiZmFtaWx5X25hbWUiOiJKb3NlcGgiLCJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20ifQ.yre6-Qz0HSEDO4o6W26vwO9hZdl0V4-JpJF9wTzXfLjBqmC44MZLqmkex__sAYgSUcbZoOvpKrVb0BCoaHdCbvt27oxA-EVa-ugXTphyy7Oes0VmHBljzg-ZoH-hMBVbUQyA9ZUHlsFX_vEueQI1mFMBrb1MPR77sCz-ZuIaKRamKZFIaAb5X3fpIl7uLL9Y0Lwfx0_wKPN3kQ6TyP3vNkF8f4y0tHf0deBzwBuNHW29D9SMfxK9qGk0jQWxz3SA312TlMaAV0JVC06dAG8RfKs0AgWS9QREjvTrT2SKiRqa51YqBIZMwPaaehe3I7NI0xspHGlBlQf4rfEzCi_1qw</pre><p>id_token</p><pre>eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqanoyd0ZEVXhzUGdZYWowcV9FbzUtdEgxWlAzMldwMldNdDltY3RCal9RIn0.eyJleHAiOjE2ODU5ODQ0NjUsImlhdCI6MTY4NTk4NDE2NSwiYXV0aF90aW1lIjoxNjg1OTg0MTY1LCJqdGkiOiIxNDg5MDZlMi02NDA4LTQwNTAtODI5Yi1jYjQ5M2I1OWI1OGUiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL2x5ZHRlY2giLCJhdWQiOiJseWR0ZWNoLWNvbmZpZGVudGlhbC1jbGllbnQiLCJzdWIiOiJiZGI5ZjllZi05YmU3LTQzNzYtOTk2NC1jNDBjNDM5NGRmNDciLCJ0eXAiOiJJRCIsImF6cCI6Imx5ZHRlY2gtY29uZmlkZW50aWFsLWNsaWVudCIsIm5vbmNlIjoiNG15cGRyYng2elFFRjdWX2JrZWFoaFdJenZXX2hNSHV0dWZUUzgwM0Y2TSIsInNlc3Npb25fc3RhdGUiOiJmNmZhOGE5OS0yNDFmLTRkNmEtOGNiZS1iODM4ZjZmNTA1YzciLCJhdF9oYXNoIjoia0FhUDExdWRyelN3bmdON1hlREE0dyIsImFjciI6IjEiLCJzaWQiOiJmNmZhOGE5OS0yNDFmLTRkNmEtOGNiZS1iODM4ZjZmNTA1YzciLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwibmFtZSI6IkpvaG4gSm9zZXBoIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidXNlckBleGFtcGxlLmNvbSIsImdpdmVuX25hbWUiOiJKb2huIiwiZmFtaWx5X25hbWUiOiJKb3NlcGgiLCJlbWFpbCI6InVzZXJAZXhhbXBsZS5jb20ifQ.0gimss-xxTOzGnmTFMx-DvX3JtyJAFvAwoevXI8KNZ8tXW7_r1Giw2nHPEHghLN4-b70JP2DQSD5q3NnjUqz5CcHyTy60FUhB-Z4S_tXcouMbQ8zENYRxLgwWExb2qYWgyviJB2FxNO1Gn1aJw_bAuEDF4DVAeaNn9j597fDLe1z2tgkQQdMqMwYrIqSLGj_X3oLVjY7zZtXMgHwlDTu2dmcwSsTpUvywT5adpWGd0Jrkx4X5Viy0nhLNs9_7qCiYpNh4x_p1LX4q3PYdsMZTPGCjJHgjoV2W49LOj7WPBoxusFPrpiQfDwLMh8W513hh4DnWto0zJROZRvV24paYA</pre><p>refresh_token</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiYWI2ZTA3NS00NzZhLTRlZTktOWZkMC1mZjJiM2MyM2FkNzMifQ.eyJleHAiOjE2ODU5ODU5NjUsImlhdCI6MTY4NTk4NDE2NSwianRpIjoiOTY4NzdkMmMtMGI1Zi00NTA3LThlOTUtMDQyY2M4ODU4NGI4IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9seWR0ZWNoIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9seWR0ZWNoIiwic3ViIjoiYmRiOWY5ZWYtOWJlNy00Mzc2LTk5NjQtYzQwYzQzOTRkZjQ3IiwidHlwIjoiUmVmcmVzaCIsImF6cCI6Imx5ZHRlY2gtY29uZmlkZW50aWFsLWNsaWVudCIsIm5vbmNlIjoiNG15cGRyYng2elFFRjdWX2JrZWFoaFdJenZXX2hNSHV0dWZUUzgwM0Y2TSIsInNlc3Npb25fc3RhdGUiOiJmNmZhOGE5OS0yNDFmLTRkNmEtOGNiZS1iODM4ZjZmNTA1YzciLCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIiwic2lkIjoiZjZmYThhOTktMjQxZi00ZDZhLThjYmUtYjgzOGY2ZjUwNWM3In0.e-rF7pKug9iASUgqfopo07hmCau4JB8tMF-qz_SoKns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*m-CxKj7yMUdW_qpzVZ9t2A.png" /><figcaption><strong>Authenticated request to application</strong></figcaption></figure><p><strong>Request</strong></p><p>The browser can now follow the final redirect (from step 4) to request the page that the user originally requested. The Session ID cookie is sent across which allows the access_token to be looked up in the HTTP session and verified</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuWq-BQczrgvcoSsY1rJfQ.png" /></figure><p><strong>Response</strong></p><p>The /users HTML is now returned successfully so that the Browser can show it to the user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ZPnVF7L31eCyvMJJ92DxPw.png" /></figure><p>Note there are additional calls that were omitted here for brevity such as the call to the Authorisation Server to get the public key sets that it can use to sign tokens, and the calls to the OIDC endpoint /userInfo which is made from the Web application to the Authorisation Server.</p><h3>Summary</h3><p>This article builds upon previous articles in this series to show how a ‘confidential’ client can be used. It created a Spring Boot app in the form of a traditional web application that creates the HTML pages on the server and returns them to the browser to display. It showed how the use of HTTP sessions can be used to allow the server side application itself to be the OAuth client.</p><p>We built upon the theory from <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>, and showed this application working with the Keycloak Authorisation Server from <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a>. We followed this version of the Authorisation Code Grant flow step by step to illustrate the differences with how a public OAuth client behaves (<a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a>).</p><p>All the code is available in the following Github repository:</p><ul><li><a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client">https://github.com/lydtechconsulting/oauth-simple-confidential-client</a></li></ul><p>As an extension to this series, <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part4.html">Part 4</a> looks at replacing the Keycloak Authorisation Server with a custom Authorisation Server created using the Spring Authorisation Server project that was mentioned in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> when providing the history on OAuth support in Spring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f747ba98e9b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorisation using OIDC and OAuth 2. Part 2]]></title>
            <link>https://medium.com/@jamespowell99/authentication-and-authorisation-using-oidc-and-oauth-2-part-2-3940dd07a4f0?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/3940dd07a4f0</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 08:33:48 GMT</pubDate>
            <atom:updated>2023-06-27T08:33:48.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJWlDXIuBFCi87qywgwDBw.jpeg" /></figure><h3>Part 2: A public client — REST API and SPA app</h3><h3>Introduction</h3><p>This is the second article in this series. <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a> was a primer to the world of Authentication and Authorisation and introduced the important concepts that need to be understood before exploring in more detail. This article puts these concepts into action and shows how you can apply these to achieve Authentication and Authorisation in a sample application.</p><p>The article concentrates on a ‘public’ OAuth client. This is where the client itself has no way of reliably storing OAuth related secrets such as the client_secret field. Think of a Single Page Application (SPA) written in React or similar — there is no secure way to store a sensitive field here as the Javascript / TypeScript code is always available to the user in the browser. The diagram below illustrates the parts of this architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*lg-Wf9WwNVBZAXTC.png" /></figure><p>This article will work through the following</p><ul><li>Choose an Authorisation Server</li><li>Configure the Authorisation Server with users, roles and an OAuth client</li><li>Create a Resource Server to expose a REST API for the client to consume</li><li>Create a Single Page Application (SPA) as the OAuth client</li><li>Show how all the moving parts are wired together to provide authentication and authorisation via OIDC / OAuth2</li></ul><p><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part3.html">Part 3</a> of this series looks at a ‘confidential’ OAuth client, in the form of a traditional server side web application.</p><h3>Choosing an Authorisation Server</h3><p>Previously, Spring offered support for all things OAuth, including support for creating Authorisation Servers and Resource Servers, via the <a href="https://spring.io/projects/spring-security-oauth">spring-security-oauth</a> library. This has now been deprecated, with OAuth support moving into the <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/index.html">Spring Security Library</a> itself. Note that Spring Security does not include support for creating custom Authorisation Servers due to the existence of a large number of specialised OAuth/OIDC compliant Authorisation Server products. Although, recently, Spring has introduced a new <a href="https://spring.io/projects/spring-authorization-server">Spring Authorisation Server project</a> to support the creation of custom Authorisation Servers again for the use cases that require that. This is explored in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part4.html">Part 4</a> of this series.</p><p>The Authorisation Server component plays a key role in the security of any architecture leveraging OIDC / OAuth. It will typically be responsible for storing user details and credentials, roles, groups and other information and be responsible for authenticating users. It is a crucial piece and it is imperative that this is done correctly. With this in mind, the industry has generally moved towards using specialist identity products such as <a href="https://auth0.com/">Auth0</a>, <a href="https://www.keycloak.org/">Keycloak</a>, <a href="https://aws.amazon.com/cognito/">AWS Cognito</a>, <a href="https://firebase.google.com/docs/auth">Firebase Authentication</a> as Authorisation Servers rather than using tools such as Spring to create custom implementations.</p><p>For this series, <a href="https://www.keycloak.org/">Keycloak</a> has been used for the Authorisation Server. The main reasons for this are:</p><ol><li>It is a well known, mature product</li><li>Has very good documentation and support community</li><li>Is very easy to run locally using Docker</li></ol><h3>Setting up Keycloak</h3><p>Note the steps below are for running an Authorisation Server locally in the interest of demonstrating the concepts in this series of articles. In order to run in production, consult the Keycloak documentation.</p><p><strong>Start Keycloak</strong></p><p>Use the following command to run Keycloak locally using Docker</p><pre>docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:21.1.1 start-dev</pre><p><strong>Create Realm</strong></p><p>The Keycloak instance will have a default realm of ‘master’. The first step is to create a realm. A realm is a space where you manage objects, including users, applications, roles, and groups. A user belongs to and logs into a specific realm.</p><p>Once logged in to the admin console at <a href="http://localhost:8080/admin">http://localhost:8080/admin</a> as the admin user (password: admin), you will see a drop down box in the top left corner to select a realm. The master realm will currently be selected. Drop the box down and click ‘Create Realm’. Choose a Realm name that is relevant to your situation. We’ll use ‘lydtech’ - our organisation name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NZzu5g9Yzf342QXD.png" /></figure><p>Once the new realm is selected there are many configuration options that can be changed. To help simplify this demo, navigate to ‘Realm Settings-&gt;Login-&gt;Email Settings’ and ensure ‘Email as username’ is enabled. Your settings should look as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*SpvwpCb7JdYdZMlY.png" /></figure><p><strong>Create Roles</strong></p><p>Now that we have a Realm, we need to create 2 roles. We will create an ‘admin’ and ‘user’ role in order to demonstrate authorisation in action.</p><p>Navigate to ‘Realm Roles’ and click ‘Create role’. Enter the name ‘admin’ and an optional description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RP70WhgXLTHOSE_9.png" /></figure><p>Click Save. Your new role will be created and will now be visible on screen.</p><p>Repeat this process to add a ‘user’ role.</p><p><strong>Create Users</strong></p><p>Next, let’s create 2 users with the relevant roles. Navigate to ‘Users’ and click ‘Create new user’. Enter the email ‘admin@example.com’, ensure ‘Email Verified’ is enabled (to avoid the user needing to verify their email) and choose an appropriate First / Last name as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7msde0NJ4fIX3JCc.png" /></figure><p>The user needs a password. We will set this in the admin console. With the new user selected, visit the ‘Credentials’ tab, click ‘Set Password’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wZ8nCqi7F340GMeu.png" /></figure><p>Choose a simple password, ensure ‘Temporary’ is disabled and click ‘Save’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yLam053HPMrMeHQv.png" /></figure><p>Finally, we need to map the user to the admin role we created previously. This can be done on the ‘Role Mapping’ tab when the user is selected. Choose to ‘Assign Role’ and select the ‘admin’ role. When complete, the admin role should be visible in the table as seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ogS9AvEiOyzJ2E5B.png" /></figure><p>Repeat this exercise to create another user ‘user@example.com’ , choosing the ‘user’ role this time during role mapping</p><p><strong>Create OAuth Client</strong></p><p>Now that we have our realm, users and roles created, it is time to create our OAuth client. A Keycloak client represents an OAuth client application and is able to request Keycloak to authenticate a user. Typically a separate client would be created for each application that will authenticate / authorise users in your realm. For this article we will create a ‘public’ type client with the name ‘lydtech-public-client’</p><p>To create a client, navigate to ‘Clients’ and click ‘Create Client’. You will have 3 pages to complete.</p><p>Under ‘General Settings’, Client Type needs to be ‘OpenID Connect’. Choose an appropriate clientID — ‘lydtech-public-client’ in this case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bl1e-r74ojgl6RBC.png" /></figure><p>Next under ‘Capability config’, ensure the following:</p><ol><li>‘Client authentication’ should be disabled. This is a ‘public’ client type, not ‘confidential’</li><li>For authentication flows, ensure only ‘Standard flow’ is selected — this is the ‘Authorisation Code’ flow that we focused on in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>. ‘Direct access grants’ will be enabled by default, but we do not want this; this is effectively a ‘Password’ grant type which is discouraged, and deprecated in OAuth 2.1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qr7aABfsH7sZDzet.png" /></figure><p>Finally, under ‘Login Settings’ we need to provide the same URL (http://localhost:3000) for both a ‘Valid redirect URI’ and a ‘Web Origin’. The former will allow our SPA to ask Keycloak to redirect back to it after a successful login while the latter will allow the SPA to make HTTP calls to Keycloak from a different origin (think CORS). We use the same value for both - our SPA client app will run locally on port 3000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fT-L2TeZIg7AEYM3.png" /></figure><p>As we’ve disabled the Direct Access Grant (Password Grant) there isn’t an easy way to generate a JWT token for this client as a test of what we just created. It is worth visiting the following URL at this stage to verify we’ve configured the basics correctly: <a href="http://localhost:8080/realms/lydtech/.well-known/openid-configuration">http://localhost:8080/realms/lydtech/.well-known/openid-configuration</a> — the JSON response will contain configuration information that can be used for discovery purposes.</p><h3>Creating a Spring Boot Resource Server</h3><p><strong>Create the project</strong></p><p>Now that we have a fully configured Authorisation Server, we can create our Resource Server. For this we will use Spring Boot to expose a simple REST API with 3 endpoints. We will use Spring Security to protect the 3 endpoints.</p><p>Visit <a href="https://start.spring.io/">start.spring.io</a> to create the template for the Resource Server. Use settings such as those in the image below but be sure to include the following dependencies:</p><ul><li>Spring Web — Needed to provide the REST API</li><li>Lombok — Helps to reduce boilerplate code</li><li>OAuth2 Resource Server — pulls in the required dependencies to configure the service as an OAuth Resource Server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bn4iAguCsg6xzaJ8.png" /></figure><p>Click Generate to download a zip file containing the project, unzip this project in a suitable directory and open it in your favourite IDE.</p><p><strong>Create REST endpoints</strong></p><p>First let’s create our single Controller class which will expose 3 endpoints as follows:</p><ul><li>GET /v1/api/public — any user will be able to call this, even if they are unauthenticated (anonymous)</li><li>GET /v1/api/user — any admin or user role will be able to call this</li><li>GET /v1/api/admin — only admin roles will be able to call this</li></ul><p>Complete <a href="https://github.com/lydtechconsulting/oauth-simple-resource-server/blob/main/src/main/java/dev/lydtech/security/simpleresourceserver/controller/MyController.java">controllers/MyController.java</a> file available in the Github repository</p><pre>package dev.lydtech.security.simpleresourceserver.controller;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.CrossOrigin;<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>import java.security.Principal;<br>import java.util.Optional;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>@Slf4j<br>@CrossOrigin(origins = &quot;http://localhost:3000&quot;)<br>public class MyController {<br><br>    @GetMapping(&quot;/public&quot;)<br>    public ResponseEntity&lt;String&gt; publicEndpoint(Principal principal) {<br>        log.info(&quot;/public called&quot;);<br>        String message = getPrincipalName(principal);<br>        return ResponseEntity.ok(&quot;Hello from Public endpoint - &quot; + message);<br>    }<br><br>    @GetMapping(&quot;/user&quot;)<br>    public ResponseEntity&lt;String&gt; userEndpoint(Principal principal) {<br>        log.info(&quot;/user called&quot;);<br>        String message = getPrincipalName(principal);<br>        return ResponseEntity.ok(&quot;Hello from User endpoint - &quot; + message);<br>    }<br><br>    @GetMapping(&quot;/admin&quot;)<br>    public ResponseEntity&lt;String&gt; adminEndpoint(Principal principal) {<br>        log.info(&quot;/admin called&quot;);<br>        String message = getPrincipalName(principal);<br>        return ResponseEntity.ok(&quot;Hello from Admin endpoint - &quot; + message);<br>    }<br><br>    private static String getPrincipalName(Principal principal) {<br>        return Optional.ofNullable(principal)<br>                .map(Principal::getName)<br>                .orElse(&quot;Not available&quot;);<br>    }<br>}</pre><p>There isn’t a great deal to explain here for those familiar with Spring, but a few key points:</p><ol><li>The @RestController and @RequestMapping(“/api/v1”) annotations are used to expose a REST API.</li><li>@GetMapping is used for each of the 3 endpoints. The 3 endpoints have a single method parameter of type java.security.Principal — this will contain details of the authenticated user.</li><li>@CrossOrigin is required to allow the SPA client to call the endpoint from a different host/port origin.</li><li>Each endpoint will return a simple string containing a message and the authenticated username (if present).</li></ol><p><strong>Extract role details from Keycloak JWT</strong></p><p>The following class is needed to customise some of the information that is extracted from the JWT:</p><p>Complete <a href="https://github.com/lydtechconsulting/oauth-simple-resource-server/blob/main/src/main/java/dev/lydtech/security/simpleresourceserver/JwtAuthConverter.java">JwtAuthConverter.java</a> file available in the Github repository</p><pre>package dev.lydtech.security.simpleresourceserver;<br><br>import org.springframework.core.convert.converter.Converter;<br>import org.springframework.security.authentication.AbstractAuthenticationToken;<br>import org.springframework.security.core.GrantedAuthority;<br>import org.springframework.security.core.authority.SimpleGrantedAuthority;<br>import org.springframework.security.oauth2.jwt.Jwt;<br>import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;<br>import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;<br>import org.springframework.stereotype.Component;<br>import java.util.Collection;<br>import java.util.Map;<br>import java.util.Set;<br>import java.util.stream.Collectors;<br>import java.util.stream.Stream;<br><br>@Component<br>public class JwtAuthConverter implements Converter&lt;Jwt, AbstractAuthenticationToken&gt; {<br>    private final JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();<br>    <br>    @Override<br>    public AbstractAuthenticationToken convert(Jwt jwt) {<br>        Collection&lt;GrantedAuthority&gt; authorities = Stream.concat(<br>                jwtGrantedAuthoritiesConverter.convert(jwt).stream(),<br>                extractRealmRoles(jwt).stream()).collect(Collectors.toSet());<br>        return new JwtAuthenticationToken(jwt, authorities, jwt.getClaim(&quot;preferred_username&quot;));<br>    }<br>    <br>    private Collection&lt;? extends GrantedAuthority&gt; extractRealmRoles(Jwt jwt) {<br>        Map&lt;String, Object&gt; realmAccess = jwt.getClaim(&quot;realm_access&quot;);<br>        Collection&lt;String&gt; realmRoles;<br>        if (realmAccess == null<br>                || (realmRoles = (Collection&lt;String&gt;) realmAccess.get(&quot;roles&quot;)) == null) {<br>            return Set.of();<br>        }<br>        return realmRoles.stream()<br>                .map(role -&gt; new SimpleGrantedAuthority(&quot;ROLE_&quot; + role))<br>                .collect(Collectors.toSet());<br>    }<br>}</pre><p>This code perform 2 functions:</p><ol><li>Use the preferred_username claim from the JWT for the principal name. Without this the principal name would be the ‘sub’ claim which is a UUID</li><li>Extract the Keycloak ‘Realm Roles’ from the JWT token and map to a collection of GrantedAuthorities stored against the principal. The last section of this article shows some examples of JWT access_tokens issued by Keycloak and calls out where role information is contained.</li></ol><p><strong>Configure Security</strong></p><p>We need to include a Spring configuration class in order to configure the Security Filter Chain that will secure the 3 endpoints. Some points to note:</p><ol><li>.requestMatchers is used to allow the relevant roles for the correct URL patterns.</li><li>The JWTAuthConverter bean we created above is registered with Spring Security</li><li>HTTP sessions are disabled (this is a stateless REST API that does not require sessions)</li><li>A CORS filter is added to allow the API to be called from a different origin (the SPA app)</li></ol><p>Complete <a href="https://github.com/lydtechconsulting/oauth-simple-resource-server/blob/main/src/main/java/dev/lydtech/security/simpleresourceserver/WebSecurityConfig.java">WebSecurityConfig.java</a> file available in the Github repository</p><pre>package dev.lydtech.security.simpleresourceserver;<br><br>import lombok.RequiredArgsConstructor;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.HttpMethod;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.web.SecurityFilterChain;<br><br>@RequiredArgsConstructor<br>@Configuration<br>@EnableWebSecurity<br>public class WebSecurityConfig {<br>    <br>    private final JwtAuthConverter jwtAuthConverter;<br>    <br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>                .authorizeHttpRequests(authorize -&gt; authorize<br>                        //Don&#39;t have to be authenticated to call anything under public<br>                        .requestMatchers(HttpMethod.GET, &quot;/api/v1/public&quot;, &quot;/api/v1/public/**&quot;).permitAll()<br>                        //Only admins can access anything under admin<br>                        .requestMatchers(HttpMethod.GET, &quot;/api/v1/admin&quot;, &quot;/api/v1/admin/**&quot;).hasRole(&quot;admin&quot;)<br>                        //Users and admins can access user endpoints<br>                        .requestMatchers(HttpMethod.GET, &quot;/api/v1/user&quot;).hasAnyRole(&quot;admin&quot;, &quot;user&quot;)<br>                        .anyRequest().authenticated()<br>                ).oauth2ResourceServer(oauth2 -&gt; oauth2<br>                        .jwt(jwt -&gt; jwt<br>                                .jwtAuthenticationConverter(jwtAuthConverter)<br>                        )<br>                ).sessionManagement(sm -&gt; sm<br>                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)<br>                ).cors(withDefaults());<br>        return http.build();<br>    }<br>}</pre><p><strong>Configure Spring Security</strong></p><p>The final step to complete the simple Resource Server is to replace the contents of src/main/resources/application.properties with <a href="https://github.com/lydtechconsulting/oauth-simple-confidential-client/blob/main/src/main/resources/application.properties">application.properties</a> as per the extract below</p><pre>server.port=8081<br>spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/lydtech<br>spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${spring.security.oauth2.resourceserver.jwt.issuer-uri}/protocol/openid-connect/certs<br>logging.level.org.springframework.security=trace</pre><p>Some points to note:</p><ol><li>The server port is set to 8081, the default of 8080 will clash with our Keycloak instance.</li><li>The spring.security.oauth2.resourceserver.jwt values are how we tell Spring Security how to validate the JWTs for this service. We are pointing it at the Keycloak realm we created and allowing it to get the set of public keys that Keycloak can use to sign the JWTs it creates.</li><li>The org.spring.security log level is set to trace which can be really helpful in showing exactly what is happening in the security filters.</li></ol><p><strong>Testing the resource server</strong></p><p>As a quick test of our resource server, start it up either by using the command ./mvnw spring-boot:run or running the SimpleResourceServerApplication in your IDE.</p><p>Once the service has started, prove that it is running and that the public endpoint does not require an access token by hitting with curl:</p><pre>curl -v http://localhost:8081/api/v1/public</pre><p>Important points in the output:</p><ul><li>&lt; HTTP/1.1 200 - a HTTP 200 response</li><li>Hello from Public endpoint - Not available - shows that the response was returned but there is no user associated</li></ul><p>Finally lets prove that the other endpoints do require an auth token</p><pre>curl -v http://localhost:8081/api/v1/user</pre><p>Note the &lt; HTTP/1.1 401 response which shows that it requires an authenticated user to call it.</p><p>We’ll see the secured endpoints in action shortly</p><h3>Creating an SPA client</h3><p>The final piece in our Auth Jigsaw is the client itself. For this we’ll produce a very simple React Single Page Application (SPA) that can perform the Authorisation Grant flow dance and call our Resource Server with the generated Access Token.</p><p><strong>Create a React app</strong></p><p>Use create-react-app to create the project template</p><pre>npx create-react-app simple-client-example --template typescript</pre><p><strong>Install libraries</strong></p><p>From the newly created project root directory, run the following to install some required libraries</p><pre>npm install axios react-oauth2-code-pkce</pre><ul><li>react-oauth2-code-pkce - a handy library that supplies the code required to perform the OAuth Authorisation Code flow dance as a client</li><li>axios - required to make HTTP calls to the REST API we created earlier</li></ul><p><strong>Code the app</strong></p><p>Remove src/App.tsx, src/App.test.tsx and overwrite src/index.tsx with the following. Complete <a href="https://github.com/lydtechconsulting/oauth-simple-client/blob/main/src/index.tsx">src/index.tsx</a> file available in the Github repository but included here in full with descriptions for each section.</p><p>Import the required libraries</p><pre>import React, {useContext, useState} from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import axios from &#39;axios&#39;;<br>import {AuthContext, AuthProvider, IAuthContext, TAuthConfig, TRefreshTokenExpiredEvent} from &quot;react-oauth2-code-pkce&quot;</pre><p>Configure the Auth config which includes</p><ul><li>The clientId to the Keycloak client we created earlier.</li><li>The 2 OAuth endpoints that we introduced in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>: /auth and /token</li><li>The logout URL of the Keycloak server and realm</li><li>The redirectUri to return to following successful authentication</li></ul><pre>const authConfig: TAuthConfig = {<br>    clientId: &#39;lydtech-public-client&#39;,<br>    authorizationEndpoint: &#39;http://localhost:8080/realms/lydtech/protocol/openid-connect/auth&#39;,<br>    tokenEndpoint: &#39;http://localhost:8080/realms/lydtech/protocol/openid-connect/token&#39;,<br>    logoutEndpoint: &#39;http://localhost:8080/realms/lydtech/protocol/openid-connect/logout&#39;,<br>    redirectUri: &#39;http://localhost:3000&#39;,<br>    scope: &#39;openid&#39;,<br>    onRefreshTokenExpire: (event: TRefreshTokenExpiredEvent) =&gt; window.confirm(&#39;Session expired. Refresh page to continue using the site?&#39;) &amp;&amp; event.login(),<br>}</pre><p>A function to make calls to the REST Endpoints we configured earlier, using Axios</p><pre>const callEndpoint = async (url: string, token: string) =&gt; {<br>    const currentdate = new Date();<br>    const datetime = currentdate.getDate() + &quot;/&quot;<br>        + (currentdate.getMonth()+1)  + &quot;/&quot;<br>        + currentdate.getFullYear() + &quot; @ &quot;<br>        + currentdate.getHours() + &quot;:&quot;<br>        + currentdate.getMinutes() + &quot;:&quot;<br>        + currentdate.getSeconds();<br>    <br>    var message;<br>    try {<br>        const response = await axios.get(url, {headers: {&#39;Authorization&#39;: `Bearer ${token}`}});<br>        message = response.data;<br>    } catch (error) {<br>        if (axios.isAxiosError(error)) {<br>            console.log(`error calling endpoint ${url}: ${error}`)<br>            if (error.response) {<br>                message = `Error: ${error.response.status}`<br>            } else {<br>                message = error;<br>            }<br>        } else {<br>            throw error;<br>        }<br>    }<br>    return `called at ${datetime} - ${message}`;<br>}</pre><p>Now we declare a React component that</p><ul><li>Prints the full JWT access token to the screen</li><li>Prints the decoded JWT access token to the screen</li><li>Has a button to call each of the Resource Server endpoints</li><li>Has a logout button</li></ul><pre>const UserInfo = (): JSX.Element =&gt; {<br>    const {token, tokenData, logOut} = useContext(AuthContext)<br>    const [publicResponse, setPublicResponse] = useState(&quot;Not called yet&quot;);<br>    const [adminResponse, setAdminResponse] = useState(&quot;Not called yet&quot;);<br>    const [userResponse, setUserResponse] = useState(&quot;Not called yet&quot;);<br><br>    const callPublic = async () =&gt; {<br>        const message = await callEndpoint(&#39;http://localhost:8081/api/v1/public&#39;, token);<br>        setPublicResponse(message);<br>    }<br><br>    const callAdmin = async () =&gt; {<br>        const message = await callEndpoint(&#39;http://localhost:8081/api/v1/admin&#39;, token);<br>        setAdminResponse(message);<br>    }<br><br>    const callUser = async () =&gt; {<br>        const message = await callEndpoint(&#39;http://localhost:8081/api/v1/user&#39;, token);<br>        setUserResponse(message);<br>    }<br><br>    return &lt;&gt;<br>        &lt;h4&gt;Your complete Access Token&lt;/h4&gt;<br>        &lt;pre&gt;{token}&lt;/pre&gt;<br>        &lt;h4&gt;Your decoded JWT payload &lt;/h4&gt;<br>        &lt;pre&gt;{JSON.stringify(tokenData, null, 2)}&lt;/pre&gt;<br>        &lt;br/&gt;<br>        &lt;button onClick={callPublic}&gt;Call /api/v1/public&lt;/button&gt;<br>        &lt;p&gt;{publicResponse}&lt;/p&gt;<br>        &lt;br/&gt;<br>        &lt;button onClick={callUser}&gt;Call /api/v1/user&lt;/button&gt;<br>        &lt;p&gt;{userResponse}&lt;/p&gt;<br>        &lt;br/&gt;<br>        &lt;button onClick={callAdmin}&gt;Call /api/v1/admin&lt;/button&gt;<br>        &lt;p&gt;{adminResponse}&lt;/p&gt;<br>        &lt;br/&gt;<br>        &lt;button onClick={() =&gt; logOut()}&gt;Log out&lt;/button&gt;<br>    &lt;/&gt;<br>}</pre><p>The React boilerplate code to bootstrap the application. Note that the UserInfo component is wrapped inside an AuthProvider, which is supplied by the react-oauth2-code-pkce library - this is what will take care of redirecting the user to Keycloak for authentication and then converting the authorisation code to an access token.</p><pre>const root = ReactDOM.createRoot(<br>    document.getElementById(&#39;root&#39;) as HTMLElement<br>);<br><br>root.render(<br>    &lt;AuthProvider authConfig={authConfig}&gt;<br>        &lt;UserInfo/&gt;<br>    &lt;/AuthProvider&gt;<br>);</pre><p><strong>Test the client runs</strong></p><p>Run the client app using npm start and make sure it starts successfully and that there are no errors.</p><h3>Testing the end result</h3><p><strong>Start the applications</strong></p><p>Ensure the following are started:</p><ul><li>Keycloak in Docker</li><li>The Resource Server REST API via Maven or in your IDE</li><li>The client application using npm</li></ul><p><strong>Test an Admin user</strong></p><p>Visit <a href="http://localhost:3000/">http://localhost:3000</a> in a browser. The application should immediately redirect you to the Keycloak login page as per the screenshot below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nm71jFF7h_yeC0kx.png" /></figure><p>Sign in using the admin@example.com user that we created earlier. Upon successful login you should be shown the main app page similar to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vEgZTszZzm3-78yd.png" /></figure><p>Observe the following:</p><ol><li>The complete access token at the top</li><li>The decoded JWT payload showing all the claims</li><li>Note the ‘admin’ entry in realm_access.roles — this shows that the user has the admin role that we created earlier</li><li>The user’s username (email address in this case) is available in the preferred_username claim</li></ol><p>Scrolling down will show the 3 buttons to call each of the API endpoints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*kYg-ZAF_-8yU9E1d.png" /></figure><p>The ‘Not called yet’ placeholder shows the endpoints have not been called yet. Click each of the 3 buttons and see that each of the successful responses is shown on screen, also note that each response contains the user’s username — showing that the Principal was available in the Spring Boot app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qulx4ciPr0qom2-k.png" /></figure><p><strong>Test a non Admin user</strong></p><p>Use the ‘Log out’ button to log out as the admin user. You should be redirected to the Keycloak login screen again. This time log in as the user@example.com user we created.</p><p>Once logged in you will see from the JWT contents that this user only has the ‘user’ role, not the ‘admin’ role</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*-2OnPUEb-zlHXpDU.png" /></figure><p>Now click each of the 3 buttons to attempt to call the 3 endpoints. This time you should see something like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GcnT0PEevOeFzB5-.png" /></figure><p>Notice that /public and /user were successful but /admin resulted in a 403 proving that this user is not in the ‘admin’ role and therefore is not allowed to access the endpoint.</p><h3>Following the Authorisation Code flow</h3><p>Now that we’ve seen it work, let’s look at each step in the flow to be able to link it to the theory in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>. Using Chrome DevTools we can capture each of the interesting HTTP requests that make up the flow. The sequence diagram below shows each call, labelled with a number, which is expanded on below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wMB-Yp1FJHLCwXEj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*QrMnA2aix8ezm7OGUQmcKA.png" /><figcaption><strong>Authorisation Request</strong></figcaption></figure><p><strong>Request</strong></p><p>Upon loading the application into the browser (from <a href="http://localhost:3000),">http://localhost:3000),</a> the react-oauth2-code-pkce realises that the user is not logged in and therefore has no access_token so redirects to the Keycloak login screen. Note, as you will see from step 1 in the sequence diagram above, this isn&#39;t via a HTTP redirect but rather by asking the browser to take the user to the Keycloak login screen via Javascript code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuzP2x0erO86X4gvMr-5Kg.png" /></figure><p><strong>Response</strong></p><p>The response from Keycloak is a HTML page containing a login page with a username &amp; password field and a ‘Log in’ button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*nQphW4tEEX6-Zqz2JMbghw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*0rLqJ-4xI_VPUlvdpGrhvA.png" /><figcaption><strong>User authenticates with Keycloak</strong></figcaption></figure><p><strong>Request</strong></p><p>The user types in their username &amp; password then clicks Log In</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_E6T2LEtph5bLjY3w8qiQ.png" /></figure><p><strong>Response</strong></p><p>Upon a successful log in, Keycloak redirects back to our SPA app as requested</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUZpcjc83H05TjN4UUPBXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*jIK-_n3ztHlQiZ9QoF7G0w.png" /><figcaption><strong>Token request</strong></figcaption></figure><p><strong>Request</strong></p><p>The SPA application can then exchange the authorisation code for an access_token with Keycloak</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28kS-DTKG3bMGaflmOp3OA.png" /></figure><p><strong>Response</strong></p><p>This includes an access token, refresh token and (because we requested the oidc scope) an ID token (all in the form of JWT tokens). Note the access tokens have been truncated for readability. They are included in full below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI5y4SI2u2bkk2yyYuWU6w.png" /></figure><p>Note you could copy any of these tokens into <a href="https://jwt.io/">jwt.io</a> to view the full contents.</p><p>access_token</p><pre>eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqanoyd0ZEVXhzUGdZYWowcV9FbzUtdEgxWlAzMldwMldNdDltY3RCal9RIn0.eyJleHAiOjE2ODQ4MzEyNjUsImlhdCI6MTY4NDgzMDk2NSwiYXV0aF90aW1lIjoxNjg0ODMwOTY1LCJqdGkiOiI0OTEyZGI5YS01NDIxLTRiMDQtOWIzNC1hYjVhMTg2MDI4ZmIiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL2x5ZHRlY2giLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiOWRlZGQzMmYtYjIxMi00MWVjLTkyOTEtZDdhY2JiM2YxNDdmIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoibHlkdGVjaC1wdWJsaWMtY2xpZW50Iiwic2Vzc2lvbl9zdGF0ZSI6ImEzZTBiMWZlLTNlZGItNGZjNC05OTQyLTEyMDgzMzM0Mzg5ZCIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiaHR0cDovL2xvY2FsaG9zdDozMDAwIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLWx5ZHRlY2giLCJvZmZsaW5lX2FjY2VzcyIsImFkbWluIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIiwic2lkIjoiYTNlMGIxZmUtM2VkYi00ZmM0LTk5NDItMTIwODMzMzQzODlkIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsIm5hbWUiOiJXaWxsaWFtIEJvc3MiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJhZG1pbkBleGFtcGxlLmNvbSIsImdpdmVuX25hbWUiOiJXaWxsaWFtIiwiZmFtaWx5X25hbWUiOiJCb3NzIiwiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSJ9.rXEp7F6JGBQ8_xCLs0A39KUVuO3AyYKslArIZQs2BFCKPOEvi9xW4SQEMToYPnX-qw0nEssgkBgvbaJQcCicJ9TA8D_v-TiLs_KqcnYgiIvt7yQtLBp57Fad0L_foiaCrDj8Nq9WqqjujsGbrXlDXG6_2EoqUCmtf1nKLkCYWY3ySsLAb2kVwkp1diXQFiIs8oTIKtnAPgZ-fMM5HoQ2zZ1fbFgY3vGWF_xwe5UpVUYsAEi2BIqmUPRnCnfnzskbnZfd7LQ5eV_Y0-54F8CuszCo9vi1R5tMb3mJuHbVeyEVRdlOiq6RParoZsDPGXY23Aq4ivbuxQvg0PmP9WxGfA</pre><p>id_token</p><pre>eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqanoyd0ZEVXhzUGdZYWowcV9FbzUtdEgxWlAzMldwMldNdDltY3RCal9RIn0.eyJleHAiOjE2ODQ4MzEyNjUsImlhdCI6MTY4NDgzMDk2NSwiYXV0aF90aW1lIjoxNjg0ODMwOTY1LCJqdGkiOiI0ZDI4YzdmNy03YzhkLTQ2MTItOGY0ZS00NzFmZTliNzc1MTciLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL2x5ZHRlY2giLCJhdWQiOiJseWR0ZWNoLXB1YmxpYy1jbGllbnQiLCJzdWIiOiI5ZGVkZDMyZi1iMjEyLTQxZWMtOTI5MS1kN2FjYmIzZjE0N2YiLCJ0eXAiOiJJRCIsImF6cCI6Imx5ZHRlY2gtcHVibGljLWNsaWVudCIsInNlc3Npb25fc3RhdGUiOiJhM2UwYjFmZS0zZWRiLTRmYzQtOTk0Mi0xMjA4MzMzNDM4OWQiLCJhdF9oYXNoIjoid2RfMFpYdVdCRll3T1otdzBDV3FtUSIsImFjciI6IjEiLCJzaWQiOiJhM2UwYjFmZS0zZWRiLTRmYzQtOTk0Mi0xMjA4MzMzNDM4OWQiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwibmFtZSI6IldpbGxpYW0gQm9zcyIsInByZWZlcnJlZF91c2VybmFtZSI6ImFkbWluQGV4YW1wbGUuY29tIiwiZ2l2ZW5fbmFtZSI6IldpbGxpYW0iLCJmYW1pbHlfbmFtZSI6IkJvc3MiLCJlbWFpbCI6ImFkbWluQGV4YW1wbGUuY29tIn0.I6fFM5cSJo5zi-kLZDX8jVsDsInHdyRK6LOTw4MN9liVYfi2-7VDAqtslON9ruqB0yoVUWe3hsFHUDOeEtRop5p2YM71y3d3kCGw9zuusBjDtb4LBsaWjnizf5FPCckKExbprpQ_l24fAg3Gj8UiwA2soSSX7HvqcHEGZWL2cqHwGu-hlSuNJrp2H3oKuV4fz_JaBMt4Xp5rO-H-citC-0Za3KArm_hzCIMOcaTL024KAwwlLWIHQRB7QYBbjw-ZgnVjF1KuEpj19myqEV_zIxWDSGzh3mjfzqlt1WyEjRSSnX9q7kpodeCiwoL-Pr1SIjWI3pUb55s_rtQU3P9bCQ</pre><p>refresh_token</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiYWI2ZTA3NS00NzZhLTRlZTktOWZkMC1mZjJiM2MyM2FkNzMifQ.eyJleHAiOjE2ODQ4MzI3NjUsImlhdCI6MTY4NDgzMDk2NSwianRpIjoiYjIyMmFkMTctNDI1Ny00N2MwLWIwNDctYWYxZWVkYmJjYWEwIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9seWR0ZWNoIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9seWR0ZWNoIiwic3ViIjoiOWRlZGQzMmYtYjIxMi00MWVjLTkyOTEtZDdhY2JiM2YxNDdmIiwidHlwIjoiUmVmcmVzaCIsImF6cCI6Imx5ZHRlY2gtcHVibGljLWNsaWVudCIsInNlc3Npb25fc3RhdGUiOiJhM2UwYjFmZS0zZWRiLTRmYzQtOTk0Mi0xMjA4MzMzNDM4OWQiLCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIiwic2lkIjoiYTNlMGIxZmUtM2VkYi00ZmM0LTk5NDItMTIwODMzMzQzODlkIn0.rpS8agLUWBbHfI89MZ9_1Y_CHREIemo_YwgOtAEQhsE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*qRa7uNwgdHBbhVfdworutA.png" /><figcaption><strong>Resource Server calls</strong></figcaption></figure><p><strong>Request</strong></p><p>Any call to the Resource Server will contain the access token returned above in the Authorization HTTP header as a Bearer token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-TCHQRyc0ZZ4-eLVoXOXA.png" /></figure><p><strong>Response</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6uKsL5hkclud8ZJH_6NUQ.png" /></figure><h3>Summary</h3><p>This article builds upon the theory introduced in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a> of this series. It created all the components of an architecture that leveraged OIDC &amp; OAuth to provide authentication and authorisation via a ‘public’ client. We created and configured:</p><ul><li>An Authorisation Server using Keycloak</li><li>A Resource Server in the shape of a REST API provided by Spring Boot</li><li>A client application in the form of a React SPA app</li><li>We showed these 3 things working together and followed the Authorisation Code Grant flow step by step, having looked at the theory for this in <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part1.html">Part 1</a>.</li></ul><p>All the code is available in the following Github repositories:</p><ul><li><a href="https://github.com/lydtechconsulting/oauth-simple-client">https://github.com/lydtechconsulting/oauth-simple-client</a></li><li><a href="https://github.com/lydtechconsulting/oauth-simple-resource-server">https://github.com/lydtechconsulting/oauth-simple-resource-server</a></li></ul><p><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part3.html">Part 3</a> of this series shows how the Authorisation Code Grant flow can be used with a confidential client, using a traditional server side web application.</p><p><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part4.html">Part 4</a> Looks at replacing Keycloak for these projects with a custom Authorisation Server using Spring Authorisation Server project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3940dd07a4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorisation using OIDC and OAuth 2. Part 1]]></title>
            <link>https://medium.com/lydtech-consulting/authentication-and-authorisation-using-oidc-and-oauth-2-part-1-9403ac2a3ed6?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/9403ac2a3ed6</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[oidc]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 16:12:18 GMT</pubDate>
            <atom:updated>2023-06-27T08:03:40.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJWlDXIuBFCi87qywgwDBw.jpeg" /></figure><h3>Introduction</h3><p>Authentication, Authorisation, OAuth, OAuth 2, OIDC… we often find that engineers and development teams experience a lack of understanding and even fear around these concepts. Comments like ‘I just can’t get my head around auth’ and ‘auth just fills me with dread’ are all too common. Engineers often become overwhelmed at the amount of conflicting information available on these subjects and the rate of change that has occurred. With Cyber Security attacks on the rise, it is imperative that technical staff have a good understanding of some of these mechanisms and which are most appropriate to their applications and organisations.</p><p>This series aims to break down modern authentication / authorisation practices and how they work, with some concrete examples to help bolster understanding. This article will introduce some of the important concepts around authentication and authorisation in modern applications and how they work in practice. Subsequent articles in this series will implement some of these mechanisms in real world scenarios.</p><h3>Key terms and concepts</h3><p>First, let’s introduce some of the important terms and concepts before diving into the details.</p><p><strong>Authentication vs Authorisation</strong></p><p>Authentication is about proving who a user is while authorisation is about deciding what that user is allowed to do.</p><p><strong>OAuth</strong></p><p><a href="https://oauth.net/2/">OAuth</a> (Open Authorisation) is the industry standard protocol for authorisation. As you will see in the remainder of this article, it allows a website or application to access resources hosted by other applications on behalf of a user. It does this by providing a number of ‘flows’ depending on the types of applications involved and leverages Access Tokens in order to control this access. <strong>OAuth was designed to address authorisation, not authentication</strong></p><p><strong>OAuth vs Oauth2 vs Oauth 2.1</strong></p><p>OAuth 1 has been largely superseded by Oauth 2. A detailed comparison of OAuth 2 vs OAuth 1 is beyond the scope of this article. The main point here is, when you see OAuth, think OAuth 2 (which is what the remainder of this series concentrates on)</p><p><a href="https://oauth.net/2.1/">OAuth 2.1</a> builds on OAuth 2.0. Default security practices are improved and some areas simplified. There are no fundamental differences between OAuth 2.1 and OAuth 2.0 and you will often see the terms used interchangeably. This article concentrates on 2.1 but calls out where there are changes.</p><p><strong>OIDC</strong></p><p><a href="https://openid.net/connect/">OIDC</a> (OpenID Connect) is a protocol that sits on top of OAuth. Whilst OAuth is specifically concerned with authorisation (what a user is allowed to do), OIDC is about authentication (the identity of the user)</p><p><strong>JWT</strong></p><p>Tokens used in both OAuth and OIDC are generally in the form of a <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JWT</a> (JSON Web Token). JWT is a compact and self-contained format for representing token information. JWT tokens contain three parts (separated by a ‘.’):</p><ul><li>Header — contains information about the type of token and the signing algorithm used.</li><li>Payload — contains ‘claims’ which are fields of information about an entity (a user in our case)</li><li>Signature — the signature is used to ensure the JWT was created/signed by the correct keypair and has not been tampered with</li></ul><p>The 3 parts of the token are base64 encoded. When debugging auth flows it can be useful to copy the Authorisation header in the JWT format of xxxxx.yyyyy.zzzzz and paste it into a JWT decoder such as <a href="https://jwt.io/">jwt.io</a> to see the full set of fields / claims.</p><h3>Authorisation via OAuth</h3><p>In order to best illustrate OAuth in action, we will introduce a real world scenario:</p><p><em>“A user named Bob would like to use a new calendar creation application called bookit.com and Bob wants to allow it to access his photographs stored on Google Drive.”</em></p><p>We’ll start by looking at the Actors involved in a typical OAuth flow, discuss scopes, client types, choose a flow that best suits this use case, and provide a walkthrough. We’ll outline some of the important endpoints from the OAuth specification, take a deeper dive into some parts of the flow and why they are so important.</p><p><strong>Actors</strong></p><p>Below is a list of actors introduced by the OAuth specification and how they align in this scenario:</p><ul><li>Resource Owner — The entity that can grant access to the protected resources. This is usually the end user (Bob in this case)</li><li>Client — The application requesting access to the protected resource on behalf of the resource owner. (The bookit.com application)</li><li>Resource Server — The server hosting the protected resources. (Google Drive)</li><li>Authorisation Server — The server that authenticates the Resource Owner and provides authorisation via Access Tokens. (Google Authorisation Server)</li></ul><p>The diagram below shows the actors in this scenario and the roles they play:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*uFLS8wdr3QlbEbAa.png" /></figure><p><strong>Scopes</strong></p><p>Scopes in OAuth are like permissions. They are the list of things that the user is going to agree to allow the application to do on behalf of them. In our example, the scope is ‘photos.read’, meaning that Bob wants to agree for bookit.com to access his photos on Google Drive. These scope strings are declared and managed by the Authorisation Server. The scopes available in a given Authorisation Server can be advertised via some of the discovery endpoints that are often made available, depending on the Authorisation Server being used.</p><p><strong>Flows / Grant types</strong></p><p>As we alluded to earlier, the OAuth protocol specifies a number of flows or ‘grant types’ which can be used to satisfy the requirement as outlined in the bookit example above. OAuth 2.1 has consolidated this list of Grant Types and the type to choose depends on the specific use case and the types of applications involved. The main Grant Types are as follows</p><ul><li>Authorisation Code — the recommended Grant Type when possible. This is a 2 step process that involves a user and browser redirects to provide a secure flow for generating an access token. The remainder of this series will focus on this Grant Type.</li><li>Client Credentials — Used for machine to machine communication where there is no user involved. Think of a scheduled job that needs to access resources on a resource server somewhere.</li><li>Refresh — A mechanism for exchanging a refresh token for a new access token but without the user needing to go through the authentication and authorisation steps again. Note that Refresh tokens can be revoked in the Authorisation Server (unlike access tokens, which will always be valid until they expire) to prevent subsequent access tokens being granted via that refresh token.</li></ul><p>There are some extension Grant Types available which are beyond the scope of this article. It is also worth noting that a number of Grant Types that were available in OAuth 2.0 have been deprecated in OAuth 2.1.</p><ul><li>Implicit — previously intended for applications running in a browser without a backend</li><li>Password — a way to exchange explicit security credentials for an access token. Previously used for native clients</li></ul><p>Our use case above has all the components that lend itself best to one of the most widely used and secure Grant Types called ‘Authorisation Code’.</p><p>Let’s take a look at the exact steps involved in this particular Authorisation Code Grant flow. Note that Bob will be accessing bookit.com in a browser, this is important as the Authorisation Grant flow depends on browser redirects to complete successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziY8t5f3pOGhBhTD.png" /></figure><ol><li>Bob would like to allow bookit.com to access his Drive photographs.</li><li>Bookit.com returns a HTTP redirect response to Bob’s Browser sending him to auth.google.com to perform the authorise step. The query parameters on the redirect URL include:</li></ol><ul><li>scope=photos.read — what we want to allow bookit.com to be allowed to do</li><li>response_type=code — indicating we want the authorisation code grant type</li><li>redirect_url — the URL to redirect the user to once the authorisation step is successful</li></ul><p>3. Bob’s browser displays a login form returned by auth.google.com and Bob is asked to authenticate with Google Auth Server, using his Google username and password.</p><p>4. Upon Successful authentication, Google Auth Server asks Bob to confirm he is happy to grant the application bookit.com ‘photos.read’ access. Bob confirms he is happy with this.</p><p>5. Bob’s Browser is now redirected back to the bookit.com callback endpoint, passing a query param called ‘code’ which is the Authorisation Code that has been created</p><p>6. Bookit.com now needs to exchange the authorisation code for an actual access token. Bookit.com calls the Authorisation Server’s /token endpoint with the authorisation code to do this.</p><p>7. The Authorisation Server responds with a successful response that includes an access token and an expiry time. The access token is in the form of a JWT, issued and signed by the Google Authorisation Server and includes a scope claim of ‘photos.read’.</p><p>8. Bob can now ask bookit.com to retrieve photos from Google Drive until the access token expires. Each time bookit.com does that, it will include the access token as a bearer token in a HTTP Authorisation header</p><p>9. Each time Google Drive receives a call from bookit.com it can verify the access token before responding. Typically it will perform validation such as:</p><ul><li>Ensuring the token is issued and signed by the correct Authorisation Server (auth.google.com)</li><li>Ensure that the token has the required scope (photos.read in this case)</li><li>Ensure the token has not expired</li></ul><p><strong>OAuth endpoints</strong></p><p>The <a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-01">OAuth specification</a> defines 2 main endpoints as you can see from the 2 calls to the Google Authorisation Server in the flow above (Steps 2 and 6 in the sequence diagram above):</p><ul><li>Authorisation — This endpoint is concerned with the authorisation itself. I.e. obtaining authorisation that the user has allowed consent to the application for that scope. The eventually resulting response type depends on the grant type, for the Authorisation Code Grant Type, the response will include an authorisation code.</li><li>Token — This endpoint is for exchanging an authorisation grant for an access token. In our example, the authorisation step returned an authorisation code, and the application then exchanged it for an access token. The response can also contain a refresh token that can be used to exchange for another access token once the previous one has expired, without the user having to go through the authorisation step again.</li></ul><p><strong>Confidential vs Public clients</strong></p><p>There is another consideration when using OAuth flows. Whether the client will be ‘Confidential’ or ‘Public’. Confidential clients can be used when the component calling /token to exchange the Authorisation Code for an access token is able to store secrets securely to include as part of the call. An example of a Confidential Client is a traditional server side web application where HTML is rendered server-side. Secrets can be stored here and not be available to any user and the call to /token can happen in a private manner and is not viewable by the user.</p><p>Public clients involve a component where secrets can’t be securely stored and the call to /token typically happens from the browser, meaning that a user can have full visibility of the call. An example of this type of application is a Single Page Application (SPA) such as a React application; this cannot store secrets because they would be available to the user in a browser.</p><p><strong>More detail on the OAuth calls</strong></p><p>In the walkthrough above, to aid clarity, we glossed over a number of security details that are crucial to OAuth, but they need to be explained in more detail to understand the security behind OAuth.</p><ul><li><strong>PKCE</strong> The 2 API calls to the Authorisation Server should actually involve some more parameters than shown above. In order to prevent Code Injection and CSRF attacks, a mechanism called PKCE (Proof Key for Code Exchange) — pronounced Pixie is used. This was an optional addition to the Authorisation Grant type in OAuth 2.0 (which used a state parameter to prevent these attacks) but is mandatory in OAuth 2.1. <a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">The second article</a> in this series shows this in more detail but for now it is enough to know that the purpose of PKCE is to ensure that a malicious user cannot intercept an authorisation code and exchange it themselves for a token.</li><li><strong>Client Secret</strong> In ‘Confidential Clients’ the call to the /token endpoint in step 6 will also typically contain a client_secret — this is a secret string which is associated with the client when it is initially registered with the Authorisation Server during initial setup. Initial setup is a one off activity that happens before an application can use OAuth. The client (bookit.com) must be registered with the Authorisation Server, at which point the client will be issued with a client ID and secret. Note that setup is not part of the OAuth spec, so each Authorisation Server will have a slightly different implementation for this. The client_secret is a sensitive value and if used, is one of the reasons that this /token call needs to be made on a ‘back channel’ i.e. not from a browser that is accessible to a human user; this is why it is only appropriate for a Confidential client. In ‘Public’ clients, a client_secret would not be used, in this case PKCE should always be used.</li><li><strong>Token Verification</strong> When a Resource Server verifies a token (step 9), it can do some of it based on the contents of a token, e.g. ensuring the expiry time has not passed and that the token contains the correct scope to perform the action. But how does the Resource Server know that it can trust a token? What stops Bob modifying his JWT token and using that instead? This is thanks to the signature of the JWT. Using asymmetric encryption techniques, the Resource Server can assert that 1) the token has been created by the correct Authorisation Server and 2) that it has not been tampered with. OAuth Authorisation Servers typically provide a list of public keys from key pairs that it uses to sign tokens. The Resource Server can obtain the public key for the key pair that was used to sign the token and use it to verify the signature. This is secure because that signature could only have been created by the holder of the private key of that pair, which only the Authorisation Server will have.</li><li><strong>Redirect URL verification</strong> Whenever a redirect URL is provided (e.g. on both Authorisation Server API calls), the RedirectURLs <a href="https://www.oauth.com/oauth2-servers/redirect-uris/redirect-uri-validation/">must be validated</a> against the list of acceptable URLs provided when the application is registered at setup time. I.e. callers can’t just ask the Authorisation Server to redirect to any arbitrary URL.</li></ul><h3>Authentication via OIDC</h3><p>Hopefully it is now clear that OAuth is about authorisation and not authentication. It has no support for identity or ‘who someone is’, it is only concerned with ‘what someone can do’. This is where OpenID comes in.</p><p>OpenID Connect extends OAuth by introducing:</p><ul><li>A new id_token</li><li>A new UserInfo endpoint</li><li>New standard scopes and claims for identities such as profile, email, address and phone Discovery endpoints</li></ul><p>To look at some of this in action, lets see a typical authorisation request using OIDC (notice the scopes of openid, profile and email)</p><pre>https://authorization-server.com/authorize?<br>response_type=code<br>&amp;client_id=zYxTG8yyNtuPvm3et--kDVDC<br>&amp;redirect_uri=https://www.oauth.com/playground/oidc.html<br>&amp;scope=openid+profile+email+photos<br>&amp;state=P6A0oPurupqWg43d<br>&amp;nonce=12Pk2dUpTv6SqRuV</pre><p>And the response that comes back from the /token endpoint (notice the new id_token) field</p><pre>{<br>   &quot;token_type&quot;: &quot;Bearer&quot;,<br>   &quot;expires_in&quot;: 86400,<br>   &quot;access_token&quot;: &quot;Gf…_IP&quot;,<br>   &quot;scope&quot;: &quot;openid profile email photo&quot;,<br>   &quot;id_token&quot;: &quot;eyJraWQ….Q&quot;<br>}</pre><p>Because the id_token is a JWT, it can be decoded using jwt.io and this time the claims in the body will include identity related fields such as name and email.</p><pre>{<br>   &quot;sub&quot;: &quot;precious-centipede@example.com&quot;,<br>   &quot;name&quot;: &quot;Precious Centipede&quot;,<br>   &quot;email&quot;: &quot;precious-centipede@example.com&quot;,<br>   &quot;iss&quot;: &quot;https://pk-demo.okta.com/oauth2/default&quot;,<br>   &quot;aud&quot;: &quot;zYxTG8yyNtuPvm3et--kDVDC&quot;,<br>   &quot;iat&quot;: 1683291571,<br>   &quot;exp&quot;: 1685883571,<br>   &quot;amr&quot;: [<br>      &quot;pwd&quot;<br>   ]<br>}</pre><h3>Summary and further reading</h3><p>This article has introduced some key concepts around authentication and authorisation and looked at what is provided by the OAuth and OIDC protocols. The next couple of articles in this series will pick an Authorisation Server and show how you might use it to secure your services depending on the types of applications you have.</p><ul><li><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part2.html">Part 2</a> shows a concrete example of how OAuth and OIDC can be used in a Public application to complement each other, providing a good solution for authentication and authorisation for a range of use cases.</li><li><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part3.html">Part 3</a> does something similar, but this time demonstrates a confidential client in action.</li><li><a href="https://www.lydtechconsulting.com/blog-oauth-oidc-part4.html">Part 4</a> Looks at using a custom Authorisation Server to replace Keycloak, chosen for Part 2 and 3.</li></ul><p>There are many OAuth and OIDC references online and we’d encourage you to research further. The following is a great video by OKTA to introduce some of these ideas: <a href="https://www.youtube.com/watch?v=996OiexHze0">Oauth 2.0 and OpenID connect in plain english</a></p><p>Finally, a brilliant resource to help learn some of the OAuth / OIDC flows is the <a href="https://www.oauth.com/playground/">OAuth playground</a> where you can follow each of the flows step by step.</p><h3>Want to read more?</h3><p>Head over to <a href="https://www.lydtechconsulting.com/">Lydtech Consulting</a> to <a href="https://lydtechconsulting.com/blog-oauth-oidc-part1.html">read this article</a> and many others on interesting areas of software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9403ac2a3ed6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lydtech-consulting/authentication-and-authorisation-using-oidc-and-oauth-2-part-1-9403ac2a3ed6">Authentication and Authorisation using OIDC and OAuth 2. Part 1</a> was originally published in <a href="https://medium.com/lydtech-consulting">Lydtech Consulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Kafka with Mutual TLS and ACLs]]></title>
            <link>https://medium.com/lydtech-consulting/securing-kafka-with-mutual-tls-and-acls-b235a077f3e3?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/b235a077f3e3</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Fri, 06 May 2022 07:32:48 GMT</pubDate>
            <atom:updated>2023-02-28T15:22:13.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The purpose of this article is to outline what it means to secure a Kafka installation with mutual TLS (Transport Layer Security), what the advantages are, and a practical example of how to achieve this. Kafka’s default configuration means that traffic is not encrypted and no authentication / authorisation takes place. This will not be acceptable for many production environments.</p><p>Kafka provides a number of security mechanisms that allow a range of authentication / authorization options. Many of these options are provided using the SASL (Simple Authentication and Security Layer) scheme. Keep tuned for another Lydtech article on this. This article focuses on securing Kafka using a combination of Mutual TLS and Kafka ACLs providing the following:</p><ul><li>Authentication: Proving that the server / client are who they say they are</li><li>Authorization: Deciding what an authenticated user can do</li><li>Encryption: Ensuring traffic cannot be read by eavesdroppers</li></ul><h3>What is TLS</h3><p>Most of us use TLS (previously known as SSL [Secure Sockets Layer] but the terms are often used interchangeably) everyday. Most websites these days will use TLS to provide a minimum level of security. Specifically, the server will present a certificate that only it will have the private key for. This certificate will give clients confidence that the server is who it says it is (<em>authentication</em>); this is achieved by the certificate being issued / signed by a Certification Authority (CA) which the client trusts. Furthermore, the client and server will decide upon a shared secret (session key) which can be used to encrypt all traffic that travels between them (<em>encryption</em>). A full explanation of TLS is beyond the scope of this article but <a href="https://www.cloudflare.com/en-gb/learning/ssl/what-happens-in-a-tls-handshake/">this page</a> gives a good explanation.</p><h3>What is Mutual TLS (authentication)</h3><p>Mutual TLS builds on One way TLS by requiring the client to provide a certificate as part of the TLS handshake. This client certificate will typically be signed by a CA that the server trusts, so the server can be sure that the client is who they say they are. Mutual TLS also opens up authorisation options; now that the server knows who the client is, it can decide what they are allowed to do.</p><h3>What is Kafka ACL (authorisation)</h3><p><a href="https://docs.confluent.io/platform/current/kafka/authorization.html">Kafka ACL</a> (Access Control List) is an authorisation mechanism. It is a feature of Kafka that allows it to be configured such that users, or groups of users, can be permitted to perform certain actions on Kafka resources (topics, consumer groups etc)</p><h3>Working example</h3><h4>Certificate generation</h4><p>We have created an example repository at <a href="https://github.com/lydtechconsulting/kafka-mutual-tls">https://github.com/lydtechconsulting/kafka-mutual-tls</a> that contains everything needed to start a Kafka installation locally, using Docker containers, secured using mutual TLS to provide authentication, authorisation and encryption.</p><p>3 Sets of key/certificate pairs need to be created as per the diagram below:</p><ul><li><em>Certification Authority (CA) key pair</em>. The private key will only ever be known by the CA. The certificate will be trusted by the Kafka broker and client, and used to issue the client/server key pairs.</li><li><em>Server (Broker) key pair</em>. The private key will only ever be known by the Broker. Certificate is presented to the client during the TLS handshake.</li><li><em>Client key pair</em>. The private key will only ever be known by the client. Certificate will be presented to Kafka broker during the TLS handshake</li></ul><p>Below is an illustration and complete list of steps (scripts available in <a href="https://github.com/lydtechconsulting/kafka-mutual-tls">the repo</a>) to generate all certificates required for the example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*F32gAvAAv1wBCZgX" /></figure><p><strong>Create Certification Authority key / cert pair</strong></p><p>Creates a ca.key and ca.crt file for the key and cert respectively. The private key will be used to sign the client &amp; server certs. Both the Kafka server and clients will be configured to trust the ca.crt certificate as a certification authority (i.e. inherently trust any certificates signed by this CA)</p><pre>openssl req -new -x509 -keyout ca.key -out ca.crt -days 365 -subj ‘/CN=ca.kafka.lydtechconsulting.com/OU=TEST/O=LYDTECH/L=London/C=UK’ -passin pass:changeit -passout pass:changeit</pre><p><strong>Create server key / cert pair</strong></p><p>The result of the commands below are a keystore file containing a key/cert that is signed by the CA and a truststore file containing the CA cert (meaning the Kafka server will trust any client certs signed by the CA)</p><p><em># Create a private key</em></p><pre>keytool -genkey -alias lydtech-server -dname “CN=localhost, OU=TEST, O=LYDTECH, L=London, S=LN, C=UK” -keystore kafka.server.keystore.jks -keyalg RSA -storepass changeit -keypass changeit</pre><p><em># Create CSR</em></p><pre>keytool -keystore kafka.server.keystore.jks -alias lydtech-server -certreq -file kafka-server.csr -storepass changeit -keypass changeit</pre><p><em># Create cert signed by CA</em></p><pre>openssl x509 -req -CA ca.crt -CAkey ca.key -in kafka-server.csr -out kafka-server-ca1-signed.crt -days 9999 -CAcreateserial -passin pass:changeit</pre><p><em># Import CA cert into keystore</em></p><pre>keytool -keystore kafka.server.keystore.jks -alias CARoot -import -noprompt -file ca.crt -storepass changeit -keypass changeit</pre><p><em># Import signed cert into keystore</em></p><pre>keytool -keystore kafka.server.keystore.jks -alias lydtech-server -import -noprompt -file kafka-server-ca1-signed.crt -storepass changeit -keypass changeit</pre><p><em># import CA cert into truststore</em></p><pre>keytool -keystore kafka.server.truststore.jks -alias CARoot -import -noprompt -file ca.crt -storepass changeit -keypass changeit</pre><p><em># Copy to directory that is used as a docker volume</em></p><pre>cp kafka.server.*.jks secrets/server/</pre><p><strong>Create client key / cert pair</strong></p><p>The result of the commands below are a keystore file containing a key/cert that is signed by the CA and a truststore file containing the CA cert (meaning the Kafka client will trust any client certs signed by the CA)</p><p><em># Create a private key</em></p><pre>keytool -genkey -alias lydtech-client1 -dname “CN=client1.kafka.lydtechconsulting.com, OU=TEST, O=LYDTECH, L=London, S=LN, C=UK” -keystore kafka.client1.keystore.jks -keyalg RSA -storepass changeit -keypass changeit</pre><p><em># Create CSR</em></p><pre>keytool -keystore kafka.client1.keystore.jks -alias lydtech-client1 -certreq -file kafka-client1.csr -storepass changeit -keypass changeit</pre><p><em># Create cert signed by CA</em></p><pre>openssl x509 -req -CA ca.crt -CAkey ca.key -in kafka-client1.csr -out kafka-client1-ca1-signed.crt -days 9999 -CAcreateserial -passin pass:changeit</pre><p><em># Import CA cert into keystore</em></p><pre>keytool -keystore kafka.client1.keystore.jks -alias CARoot -import -noprompt -file ca.crt -storepass changeit -keypass changeit</pre><p><em># Import signed cert into keystore</em></p><pre>keytool -keystore kafka.client1.keystore.jks -alias lydtech-client1 -import -noprompt -file kafka-client1-ca1-signed.crt -storepass changeit -keypass changeit</pre><p><em># import CA cert into truststore</em></p><pre>keytool -keystore kafka.client1.truststore.jks -alias CARoot -import -noprompt -file ca.crt -storepass changeit -keypass changeit</pre><p><em># Copy to directory that is used as a docker volume</em></p><pre>cp kafka.client1.*.jks secrets/client</pre><h4>Starting Kafka</h4><p>Simply execute ‘docker-compose up -d’ to start up the Kafka installation. This will start a single Kafka broker listening on port 29092 and a Zookeeper instance listening on port 2181. The configuration means that the server uses the server keypair generated above in any TLS handshakes it performs. Additionally it will trust any keys signed by the CA.</p><h4>Creating the ACLs</h4><p>The following command adds ACL entries for our client to create, consume from and produce to 1 topic using any consumer group</p><pre>docker exec -t kafka-mutual-tls_kafka_1 /usr/bin/kafka-acls --bootstrap-server localhost:29092 --command-config /etc/kafka/secrets/certs.properties --add --allow-principal &quot;User:CN=client1.kafka.lydtechconsulting.com,OU=TEST,O=LYDTECH,L=London,ST=LN,C=UK&quot; --operation Read --operation Write --operation Create --topic my-topic</pre><pre>docker exec -t kafka-mutual-tls_kafka_1 /usr/bin/kafka-acls --bootstrap-server localhost:29092 --command-config /etc/kafka/secrets/certs.properties --add --allow-principal &quot;User:CN=client1.kafka.lydtechconsulting.com,OU=TEST,O=LYDTECH,L=London,ST=LN,C=UK&quot; --operation Read --group &#39;*&#39;</pre><h4>Connecting to the broker</h4><p>The examples below use the Kafka CLI (running inside docker containers) to connect to the sample Kafka broker using TLS. Note the following file is needed and will be specified by a command line argument for each client command executed. It tells the client where the keystore, truststore and what the credentials are. Note that this configuration is similar to the server side; the client will use the keypair from the keystore in any TLS handshakes it performs and will trust any certs signed by the CA.</p><pre>ssl.truststore.location=/etc/kafka/secrets/kafka.client1.truststore.jks<br>ssl.truststore.password=changeit<br>ssl.keystore.location=/etc/kafka/secrets/kafka.client1.keystore.jks<br>ssl.keystore.password=changeit<br>ssl.key.password=changeit<br>ssl.endpoint.identification.algorithm=<br>security.protocol=SSL</pre><p>Note: This file and all the commands below are available in the <a href="https://github.com/lydtechconsulting/kafka-mutual-tls">Lydtech kafka-mutual-tls repo</a></p><p><strong>List / create topics</strong></p><p>The following will initially show that there are no Kafka topics</p><pre>docker run -v &quot;$(pwd)/certCreation/secrets/client:/etc/kafka/secrets&quot; --network host \<br>   confluentinc/cp-kafka:latest /usr/bin/kafka-topics \<br>   --bootstrap-server localhost:29092 --list \<br>   --command-config /etc/kafka/secrets/certs.properties</pre><p><strong>Consume from a topic</strong></p><p>Start consuming from the topic my-topic (and auto create it)</p><pre>docker run -v &quot;$(pwd)/certCreation/secrets/client:/etc/kafka/secrets&quot; --network host  \<br>   confluentinc/cp-kafka:latest /usr/bin/kafka-console-consumer \<br>   --bootstrap-server localhost:29092 --topic my-topic --from-beginning \<br>   --consumer.config /etc/kafka/secrets/certs.properties</pre><p><strong>Publish to a topic</strong></p><p>Publish to the topic (in another shell window/tab). Any message typed will appear in the consumer window, proving a successful publish / consume)</p><pre>docker run -v &quot;$(pwd)/certCreation/secrets/client:/etc/kafka/secrets&quot; --network host -ti \<br>   confluentinc/cp-kafka:latest /usr/bin/kafka-console-producer \<br>   --bootstrap-server localhost:29092 --topic my-topic \<br>   --producer.config /etc/kafka/secrets/certs.properties</pre><p><strong>TLS authentication failure</strong></p><p>To prove that TLS is enabled and working correctly, attempt to connect to the broker without TLS (omit the consumer.config argument)</p><pre>docker run -v &quot;$(pwd)/certCreation/secrets/client:/etc/kafka/secrets&quot; --network host  \<br>   confluentinc/cp-kafka:latest /usr/bin/kafka-console-consumer \<br>   --bootstrap-server localhost:29092 --topic my-topic --from-beginning</pre><p>The client will display an error such as</p><pre>[2022–04–22 12:19:39,875] WARN [Consumer clientId=consumer-console-consumer-1660–1, groupId=console-consumer-1660] Bootstrap broker localhost:29092 (id: -1 rack: null) disconnected (org.apache.kafka.clients.NetworkClient)</pre><p>But the docker logs (docker logs kafka-mutual-tls-kafka-1) show a more definitive reason for the failure</p><pre>[2022–04–22 12:19:40,117] INFO [SocketServer listenerType=ZK_BROKER, nodeId=1] Failed authentication with /172.18.0.1 (SSL handshake failed) (org.apache.kafka.common.network.Selector)</pre><p><strong>ACL authorisation failure</strong></p><p>To prove that ACL works, attempt to consume from a topic that is not covered by our ACL entry:</p><pre>docker run -v &quot;$(pwd)/certCreation/secrets/client:/etc/kafka/secrets&quot; --network host \<br>   confluentinc/cp-kafka:latest /usr/bin/kafka-console-consumer \<br>   --bootstrap-server localhost:29092 --topic other-topic --from-beginning <br>   --consumer.config /etc/kafka/secrets/certs.properties</pre><p>An error such as the following will be observed showing the authorisation failure.</p><pre>[2022–04–22 15:02:30,213] ERROR [Consumer clientId=consumer-console-consumer-22992–1, groupId=console-consumer-22992] Topic authorization failed for topics [other-topic] (org.apache.kafka.clients.Metadata)</pre><h3>How it works</h3><h4>TLS Handshake</h4><p>The diagram below shows a simplified view of the TLS handshake that takes place when a client attempts to connect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x3JEbmNj08bTDCUL" /></figure><ol><li>The client attempts to connect to the broker</li><li>The broker provides its certificate to the client</li><li>The client validates the certificate. It checks things like:<br>- Does the hostname in the certificate match what the client tried to connect to<br>- Does the broker own the certificate? Proves that the broker has the private key. Without this it could not have signed the message.<br>- Does the client trust the broker certificate? I.e. Is it signed by a CA that the client trusts?</li></ol><p>4. Broker requests the client certificate (because this is mutual TLS)</p><p>5. Client provides its certificate to the broker</p><p>6. Broker validates the client cert (similar steps as in step 3 above)</p><p>7. Connection is successful</p><h4>Authorisation (via Kafka ACL)</h4><p>Once the TLS handshake is complete, Kafka will then consult its ACL configuration to see if the authenticated user (principal) is allowed to perform the requested action on that resource. By default, the value of ‘principal’ will be the ‘DistinguishedName’ from the client certificate. This can be customised as per the <a href="https://docs.confluent.io/platform/current/kafka/authorization.html#tls-ssl-principal-user-names">Kafka ACL documentation</a>.</p><h3>Connecting via other means</h3><h4>Java</h4><p>See the Lydtech <a href="https://github.com/lydtechconsulting/kafka-spring-consumer#using-mutual-tls">Spring Boot Kafka consumer</a> repo for an example client configured with mutual TLS. To summarise, the following Spring Boot properties can be set to support mutual TLS:</p><pre>spring.kafka.security.protocol=SSL</pre><pre>spring.kafka.ssl.trust-store-location=classpath:tls/kafka.client.truststore.jks</pre><pre>spring.kafka.ssl.trust-store-password=changeit</pre><pre>spring.kafka.ssl.key-store-location=classpath:tls/kafka.client.keystore.jks</pre><pre>spring.kafka.ssl.key-store-password=changeit</pre><h4>KafkaJS</h4><p>Enabling TLS via KafkaJS is documented <a href="https://kafka.js.org/docs/configuration#ssl">here</a>. The ‘ssl’ block in config can be used to provide the ca cert and client key and cert:</p><pre>const kafka = new Kafka({<br>   clientId,<br>   brokers: [kafkaAddress],<br>   ssl: {<br>      rejectUnauthorized: false,<br>      ca: [fs.<em>readFileSync</em>(&#39;/tmp/ca.crt&#39;, &#39;utf-8&#39;)],<br>      key: fs.<em>readFileSync</em>(&#39;/tmp/client-key.pem&#39;, &#39;utf-8&#39;),<br>      cert: fs.<em>readFileSync</em>(&#39;/tmp/client-cert.pem&#39;, &#39;utf-8&#39;)<br>   }<br>})</pre><h3>Drawbacks of using TLS for Kafka security</h3><p>Below is a list of drawbacks of using this TLS &amp; ACL approach for Kafka security</p><ul><li>Revocation or certificates / users isn’t trivial</li><li>Mutual TLS will have a performance impact as it is more CPU intensive. The impact of this depends on many factors including how and where Kafka is run and the types of encryption algorithms used for the TLS.</li><li>Manually managing TLS certificates and ACL entries could quickly become unwieldy, meaning this may not be a scalable solution</li><li>This means of security could be seen as inflexible. Many organisations will require authentication / authorisation to be integrated with their existing security ecosystem.</li></ul><h3>Conclusion</h3><p>This article has demonstrated how to secure a Kafka installation using a combination of TLS and Kafka ACL to provide encryption, authentication and authorisation. It is supported by an <a href="https://github.com/lydtechconsulting/kafka-mutual-tls">example repo</a> containing all the commands used here.</p><p>Keep an eye out for future, related articles that we have in the pipeline</p><ul><li>Example of configuring mutual TLS on a AWS MSK setup</li><li>A deeper dive into using SASL with Kafka</li><li>Tips on troubleshooting common TLS connection / authorisation issues</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px1Y355yyrBESDV21WKrng.jpeg" /></figure><h3>Want to read more?</h3><p>Head over to <a href="https://www.lydtechconsulting.com/">Lydtech Consulting</a> to <a href="https://www.lydtechconsulting.com/blog-kafka-tls.html">read this article</a> and many others on interesting areas of software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b235a077f3e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lydtech-consulting/securing-kafka-with-mutual-tls-and-acls-b235a077f3e3">Securing Kafka with Mutual TLS and ACLs</a> was originally published in <a href="https://medium.com/lydtech-consulting">Lydtech Consulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden cost of AWS Lambdas]]></title>
            <link>https://medium.com/lydtech-consulting/the-hidden-cost-of-aws-lambdas-c42477c3f368?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42477c3f368</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[lean-startup]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 08:23:45 GMT</pubDate>
            <atom:updated>2023-02-28T15:24:09.525Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Background</strong></p><p>Agile principles and strategies such as <a href="http://theleanstartup.com/">Lean Startup</a> outline how important it is when developing a new product to get user engagement and feedback early and often. To this end, during the early stages of <a href="http://ovalview.io/">ovalview.io</a>, we wanted to prove the concept with a very simple MVP (Minimal Viable Product). We needed the quickest and most cost effective way to stand up a backend service that exposed a REST API so that we could allow interested parties to use the app and provide feedback. This article documents the approach we used and some lessons learned for future ventures.</p><p><strong>Iteration 1</strong></p><p>On the surface, FaaS (Function as a Service) using AWS Lambda seemed like a good candidate for this; only pay for what you use and no servers to think about.</p><p>We created our API using NodeJS, the Serverless framework and AWS Cognito for authentication; this allowed us to get a secure, working application quickly. Serverless made deployments simple and it was costing us very little in terms of minimum AWS monthly cost.</p><p><em>Estimated minimum monthly cost</em></p><ul><li>API Gateway, Lambda, Cognito, Cloudfront, Route53: Negligible</li><li>RDS: ~$20</li><li><strong>Total: ~$20 per month</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*_p3TIRroPe2ZQbDNGxqf1g.png" /></figure><p><strong>Iteration 2</strong></p><p>The jump in cost came when our service needed to make HTTP calls to the outside world, in this case to update Jira; an important proposition in Ovalview.</p><p>Making outbound HTTP calls from a Lambda attached to a VPC (needed for RDS access) requires a NAT Gateway. NAT Gateways are surprisingly pricey in AWS and all of a sudden our minimum AWS bill per month had tripled to over $65 a month.</p><p><em>Estimated minimum monthly cost</em></p><ul><li>API Gateway, Lambda, Cognito, Cloudfront, Route53: Negligible</li><li>RDS: ~$20</li><li>NAT Gateway: ~$45</li><li><strong>Total: ~$65 per month</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*KGXe26DbibYeTj50kZnuaQ.png" /></figure><p><strong>A more cost effective alternative?</strong></p><p>On reflection, although not an architecture that is advisable for any long term product, for our initial prototype, we could have just run a small EC2 instance in a public subnet which would have avoided the need for a NAT Gateway and therefore been significantly cheaper.</p><p><em>Estimated minimum monthly cost</em></p><ul><li>Cognito, Cloudfront, Route53: Negligible</li><li>RDS: ~$20</li><li>EC2 instance: ~$5</li><li><strong>Total: ~$25 per month</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*OW9FXwiboKeaON38Ovza9w.png" /></figure><p><strong>A Hybrid solution</strong></p><p>One of the trade-offs with the single EC2 instance approach above is the scalability afforded by using Lambdas. A possible, but more involved alternative, would be to continue using the Lambdas but configure the code to use a HTTP proxy sitting inside a public subnet as per the diagram below. The EC2 instance would need to have one of the following:</p><ul><li>a HTTP proxy service using something like TinyProxy as documented <a href="https://medium.com/@yurysmykalov/aws-lambda-with-static-outgoing-ip-a-complete-no-vpc-tutorial-8b994229dee4">here</a></li><li>Networking configuration to make it act like a NAT Gateway</li></ul><p><em>Estimated minimum monthly cost</em></p><ul><li>As above</li><li><strong>Total: ~$25 per month</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*BnQ_gSxB2WNdh-oIiKQHfA.png" /></figure><p><strong>Conclusion</strong></p><p>This article proposes 2 methods to avoid incurring the expense of using a NAT Gateway for projects that are in their infancy, where the goal is a low cost method to demonstrate an idea and gain quick feedback. Once the proposition was deemed to have value, work would then need to be done to create a scalable, resilient architecture, following industry best practices.</p><p><em>A note on pricing estimates</em></p><ul><li>Accurate as at time of writing (Feb, 2022)</li><li>Based on eu-west-2 (London). Tax at 20% (UK VAT)</li><li>Leveraging ‘always free’ tier of Lambda, Cognito &amp; Cloudfront</li><li>Based on services running for a whole month (730 hours in an average month)</li><li><a href="https://aws.amazon.com/lambda/pricing/">Lambda</a> / <a href="https://aws.amazon.com/api-gateway/pricing/">API Gateway</a> pricing (effectively free for our initial usage)</li><li><a href="https://aws.amazon.com/cognito/pricing/">Cognito</a> pricing (effectively free for our initial usage)</li><li><a href="https://aws.amazon.com/rds/postgresql/pricing/?pg=pr&amp;loc=3">RDS</a> pricing. Based on a Postgres db.t3.micro instance @$0.021 per hour (plus some storage costs)</li><li><a href="https://aws.amazon.com/vpc/pricing/">NAT Gateway</a> pricing @$0.05 per hour</li><li><a href="https://aws.amazon.com/ec2/pricing/on-demand/">EC2</a> pricing. Based on a t3.nano instance @$0.0052 per hour</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVppzMyjvRglmApmPx8Ekw.jpeg" /></figure><h3>Want to read more?</h3><p>Head over to <a href="https://www.lydtechconsulting.com/">Lydtech Consulting</a> to <a href="https://www.lydtechconsulting.com/blog-hidden-cost-lambdas.html">read this article</a> and many others on Kafka and other interesting areas of software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42477c3f368" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lydtech-consulting/the-hidden-cost-of-aws-lambdas-c42477c3f368">The hidden cost of AWS Lambdas</a> was originally published in <a href="https://medium.com/lydtech-consulting">Lydtech Consulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring JHipster]]></title>
            <link>https://medium.com/lydtech-consulting/exploring-jhipster-6c567f3b7d77?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c567f3b7d77</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jhipster]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 21:20:34 GMT</pubDate>
            <atom:updated>2023-02-28T15:25:16.645Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Background</strong></p><p>Almost 15 years ago I developed a relatively simple CRM system for a small company. The requirements were to track customers, products and orders and there was a need for Microsoft Word integration for producing templated letters. For reasons that don’t seem obvious now I chose to implement it as a Windows desktop application in C#.NET, partly because of the simple Word integration and partly because I was working on a .NET project at the time. Fast forward a decade and a half and the system is still heavily used by the company, they are still asking for new features, I have very little time to devote to this and I’ve not touched .NET much since that project.</p><p>I’ve wanted to re-write the solution for a long time and decided to bite the bullet. It seemed obvious that it would be much better suited as a web application; I wanted the backend to be in Java because, although I would have liked to experiment with something different, time was a huge factor. Then came the front end technology choice; I’m relatively familiar with a number of Javascript frameworks but found the concept of starting a project from scratch daunting.</p><p><strong>JHipster</strong></p><p>I’d been following the <a href="https://www.jhipster.tech/">JHipster project</a> for some time and after some additional research decided that it would be a good fit for what I wanted. In essence, JHipster is a tool that allows you to quickly generate a modern, full-stack web application with a Java backend using Spring Boot and a front end in a choice of popular frameworks.</p><p>There is now a lot more to JHipster but for my use case it offered an extremely quick path to a fully functional, secure, resilient web application. Using it meant I had to spend very little time on developing many of the non-functional requirements that most modern applications have. Furthermore, JHipster appears to be backed by a strong community including some prominent individuals such as Matt Raible and companies such as Okta.</p><p><strong>Creating An Application</strong></p><p>JHipster is installed via a single npm command, although there are now some other options such as using a docker container or some online generator options. Once installed, creating an initial application is quick and easy — running the ​jhipster ​command executes a command line generator which asks the user a number of questions to decide what to create, such as:</p><ul><li>Application type — essentially to decide between a simple monolithic application and a myriad of microservice options (I only needed the former)</li><li>Authentication type — (JWT [default], OAuth 2.0 / OIDC Authentication that uses Keycloak or Okta). The default was sufficient for me</li><li>Which development &amp; production database is desired (All popular SQL databases appear to be supported along with a range of NoSQL options). PostgresSQL was my choice.</li><li>Caching options, Maven vs Gradle, Testing frameworks etc</li><li>Additional technology options such as the following (each of which would be configured using best practices and sensible defaults if chosen):</li><li>API first development using Swagger-Codegen</li><li>ElasticSearch</li><li>Hazelcast</li><li>Websockets</li><li>Kafka</li></ul><p>Front end technology choice. Main options appear to be React or Angular; I opted for the former.</p><p>The result of running this generator is a fully configured Gradle or Maven project. Now is a good time to use a source control tool like Git so that any changes made by subsequent generator runs can easily be identified (from experience things can get confusing without this when running other commands).</p><p><strong>Entities, Controllers and Services</strong></p><p>Once the project is created, the application itself is created around the entities of your project. I initially required entities such as Customer, Product, Order, OrderItem.</p><p>Creating an entity involves running ​jhipster entity ​whereupon you will be prompted with questions related to generating the entity such as:</p><ul><li>Field name &amp; types</li><li>Validation requirements</li><li>Filtering &amp; Pagination requirements</li></ul><p>Creating the entity produces the following in your project:</p><ul><li>Functional Java code for a Spring controller with CRUD methods (with pagination for GETs) through to a service and repository class. Unit and integration tests proving everything works.</li><li>Database changes via the chosen tool (Liquibase / Flyway etc)</li><li>A HTML view for the entity with all relevant Javascript artifacts created (for your chosen framework) with the chosen pagination implementation (infinite scroll, links etc)</li><li>End to end (Protractor) / performance (Gatling) tests depending on configuration</li></ul><p>Entities can also be configured to have relationships in line with JPA entity relationships. For example in my application, there is a one to many relationship between Customer and Order. Choosing a relationship also results in the front end generated code having features to manage these relationships (e.g. choosing a customer from a drop down when creating an order), although I found that a significant amount of work was needed in order to get the functionality I wanted.</p><p><strong>Result</strong></p><p>The end result was an excellent starting point for creating an acceptable replacement of the legacy application I’d built all those years ago, with no loss of functionality and quite significant improvements. After experimenting with some other solutions I integrated it with the Google Docs API to provide a simple letter generation &amp; templating feature which is more streamlined than the legacy one. I ended up deploying to AWS and used NGINX and sendwithus for SSL, however I would have liked to experiment with some of the JHipster generators to aid deployment to AWS, Heroku, Azure, CloudFoundry etc.</p><p>Some of the additional benefits you immediately get from creating an application via JHipster are:</p><ul><li>Authentication</li><li>Authorisation (different levels of user — initially just ‘user’ and ‘admin’ but easily extendable)</li><li>Monitoring / Metrics</li><li>Logging</li><li>Auditing framework</li><li>Pagination / filtering</li></ul><p>My project can be seen on ​Github​. ​Some useful areas to explore, focusing on my ‘Product’ entity which has had no customisation:</p><ul><li>Generated Spring Controller class</li><li>Generated React components (Typescript)</li></ul><p>Some screenshots of the generated application are included at the end of this article.</p><p><strong>Summary</strong></p><p>I found JHipster to be hugely beneficial in creating a full stack product quickly and efficiently and reduced the time to market greatly. I really liked the way it gave me a starting point of a project with the chosen technologies configured with sensible defaults and using recommended best practices. I would suggest this could be a great tool to help develop PoCs and even MVPs from ideas / propositions, resulting in an impressive demonstrable application in a quick time frame.</p><p>There are far more features and options to JHipster than I’ve mentioned here and there is comprehensive documentation at ​jhipster.tech.​ Given more time I would like to investigate some of these other options and technologies that JHipster can leverage.</p><p><strong>Screenshots</strong></p><p>User management (as admin and user):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ymc6GBe6eaU_5yZ.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-pLok0qCV-roVwEH.jpg" /></figure><p>Metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m3PEPjDx96p07um1.jpg" /></figure><p>Auditing Framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_9ATNNKEMT-gl5KU.jpg" /></figure><p>An example of a generated page for the ‘list’ view of the ‘Product’ entity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYLSNFZ5Nd3pMIEt.jpg" /></figure><p>This has not been customised at all. Note links for Creating, Reading, Updating and Deleting the entity. All generated by the tool and fully functional.</p><p>An example of a ‘list view’ initially generated by the tool but extended to meet requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*57ydM2dTWLZ-AdBu.jpg" /></figure><p>Note pagination &amp; filtering components are generated by the tool. (Sensitive data obfuscated).</p><h4>For more articles…</h4><p>Head over to <a href="https://www.lydtechconsulting.com/blog.html">Lydtech Consulting</a> at for this and many more articles on interesting areas of software development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*bHnsPYbVBtgj2C-zIGhzZQ.png" /></figure><h3>Want to read more?</h3><p>Head over to <a href="https://www.lydtechconsulting.com/">Lydtech Consulting</a> to <a href="https://www.lydtechconsulting.com/blog-jhipster.html">read this article</a> and many others on Kafka and other interesting areas of software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c567f3b7d77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lydtech-consulting/exploring-jhipster-6c567f3b7d77">Exploring JHipster</a> was originally published in <a href="https://medium.com/lydtech-consulting">Lydtech Consulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flyway in Serverless Architectures]]></title>
            <link>https://medium.com/lydtech-consulting/flyway-in-serverless-architectures-6dce36f8005?source=rss-93747b07fb72------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dce36f8005</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[flywaydb]]></category>
            <category><![CDATA[flyway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[James Powell]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 21:08:44 GMT</pubDate>
            <atom:updated>2023-02-28T15:26:10.633Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Challenge</strong></p><p><a href="https://flywaydb.org/">Flyway</a> is a great tool that provides version control for your database schema. One problem we’ve experienced recently is that, with the increasing popularity of Serverless environments, there isn’t always an obvious way to run Flyway as part of your Continuous Integration / Continuous Delivery (CI/CD) pipeline.</p><p>Flyway needs access to your database, which should not be publicly accessible. But Flyway needs to run from a location with Database access. Traditionally this could be achieved by having a permanent bastion instance as part of your infrastructure. In a Serverless environment, it is likely that your stack has no fixed instances with DB access. Furthermore, bastion instances introduce an unnecessary security risk and financial cost.</p><p><strong>The Solution</strong></p><p>We’ve developed a solution for this in the form of an AWS Lambda function that can be invoked to perform the Flyway migration against your Database. The project can be found on <a href="https://github.com/lydtechconsulting/flyway-lambda">Lydtech’s Github</a>. The diagram below outlines how the solution works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*j9hoXjNhGhCVZOsc.png" /></figure><p><em>Figure 1</em></p><p>Your CD pipeline will control Flyway execution via a Lambda. It will use an S3 bucket to upload the Flyway scripts. The general flow as depicted in figure 1 is:</p><ol><li>CI / CD pipeline uploads Flyway artifacts (SQL / Java files) to an S3 bucket</li><li>CI / CD pipeline invokes Lambda</li><li>Lambda retrieves files from S3 bucket</li><li>DB user password is retrieved from Secrets Manager</li><li>Lambda executes S3 bucket against RDS instance</li></ol><p>The result is that once the required components have been provisioned (details below). Your CI / CD pipeline can just do the following to achieve points 1 and 2 above and run a flyway migrate. Consider that your flyway scripts are in ./flyway/sql, your S3 bucket is myapp-flyway-migrations and your lambda is named myapp-flyway-migration:</p><pre># Synchronise s3 bucket with sql directory (--delete deletes any files on the target which no longer exist)<br>aws s3 sync ./flyway/sql s3://myapp-flyway-migrations --delete</pre><pre># Invoke flyway lambda, passing 2 parameters<br>aws lambda invoke \<br>    --function-name myapp-flyway-migration out \<br>    --log-type Tail \<br>    --payload &#39;{ &quot;bucket_name&quot;: &quot;myapp-flyway-migrations&quot;, &quot;secret_name&quot;: &quot;myapp_db_creds&quot; }&#39; \<br>    --cli-binary-format raw-in-base64-out</pre><p><strong>The Details</strong></p><p>In order to use this approach, the following setup steps need to be performed before being able to invoke the Lambda:</p><ol><li>S3 bucket setup</li><li>Create secret for DB password</li><li>Create IAM Lambda execution role</li><li>Deploy the Lambda</li><li>Create IAM user to invoke Lambda</li></ol><p>The remainder of this article details each of these steps. Note: it assumes familiarity with AWS.</p><p><strong>1. S3 bucket setup</strong></p><p>With your AWS credentials set as environment variables, run the following:</p><pre>#create bucket<br>aws s3api create-bucket \<br>    --bucket myapp-flyway-migrations \<br>    --region eu-west-2 \<br>    --create-bucket-configuration LocationConstraint=eu-west-2</pre><pre>#block all public access<br>aws s3api put-public-access-block \<br>    --bucket myapp-flyway-migrations \<br>    --public-access-block-configuration  &quot;BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true&quot;</pre><p><strong>2. Create secret for DB password</strong></p><pre>aws secretsmanager create-secret \<br>    --name myapp_db_creds \<br>    --secret-string &#39;{&quot;db_password&quot;: &quot;myDbPassword&quot;}&#39;</pre><p><strong>3. Create IAM Lambda execution role</strong></p><p>Create an execution role for the Lambda, following the principle of least privilege this role will only have access to the S3 bucket and the secret manager entry:</p><pre>#Create role<br>aws iam create-role --role-name myapp-flyway-lambda \<br>    --assume-role-policy-document &#39;{&quot;Version&quot;: &quot;2012-10-17&quot;,&quot;Statement&quot;: [{ &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: {&quot;Service&quot;: &quot;lambda.amazonaws.com&quot;}, &quot;Action&quot;: &quot;sts:AssumeRole&quot;}]}&#39;</pre><pre># Attach required managed policies<br>aws iam attach-role-policy \<br>    --role-name myapp-flyway-lambda \<br>    --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole</pre><pre>aws iam attach-role-policy \<br>    --role-name myapp-flyway-lambda \<br>    --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole</pre><pre># Allow lambda to access s3 bucket<br>aws iam put-role-policy --role-name myapp-flyway-lambda \<br>    --policy-name allow-s3-access --policy-document \<br>&#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:GetObject&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::myapp-flyway-migrations&quot;,<br>                &quot;arn:aws:s3:::myapp-flyway-migrations/*&quot;<br>            ]<br>        }<br>    ]<br>}<br>&#39;</pre><pre># Allow lambda to access db password secret<br>aws iam put-role-policy --role-name myapp-flyway-lambda \<br>    --policy-name allow-secret-access --policy-document \<br>&#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;secretsmanager:GetSecretValue&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>               &quot;{db_password_secret_arn}&quot;<br>            ]<br>        }<br>    ]<br>}<br>&#39;</pre><p>Note: The db_password_secret_arn will be provided by step 2.</p><p><strong>4. Deploy the Lambda</strong></p><p>Download the code artifact from Github:</p><pre>curl -L -o flyway-lambda.jar \<br>https://github.com/lydtechconsulting/flyway-lambda/releases/latest/download/flyway-lambda-jar-with-dependencies.jar</pre><p>Deploy the lambda to your AWS account<br>Set the following variables as per the table below</p><p><strong>PlaceholderDescriptionExample</strong>subnet-idSubnet to deploy lambda to. Must be able to access the DB.subnet-42f69738security-group-idSecurity group to place the Lambda in. Must be able to access the DB.sg-4994912flambda-execution-role-arnobtained from step 3arn:aws:iam::123456789:role/myapp-flyway-lambdadb-urlJDBC URL to the databasejdbc:postgresql://myapp-prod-db.c7c5nbuwkxpy.eu-west-2.rds.amazonaws.com/myappflyway-userUsername to connect to DBpostgresschemasName of schema that Flyway will managemyapp</p><pre># Set variables<br>SUBNET_ID={subnet-id}<br>SEC_GROUP={security-group-id}<br>LAMBDA_EXECUTION_ROLE_ARN={lambda-execution-role-arn}<br>DB_URL={db-url}<br>FLYWAY_USER={flyway-user}<br>FLYWAY_SCHEMAS={schemas}</pre><pre># Create Lambda function<br>aws lambda create-function \<br>    --function-name myapp-flyway-migration \<br>    --runtime java11 \<br>    --zip-file fileb://flyway-lambda.jar \<br>    --handler &quot;com.lydtechconsulting.flywaylambda.FlywayHandler&quot; \<br>    --timeout 120 \<br>    --memory-size 512 \<br>    --vpc-config SubnetIds=${SUBNET_ID},SecurityGroupIds=${SEC_GROUP} \<br>    --role ${LAMBDA_EXECUTION_ROLE_ARN} \<br>    --environment &#39;{ &quot;Variables&quot;: {&quot;FLYWAY_URL&quot;:&quot;&#39;&quot;${DB_URL}&quot;&#39;&quot;,&quot;FLYWAY_USER&quot;: &quot;&#39;&quot;${FLYWAY_USER}&quot;&#39;&quot;,&quot;FLYWAY_SCHEMAS&quot;: &quot;&#39;&quot;${FLYWAY_SCHEMAS}&quot;&#39;&quot;}}&#39;</pre><p><strong>5. Create IAM user to invoke Lambda</strong></p><p>Create an IAM user to use from your CI server to execute the Lambda. The user will only be able to do 2 things; sync files to the S3 bucket and execute the lambda:</p><pre># Create user<br>aws iam create-user --user-name myapp-flyway-lambda-executor</pre><pre># allow user to access s3 bucket<br>aws iam put-user-policy \<br>    --user-name myapp-flyway-lambda-executor \<br>    --policy-name flyway-s3-access --policy-document \<br>&#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:DeleteObject&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::myapp-flyway-migrations&quot;,<br>                &quot;arn:aws:s3:::myapp-flyway-migrations/*&quot;<br>            ]<br>        }<br>    ]<br>}<br>&#39;</pre><pre># allow user to invoke lambda<br>aws iam put-user-policy \<br>    --user-name myapp-flyway-lambda-executor \<br>    --policy-name flyway-lambda-access --policy-document \<br>&#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;lambda:InvokeFunction&quot;,<br>                &quot;lambda:InvokeAsync&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:lambda:eu-west-2:544193841373:function:myapp-flyway-migration&quot;<br>            ]<br>        }<br>    ]<br>}</pre><pre>&#39;<br>                    <br># Create access key and secret for user<br>aws iam create-access-key --user-name myapp-flyway-lambda-executor</pre><p><strong>Executing the lambda</strong></p><p>Now you can configure your chosen CI server to execute the lambda as per the commands shown above. You will need to use your chosen CI provider’s recommended secret management mechanism to store your AWS key and secret and access it in your pipeline.</p><p><strong>Conclusion</strong></p><p>This article has demonstrated a simple, secure and cost-effective method for running your Flyway migrations in a serverless environment.</p><h3>Want to read more?</h3><p>Head over to <a href="https://www.lydtechconsulting.com/">Lydtech Consulting</a> to <a href="https://www.lydtechconsulting.com/blog-flyway-serveless.html">read this article</a> and many others on Kafka and other interesting areas of software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dce36f8005" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lydtech-consulting/flyway-in-serverless-architectures-6dce36f8005">Flyway in Serverless Architectures</a> was originally published in <a href="https://medium.com/lydtech-consulting">Lydtech Consulting</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>