<?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 Jaiden Ashmore on Medium]]></title>
        <description><![CDATA[Stories by Jaiden Ashmore on Medium]]></description>
        <link>https://medium.com/@jaidenashmore?source=rss-e3f876684ed0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*cLYs_dh2r6lsrKGy9SA3cA.jpeg</url>
            <title>Stories by Jaiden Ashmore on Medium</title>
            <link>https://medium.com/@jaidenashmore?source=rss-e3f876684ed0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:29:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaidenashmore/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[Listening to SQS in Java Apps]]></title>
            <link>https://medium.com/@jaidenashmore/listening-to-sqs-in-java-apps-2d4f10d291f0?source=rss-e3f876684ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4f10d291f0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jaiden Ashmore]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 09:57:42 GMT</pubDate>
            <atom:updated>2020-08-03T09:57:42.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Listening to SQS in Java/Kotlin Apps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCXbcsj11yoQRcufH9afFg.png" /></figure><p>I have worked on a lot of microservices that interact with SQS queues and we used the very easy to use and robust <a href="https://github.com/spring-cloud/spring-cloud-aws/tree/master/spring-cloud-aws-messaging">Spring Cloud AWS Messaging library</a> for this. It achieved all of our business needs and there was no need to use anything else but there were some edge cases that I thought could be nice to include in a message listener library:</p><ol><li>The ability to dynamically change the concurrency rate of messages being processed while the message listener container was running. You could get around it (and we did) but I really liked the idea of having this dynamic configuration as a core component of the library. It would be nice to be able to change the concurrency rate based on logic like a feature flag or by monitoring the health of a separate microservice (think back pressure).</li><li>There was also a little edge case where if you had a concurrency rate of 10 messages and nine of them took 1 minute to run but the 10th took 3 minutes, your microservice would be sitting there waiting for the 10th to finish before fetching any more messages. This was because internally the library used a CountDownLatch which waited for all messages to be processed and therefore couldn’t retrieve another batch until that original batch was completed.</li></ol><p>As this would have been a bigger change to their library and I had very little experience with the internals of it, I wanted to see if I could create my own library that supported these use cases as well as allow easier interchanging of each component. If I wanted to change how I received messages from the SQS queue, I could switch that out but keep the rest of the code. With this I created the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener">Java Dynamic SQS Listener</a> library.</p><p>I recently released version <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/releases/tag/v4.0.0">4.0</a>, which added support for tracing and a Kotlin DSL, and <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/releases/tag/v4.1.0">4.1</a>, which added Ktor support and the ability to create a message listener using a lambda function. At this point I thought it would be a good opportunity to start writing about it in some fashion as I have done zero promotion for it so far.</p><h3>Infrastructure</h3><p>If you are interested in the architecture, here is a a really quick background design of the library. Each component has a distinct responsibility and can easily be switched out if the core implementation isn’t providing what you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*niVLO-heQDSSpKLk.png" /></figure><p>Details about each component are:</p><ul><li>The <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/retriever/MessageRetriever.java">MessageRetriever</a> handles obtaining messages from the SQS queue. This can optimise the retrieval of messages by batching requests for messages or prefetching messages before they are needed.</li><li>The <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/processor/MessageProcessor.java">MessageProcessor</a> controls the processing of a message from the queue by delegating it to the corresponding Java method that handles the message.</li><li>The <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/argument/ArgumentResolverService.java">ArgumentResolverService</a> is used by the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/processor/MessageProcessor.java">MessageProcessor</a> to populate the arguments of the message listener method. For example, a parameter with the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/core/src/main/java/com/jashmore/sqs/argument/payload/Payload.java">@Payload</a> annotation will be resolved with the body of the message cast to that type (e.g. a POJO).</li><li>The <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/broker/MessageBroker.java">MessageBroker</a> is the main container that controls the whole flow of messages from the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/retriever/MessageRetriever.java">MessageRetriever</a> to the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/processor/MessageProcessor.java">MessageProcessor</a>. It can determine when more messages are to be processed and the rate of concurrency for processing messages.</li><li>The <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/api/src/main/java/com/jashmore/sqs/resolver/MessageResolver.java">MessageResolver</a> is used after successful processing of the message and its responsibility is to remove the message from the SQS queue, so it is not processed again if there is a re-drive policy.</li></ul><p>For more information about the core implementations provided by this library, see the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/doc/core-implementations-overview.md">Core Implementations Overview</a>.</p><h3>Getting Started</h3><p>As the Spring auto configuration is the easiest to get setup, we will use this to get started. Note that this library is framework agnostic and you can build this outside of Spring.</p><p>Before you get started, you will need to make sure you have access tokens for your AWS account and a SQS queue already created. I am assuming you know how to do this, but if you don’t there will be a lot of guides online on how to set this up. For example, this <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-getting-started.html">guide</a> on how to create a queue and this <a href="https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/signup-create-iam-user.html">guide </a>for creating an IAM user.</p><ol><li>Import the <a href="https://search.maven.org/artifact/com.jashmore/java-dynamic-sqs-listener-spring-starter/4.0.0/jar">Spring Starter</a> into your system:</li></ol><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.jashmore&lt;/groupId&gt;<br>  &lt;artifactId&gt;java-dynamic-sqs-listener-spring-starter&lt;/artifactId&gt;<br>  &lt;version&gt;4.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>2. Create a SqsAsyncClient bean. We will manually configure the IAM Access Key and Secret here from your AWS but the preferred method is to use environment variables, as seen in this <a href="https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/setup-credentials.html">AWS documentation</a>.</p><pre>@Configuration<br>public class MyConfiguration {<br>  @Bean<br>  public SqsAsyncClient sqsAsyncClient() {<br>    return SqsAsyncClient.<em>builder</em>()<br>      .region(Region.<em>US_WEST_1</em>) // replace this with the SQS region<br>      .credentialsProvider(StaticCredentialsProvider.<em>create</em>(<br>        new AwsCredentials() {<br>           @Override<br>            public String accessKeyId() {<br>                return &quot;{accessKeyHere}&quot;;<br>             }</pre><pre>            @Override<br>            public String secretAccessKey() {<br>                return &quot;{secretKeyHere}&quot;;<br>            }<br>        }<br>      ))<br>      .build();<br>   }<br>}</pre><p>3. Create a message listener that will be used to consume messages, replacing the URL with your own queue’s URL.</p><pre>@Component<br>public class MyMessageListener {<br>    @QueueListener(&quot;{queueUrlHere}&quot;)<br>    public void listen(@Payload String payload) {<br>         // do something with the message here<br>    }<br>}</pre><p>4. Start the application.</p><p>5. Place a message onto the SQS queue using the AWS console or CLI, it should now invoke this method with the message payload.</p><h3>Getting started without an AWS account</h3><p>One thing I find really important for a development experience is being able to work on an application without needing to set up access to the plethora of systems that it interacts with. Theoretically, I should be able to go into the repo and run mvn spring-boot:run or gradle bootRun and be able to test some basic use cases.</p><p>To do this, we need to mock all of our external dependencies and a really good tool to mock the SQS queues is an in-memory implementation called <a href="https://github.com/softwaremill/elasticmq">ElasticMQ</a>.</p><p>This will show you how to create a Spring Boot app that will periodically send messages to an ElasticMQ queue and set up a message listener to consume this.</p><ol><li>Import the <a href="https://search.maven.org/artifact/com.jashmore/java-dynamic-sqs-listener-spring-starter/4.0.0/jar">Spring Starter</a> module:</li></ol><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.jashmore&lt;/groupId&gt;<br>  &lt;artifactId&gt;java-dynamic-sqs-listener-spring-starter&lt;/artifactId&gt;<br>  &lt;version&gt;4.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>2. Import the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/tree/4.x/util/elasticmq-sqs-client">ElasticMQ SQS Client</a> module. This is just a simple wrapper around the ElasticMQ server that exposes a SqsAsyncClient connected to this queue.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.jashmore&lt;/groupId&gt;<br>  &lt;artifactId&gt;elasticmq-sqs-client&lt;/artifactId&gt;<br>  &lt;version&gt;4.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>3. Create the ElasticMQ server with a single queue already setup for you. In this case it will create a queue called myQueueName for you when it starts up. See the ElasticMqAsyncClient for more configuration options.</p><pre>@Configuration<br>public class MyConfiguration {<br>    @Bean<br>    public SqsAsyncClient sqsAsyncClient() {<br>        return new ElasticMqAsyncClient(&quot;myQueueName&quot;);<br>    }<br>}</pre><p>4. Create a message listener that will listen to this queue.</p><pre>@Component<br>public class MessageListener {<br>    private static Logger log<br>         = LoggerFactory.getLogger(MessageListener.class);</pre><pre>    @QueueListener(&quot;myQueueName&quot;)<br>    public void listen(@Payload String payload) {<br>         log.info(&quot;Message received: {}&quot;, payload);<br>    }<br>}</pre><p>5. Create a scheduled task that will send messages to this queue periodically.</p><pre>@Component<br>@EnableScheduling<br>public class MessageScheduler {<br>  private final SqsAsyncClient sqsAsyncClient;</pre><pre>  @Autowired<br>  public MessageScheduler(SqsAsyncClient sqsAsyncClient) {<br>      this.sqsAsyncClient = sqsAsyncClient;<br>  }</pre><pre>  @Scheduled(fixedRate = 1_000)<br>  public void sendMessageToQueue() throws Exception {<br>    String queueUrl = sqsAsyncClient.getQueueUrl(builder -&gt;<br>              builder.queueName(&quot;myQueueName&quot;))<br>              .get()<br>              .queueUrl();</pre><pre>    sqsAsyncClient.sendMessage(builder -&gt; builder.queueUrl(queueUrl)<br>                .messageBody(&quot;hello world!&quot;));<br>  }<br>}</pre><p>6. Start the application, you should now have messages being sent to your queue every second.</p><p>You can see this full example in the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/tree/4.x/examples/spring-starter-minimal-example">Spring Starter Minimal Example</a> in the project’s repo.</p><h3>Using the Core Library with the Kotlin DSL</h3><p>In the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/releases/tag/v4.0.0">4.0</a> release, I added the ability to build a message listener container using a Kotlin DSL instead of building them using Java builders. If you want to see a full comparison, you can see an <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/v4.0.0/examples/core-example/src/main/java/com/jashmore/sqs/examples/ConcurrentBrokerExample.java">example</a> with a message listener using the core library or the equivalent <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/v4.0.0/examples/core-kotlin-example/src/main/kotlin/com/jashmore/sqs/examples/KotlinConcurrentBrokerExample.kt">example</a> using the core Kotlin DSL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6341df8b36c4e72d21c21c1e93ad8f7d/href">https://medium.com/media/6341df8b36c4e72d21c21c1e93ad8f7d/href</a></iframe><p>In this container above, we have a message listener that prefetches 10 to 20 messages and will process them at a concurrency rate that will randomly change every 10 seconds to be between 0 and 10.</p><h3>Writing Integration Tests</h3><p>As I feel it is important to include the testing side of a library, you can see a simple <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/tree/4.x/examples/spring-integration-test-example">example</a> here to write integration tests for this library. You can get more information in the <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/blob/4.x/doc/how-to-guides/spring/spring-how-to-write-integration-tests.md">Spring - How to write integration tests</a> documentation.</p><h3>Thanks!</h3><p>If you have questions, feature requests or bugs, <a href="https://github.com/JaidenAshmore/java-dynamic-sqs-listener/issues">create an issue</a> in the GitHub repo and I should be able to get back to you pretty quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4f10d291f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in Spring Boot Webflux]]></title>
            <link>https://medium.com/@jaidenashmore/jwt-authentication-in-spring-boot-webflux-6880c96247c7?source=rss-e3f876684ed0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6880c96247c7</guid>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Jaiden Ashmore]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 23:37:24 GMT</pubDate>
            <atom:updated>2020-04-18T23:37:24.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*d_7YQ1mMmCkuO2X-5BISsA.png" /></figure><p>Spring Security has always been a hurdle for me to maintain my interest in my personal projects. Once I have to figure out how to authenticate my users I use to get frustrated or bored and would go back to relaxing and playing games. While working on personal project I wanted to add JWT authentication to the user service so that other services could authenticate a request independently. To do this, I dug into the internals of Spring Security to learn how it worked and thought it would be a good topic to write about.</p><p>By the end of this article we will have a Spring Webflux service that can create accounts, login to these accounts and make authenticated requests as this user using JWT. There will be a lot of shortcuts, e.g. a Map of users instead of an actual database but those aspects can easily be extrapolated from this article.</p><h3>Initial project</h3><p><a href="https://start.spring.io/">Spring Initializr</a> was used with the following configurations:</p><ul><li><a href="https://kotlinlang.org/">Kotlin</a></li><li><a href="https://gradle.org/">Gradle</a></li><li><a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html">Spring Boot Webflux</a></li><li><a href="https://spring.io/projects/spring-security">Spring Security</a></li></ul><p>From here I created a really basic REST controller for doing signup, login and getting a user’s details. You can see the start of this service at the <a href="https://github.com/JaidenAshmore/spring-boot-webflux-jwt-authentication-example/tree/4d149ded77bec3da9ad269e2feb30e81d10d774e">spring-boot-webflux-jwt-authentication-example#4d149ded77bec3da9ad269e2feb30e81d10d774e</a> commit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad6e74a6a65ab96876bba6a30a8131d/href">https://medium.com/media/cad6e74a6a65ab96876bba6a30a8131d/href</a></iframe><h3>Hooking in Spring Security</h3><p>Spring Security provides the tools to easily authenticate and authorise user’s access to your application. Simply put it is just a sequence of filters that run before the Controller of your application to apply security logic, such as authenticating a user or blocking access completely. These filters are performed in a distinct order defined by the <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/config/src/main/java/org/springframework/security/config/web/server/SecurityWebFiltersOrder.java#L23">SecurityWebFiltersOrder</a>, for example, the process of authenticating the user (confirming that you are a valid user in the system) needs to be done before authorisation (confirming whether you have access to this resource).</p><p>These filters are set up via the <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java#L183">ServerHttpSecurity</a> which allows you to configure which filters you want to have. The following code gist is a simple security filter chain that allows all requests to pass into our controllers and disables some features that aren’t useful for our purely REST API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8223720ae102f0836e1bda3214e1f0cc/href">https://medium.com/media/8223720ae102f0836e1bda3214e1f0cc/href</a></iframe><p>If you dig into the Spring Security code, you can see that the <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java#L2392">ServerHttpSecurity#build(</a>) method is used to apply these filters to the SecurityWebFilterChain. I would recommend digging through this to get a stronger understanding of the internals.</p><p>If we analyse how basic authentication works we can figure out the three main components that will be applicable for our custom JWT Authentication:</p><ul><li><a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationConverter.java#L33"><strong>ServerAuthenticationConverter</strong></a>: this is used to convert the request to the authentication object. For example, in basic authentication it would read the Authorization header of the HTTP request and extract the username and password into an Authentication object for further processing.</li><li><a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/core/src/main/java/org/springframework/security/authentication/ReactiveAuthenticationManager.java#L29"><strong>ReactiveAuthenticationManager</strong></a>: this is used to determine if the provided Authentication can be authenticated. For example, it could take the username and password and check that it exists in the database and is the correct credentials.</li><li><a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java#L39"><strong>AuthenticationWebFilter</strong></a><strong>: </strong>filter used to take the request and apply all of the logic above. If the Authentication object can be authenticated, it will be added to the <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/core/src/main/java/org/springframework/security/core/context/ReactiveSecurityContextHolder.java#L27">ReactiveSecurityContextHolder</a> for usage by the subsequent <a href="https://github.com/spring-projects/spring-security/blob/5.3.0.RELEASE/web/src/main/java/org/springframework/security/web/server/authorization/AuthorizationWebFilter.java#L33">AuthorizationWebFilte</a>r which will determine whether they have access to the resource.</li></ul><h3>Creating a JWT on successful login</h3><p>The first thing we will do is update the login endpoint to generate a JWT on a successful login. For simplicity, we will use store the JWT in a cookie but there are better approaches from a security perspective. Take a look at <a href="https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/">The Ultimate Guide to handling JWT on frontend clients</a> for a real in-depth explanation on this topic.</p><p>We will use RSA, an asymmetric key algorithm, that will generate a private key for signing a new token and a public key very verify the token. This will allow us to share the public key to other microservices so that they can do their own authentication without needing to call this user service.</p><p>I am going to use <a href="https://github.com/jwtk/jjwt">JJWT</a> as the JWT library but any other equivalent library would do the job.</p><pre>implementation(&quot;io.jsonwebtoken:jjwt-api:0.11.1&quot;)<br>runtimeOnly(&quot;io.jsonwebtoken:jjwt-impl:0.11.1&quot;)<br>runtimeOnly(&quot;io.jsonwebtoken:jjwt-jackson:0.11.1&quot;)</pre><p>We can now create a basic JwtSigner class that can be used to generate a keypair on startup and allow it to create JWT tokens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e43977022903122c0e19ababbc01a0/href">https://medium.com/media/66e43977022903122c0e19ababbc01a0/href</a></iframe><p>Now when we successfully login we can use this JwtSigner to add a cookie to the response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d18b4430a329cb5fa07463e65c82eb1/href">https://medium.com/media/1d18b4430a329cb5fa07463e65c82eb1/href</a></iframe><h3>Authenticating the JWT</h3><p>Currently the user will be able to include the JWT token for each request due to the additional cookie but the current code doesn’t do anything about validating this. The next step is to hook into the Spring Security to make sure we authorise our protected requests against the JWT token.</p><p>We can apply this authentication by adding a <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/web/src/main/java/org/springframework/security/web/authentication/AuthenticationFilter.java#L39">AuthenticationWebFilter</a>into our filter chain. To get this to work we will need to tell the filter how to get the JWT token out of the request via a custom <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/web/src/main/java/org/springframework/security/web/server/authentication/ServerAuthenticationConverter.java#L33">ServerAuthenticationConvert</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccf1a5e1646d37220d23ccee28e662e9/href">https://medium.com/media/ccf1a5e1646d37220d23ccee28e662e9/href</a></iframe><p>What this function does it looks to see if there is any cookie with the name X-Auth and generates the Authentication object from it. I have used the JWT value as both the username and password as it stores both of these details.</p><p>The next step is to implement a <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/core/src/main/java/org/springframework/security/authentication/ReactiveAuthenticationManager.java#L29">ReactiveAuthenticationManager</a> which will be used to take this extracted Authentication and check that it is a valid user. This will need to parse the JWT and make sure that it is valid and not expired.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95673880fc4e0e23954142510869ab42/href">https://medium.com/media/95673880fc4e0e23954142510869ab42/href</a></iframe><p>This uses the JwtSigner that was created before to take the JWT and check that it is valid. The JJWT library handles cases like the token expiring so if the method does not throw a JwtException it is a valid token.</p><p>Now we need to build our AuthenticationWebFilter and add it to our chain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e449149927ef2969673991575fb7609/href">https://medium.com/media/9e449149927ef2969673991575fb7609/href</a></iframe><p>Now when we run the application, any request that does not have a valid JWT token will be rejected with a 401 response.</p><h3>Obtaining the user in our Controller</h3><p>The final step for this application is to get the Authentication object so we can use the current logged in user within our Controller. As Webflux does not allow for ThreadLocals it is stored in the context of the Mono instead as a SecurityContextobject. The <a href="https://github.com/spring-projects/spring-security/blob/5.3.1.RELEASE/core/src/main/java/org/springframework/security/core/context/ReactiveSecurityContextHolder.java#L32">ReactiveSecurityContextHolder</a> can be used to easily obtain this context but it would be nicer if this was automatically injected into the function signature of our REST endpoint.</p><p>To do this we can include the Principal into our method signature which is the UsernamePasswordAuthenticationToken that we can had created before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc0f2622f69a6fdb95622ec18e32d061/href">https://medium.com/media/cc0f2622f69a6fdb95622ec18e32d061/href</a></iframe><h3>What about testing?</h3><p>I hate these blog posts that show you a technique and then don’t show how you can write some tests for this. As unit tests should be easy to do yourself, I will show you an example of an integration test that signs a user up, logs it in and then gets its owner user details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680ad2d1498793f88d8da68ba195629a/href">https://medium.com/media/680ad2d1498793f88d8da68ba195629a/href</a></iframe><h3>What’s next?</h3><p>While this goes over the basics of JWT Authentication, there is a lot missing in this solution. For example:</p><ol><li>How do we allow refreshing of the JWT token before it expires?</li><li>How do other services authenticate the JWT?</li><li>As the token is being generated on startup, how would this work for a multi-node system?</li></ol><p>I am hoping to have follow up blog posts around this topics as I solve these in my own application.</p><p>If you are interested in the final state of the application, take a look at this repo’s <a href="https://github.com/JaidenAshmore/spring-boot-webflux-jwt-authentication-example/tree/7fa427b35f9636a4f1f87eaa73d4c7a5929434ff">commit</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6880c96247c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>