<?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 Afeef Razick on Medium]]></title>
        <description><![CDATA[Stories by Afeef Razick on Medium]]></description>
        <link>https://medium.com/@afeefrazickamir?source=rss-82928ac48e88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wROHucQExyEKdMTbtQREFA.jpeg</url>
            <title>Stories by Afeef Razick on Medium</title>
            <link>https://medium.com/@afeefrazickamir?source=rss-82928ac48e88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:10:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afeefrazickamir/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Authorization Server — Customized login page]]></title>
            <link>https://medium.com/@afeefrazickamir/spring-authorization-server-customized-login-page-589df124d26f?source=rss-82928ac48e88------2</link>
            <guid isPermaLink="false">https://medium.com/p/589df124d26f</guid>
            <dc:creator><![CDATA[Afeef Razick]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 15:28:34 GMT</pubDate>
            <atom:updated>2025-01-19T15:28:34.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Authorization Server — Customized login page</h3><h4>This is Part 4 of ‘Spring Authorization Server : 0–90’ series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaP8Q3nfUUnp56Sn2S-Kvg.jpeg" /><figcaption>For an AI generated image, this is pretty good imo</figcaption></figure><p>If you haven’t read <a href="https://medium.com/@afeefrazickamir/spring-authorization-server-0-90-03d996d5c5a7">Part 1</a>, I recommend starting there, as this guide is part of a series and builds upon the concepts introduced earlier (Part 2 and 3 is not required for this part).</p><p>You can find all the code for this series in this <a href="https://github.com/AfeefRazick/spring-authorization-server-guide">Github repo</a>. The branch for this guide is part-4/customized-login-page</p><p>So far, we’ve been using Spring’s default login page, and it looks pretty bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*hjiKcwYJ2f9Lvbv86PoaWg.png" /></figure><p>In this guide, I’ll customize the login page for form login (username-password) and OAuth2 login (social providers like Google). If your auth server doesn’t need one of these, feel free to skip it.</p><p>Since we only need a single page and the login page isn’t complex, we’ll use Thymeleaf — it’s more than enough. Let’s start by adding the Thymeleaf dependency to the auth server.</p><pre>// build.gradle<br>dependencies {<br>    // ... other dependencies<br>    implementation &#39;org.springframework.boot:spring-boot-starter-thymeleaf&#39;<br>}</pre><p>I’m no designer, so I grabbed a design from online. Source: <a href="https://www.justinmind.com/blog/inspiring-website-login-form-pages/">https://www.justinmind.com/blog/inspiring-website-login-form-pages/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*FOY6aoBex6LOCT6SNVXJJw.png" /></figure><p>After running it through <a href="https://v0.dev/">v0</a> and making a few tweaks in the v0 chat, it’s close enough to the original design. This works for me since getting it exact isn’t a priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJHq1RwJAF6FPW2xqcRSmA.png" /></figure><p>Let’s create the login.html page in resources/templates/. I’ve stripped out all the styles, SVGs, and unrelated functionality. If you want the complete code, you can find it on the <a href="https://github.com/AfeefRazick/spring-authorization-server-guide">GitHub repo</a>.</p><p>OAuth2 login providers are simple links following the URL format /oauth2/authorization/{registrationId}, while the form login posts to the /login endpoint with username and password as form data fields.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Welcome Back! - Ticketed&lt;/title&gt;<br>    &lt;style&gt;<br>        /* ... all styles */<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div class=&quot;split-container&quot;&gt;<br>    &lt;div class=&quot;left-side&quot;&gt;<br>        &lt;div class=&quot;logo&quot;&gt;Spring Authorization Server&lt;/div&gt;<br>        &lt;div class=&quot;hero-text&quot;&gt;<br>            Go from 0-90,&lt;br&gt;<br>            Your almost at prod!<br>        &lt;/div&gt;<br>        &lt;img class=&quot;mountains&quot; th:src=&quot;@{/images/mountains.jpg}&quot; alt=&quot;mountains&quot;/&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;right-side&quot;&gt;<br>        &lt;div class=&quot;login-container&quot;&gt;<br>            &lt;div class=&quot;login-header&quot;&gt;<br>                &lt;h1&gt;Welcome Back!&lt;/h1&gt;<br>                &lt;p&gt;Continue with Google or enter your details.&lt;/p&gt;<br>            &lt;/div&gt;<br>            &lt;a href=&quot;/oauth2/authorization/google&quot; role=&quot;link&quot; class=&quot;google-sign-in&quot;&gt;<br>               Login with Google<br>            &lt;/a&gt;<br>            &lt;form th:action=&quot;@{/login}&quot; method=&quot;post&quot;&gt;<br>                &lt;div class=&quot;form-group&quot;&gt;<br>                    &lt;label for=&quot;username&quot;&gt;Email&lt;/label&gt;<br>                    &lt;input<br>                            type=&quot;email&quot;<br>                            id=&quot;username&quot;<br>                            name=&quot;username&quot;<br>                            placeholder=&quot;example@gmail.com&quot;<br>                            required<br>                    &gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;form-group&quot;&gt;<br>                    &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;<br>                    &lt;div class=&quot;password-container&quot;&gt;<br>                        &lt;input<br>                                type=&quot;password&quot;<br>                                id=&quot;password&quot;<br>                                name=&quot;password&quot;<br>                                placeholder=&quot;••••••&quot;<br>                                required<br>                        &gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;button type=&quot;submit&quot; class=&quot;login-button&quot;&gt;Login&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now that we have our template, let’s add a controller method to serve this Thymeleaf template.</p><pre>// AuthController.java<br>@Controller<br>public class AuthController {<br> <br>    @GetMapping(&quot;/login&quot;)<br>    public String login() {<br>        return &quot;login&quot;;<br>    }<br>}</pre><p>Previously, we used Customizer.withDefaults() when setting up formLogin and oauth2Login without any customizations. To make Spring use our custom login template instead of the default, we need to specify the login page path. We’ll also allow unauthenticated access to any static resources, such as CSS and images, that the login page references.</p><pre>// SecurityConfig.java<br>@Bean<br>@Order(2) // security filter chain for the rest of your application and any custom endpoints you may have<br>public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {<br>    // @formatter:off<br>    http<br>            .cors(Customizer.withDefaults())<br>            .formLogin(formLogin -&gt; formLogin.loginPage(&quot;/login&quot;).permitAll()) // Enable form login<br>            .oauth2Login(oauth2Login -&gt; oauth2Login.loginPage(&quot;/login&quot;).permitAll()) // Enable oauth2 federated identity login<br>            .authorizeHttpRequests(authorize -&gt;<br>                    authorize<br>                            .requestMatchers(&quot;/webjars/**&quot;, &quot;/images/**&quot;, &quot;/css/**&quot;, &quot;/assets/**&quot;, &quot;/favicon.ico&quot;).permitAll()<br>                            .anyRequest().authenticated()<br>            );<br>    // @formatter:on<br> <br>    return http.build();<br>}</pre><p>If we rerun the auth server, we should see the new login page, and both login methods should work as before.</p><p>To improve the experience, we can handle error states. For example, if invalid credentials are entered, Spring adds the error query parameter to the URL. We can use this to display an appropriate error message to the user.</p><pre>&lt;!-- login.html--&gt;<br>&lt;div th:if=&quot;${param.error}&quot; class=&quot;alert-error&quot;&gt;<br>    &lt;!-- an svg is here --&gt;<br>    The combination of email and password is incorrect!<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*VGo8BjS4AeH0A2WhdX5_iQ.png" /></figure><p>With that, we’ve successfully customized our login page — yep, it’s as easy as that!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=589df124d26f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Authorization Server — Social login (with customized jwt)]]></title>
            <link>https://medium.com/@afeefrazickamir/spring-authorization-server-social-login-with-customized-jwt-4e7c65e35194?source=rss-82928ac48e88------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e7c65e35194</guid>
            <dc:creator><![CDATA[Afeef Razick]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 12:40:05 GMT</pubDate>
            <atom:updated>2025-01-18T12:40:05.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Authorization Server — Social login (with customized jwt)</h3><h4>This is Part 3 of ‘Spring Authorization Server : 0–90’ series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaP8Q3nfUUnp56Sn2S-Kvg.jpeg" /><figcaption>For an AI generated image, this is pretty good imo</figcaption></figure><p>If you haven’t read <a href="https://medium.com/@afeefrazickamir/spring-authorization-server-0-90-03d996d5c5a7">Part 1</a>, I recommend starting there, as this guide is part of a series and builds upon the concepts introduced earlier (Part 2 is not required).</p><p>You can find all the code for this series in this <a href="https://github.com/AfeefRazick/spring-authorization-server-guide">Github repo</a>. The branch for this guide is part-3/oauth2-social-login</p><p>So far, users log in by entering their username and password, where the username is typically a unique email address. However, many users prefer social login for email-based identity verification.</p><p>To enable social login in Spring Authorization Server, start by setting up the authorization server as described in Part 1. If you don’t want to support username-password login, you can skip form login. (Omit .formLogin() in security filter chain)</p><p>For this guide, we’ll use Google as the OAuth2 provider since it’s the most popular choice.</p><p>First, register your application as an OAuth2 client with the provider. This involves obtaining a client ID and secret pair. The process varies by provider, so I won’t go into detail. For Google, you can refer to these resources:</p><ul><li><a href="https://developers.google.com/identity/protocols/oauth2">https://developers.google.com/identity/protocols/oauth2</a>,</li><li><a href="https://support.google.com/cloud/answer/6158849?hl=en">https://support.google.com/cloud/answer/6158849?hl=en</a></li></ul><p>It’s crucial to add the authorization server’s redirect URL to our OAuth2 provider. If you’ve been following along, in Part 1, we configured the authorization server to run on 127.0.0.1. We can include this URL in the list of authorized redirect URIs on Google.</p><p>As mentioned earlier, the default redirect URI format used by Spring Authorization Server is /login/oauth2/code/{registrationId}, so we need to add http://127.0.0.1:9000/login/oauth2/code/google as the redirect URI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*VCYLRrqvNiswhGJBaG5bzQ.png" /></figure><p>Similar to how our SPA Web App and API Gateway act as OAuth2 clients to our authorization server, our authorization server will now function as an OAuth2 client to an external authorization provider — in this case, Google.</p><p>To enable this functionality, we need to add the OAuth2 client dependency to our authorization server.</p><pre>// build.gradle<br>dependencies {<br>    // ... other dependencies<br>    implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-client&#39;<br>}</pre><p>Next, we can add the OAuth2 client configuration to our application.yml. Google requires minimal configuration since it is included in the <a href="https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/oauth2/client/CommonOAuth2Provider.java">CommonOauth2Provider</a> enum provided by Spring Security.</p><p>For other OAuth2 providers, you may need to specify additional properties. Refer to this <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/login/core.html#oauth2login-boot-property-mappings">list of properties</a> for details. Replace the client Id and secret with the ones you obtained (Ofcourse, the keys below wont work as I have deleted them).</p><pre># application.yml (auth-server)<br>spring:<br>  # ... other configuration<br>  security:<br>    oauth2:<br>      client:<br>        registration:<br>          google:<br>            clientId: 432843073336-25dti6760u9drsjee2rmuho3au9ph90n.apps.googleusercontent.com # replace with your client id<br>            clientSecret: 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 # replace with your client secret<br>            authorization-grant-type: authorization_code</pre><p>Next, we need to enable OAuth2 login in our default security filter chain.</p><pre>// SecurityConfig.java<br>@Bean<br>@Order(2)<br>public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {<br>    // @formatter:off<br>    http<br>            // ... other configuration<br>            .oauth2Login(Customizer.withDefaults()) // Enable oauth2 federated identity login<br>    // @formatter:on<br> <br>    return http.build();<br>}</pre><p>Let&#39;s add another user to our user store with a username matching the email we’ll use to log in. This ensures a user account already exists for that email (Make sure you replace my email with the email you will use to login).</p><p>Alternatively, you can create a new account when a user logs in for the first time by implementing an <a href="https://docs.spring.io/spring-authorization-server/reference/guides/how-to-social-login.html#advanced-use-cases-capture-users">AuthenticationSuccessHandler</a>.</p><pre>// SecurityConfig.java<br>@Bean<br>UserDetailsService users() {<br>    // ... other users<br> <br>    // @formatter:off<br>    UserDetails me = User.builder()<br>            .username(&quot;afeefrazickamir@gmail.com&quot;)<br>            .password(&quot;pass&quot;)<br>            .passwordEncoder(passwordEncoder()::encode)<br>            .roles(&quot;USER&quot;, &quot;ADMIN&quot;)<br>            .build();<br>    // @formatter:on<br> <br>    return new InMemoryUserDetailsManager(user, me);<br>}</pre><p>Next, let’s revisit the OAuth2 JWT token customizer we implemented earlier. For form login, the JWT context uses a UserDetails principal stored in our repository. However, for OAuth2 social login, the JWT context contains information from the external authorization provider—in this case, Google.</p><p>To ensure the JWTs issued and used across our application have a consistent structure, regardless of the authorization method, we’ll make some small tweaks.</p><pre>// Oauth2AccessTokenCustomizer.java<br>@RequiredArgsConstructor<br>@Component<br>public class Oauth2AccessTokenCustomizer implements OAuth2TokenCustomizer&lt;JwtEncodingContext&gt; {<br> <br>    // Here we are using the in memory user details service, but this could be any user service/repository<br>    private final UserDetailsService userService;<br> <br>    @Override<br>    public void customize(JwtEncodingContext context) {<br>        if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {<br>            context.getClaims().claims(claims -&gt; {<br>                Object principal = context.getPrincipal().getPrincipal();<br> <br>                // STARTS HERE<br>                User user = null;<br> <br>                if (principal instanceof UserDetails) { // form login<br>                    user = (User) principal;<br>                } else if (principal instanceof DefaultOidcUser oidcUser) { // oauth2 login<br>                    // fetch user by email to obtain User object when principal is not already a User object<br>                    String email = oidcUser.getEmail();<br>                    user = (User) userService.loadUserByUsername(email);<br>                }<br> <br>                if (user == null) return;<br>                // ENDS HERE<br> <br>                Set&lt;String&gt; roles = AuthorityUtils.authorityListToSet(user.getAuthorities()).stream().map(c -&gt; c.replaceFirst(&quot;^ROLE_&quot;, &quot;&quot;)).collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));<br>                claims.put(&quot;roles&quot;, roles);<br> <br>                // I have only added the roles to the JWT here as I am using the limited fields<br>                // on the UserDetails object, but you can add many other important fields by<br>                // using your applications User class (as shown below)<br> <br>                // claims.put(&quot;email&quot;, user.getEmail());<br>                // claims.put(&quot;sub&quot;, user.getId());<br>            });<br>        }<br>    }<br>}</pre><p>Since the user details service bean from Part 1 is already defined in the security configuration, we need to avoid a cyclic dependency error. To do so, we’ll remove the injection of the Oauth2AccessTokenCustomizer bean and instantiate it manually.</p><pre>// SecurityConfig.java<br>@Bean<br>OAuth2TokenGenerator&lt;OAuth2Token&gt; tokenGenerator(JWKSource&lt;SecurityContext&gt; jwkSource) {<br>    JwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);<br>    JwtGenerator jwtAccessTokenGenerator = new JwtGenerator(jwtEncoder);<br>    jwtAccessTokenGenerator.setJwtCustomizer(new Oauth2AccessTokenCustomizer(users())); // instantiate manually to prevent cyclic bean dependency<br> <br>    return new DelegatingOAuth2TokenGenerator(jwtAccessTokenGenerator);<br>}</pre><p>Now, if we rerun all our applications and navigate to localhost:8080/books, we should be redirected to the login page on the auth server, where Google should appear as an OAuth2 login option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*U1YkWryjRyauc_JpXq4d6Q.png" /></figure><p>Upon clicking “Login”, we should be able to authorize via the authorization provider and finally be redirected back to the books page. If you encounter an error, check the error message, your credentials, or the redirect URI in the console, as one of them may be incorrect.</p><p>Now that we have the JWT displayed on the /books page, let&#39;s copy and paste it into <a href="https://ritviknag.com/markdown-to-medium/jwt.io">jwt.io</a>. To demonstrate the role of the JWT customizer in these different login methods, restart the servers and also log in using username-password. When we paste the JWT into jwt.io, we can see that the roles we set are present in both tokens. However, the sub field, which is set by default using the principal name, differs because of the variation in the JWT context.</p><ul><li>Google OAuth2 Login JWT Payload</li></ul><pre>{<br>  &quot;sub&quot;: &quot;113406613444429860426&quot;,<br>  &quot;aud&quot;: &quot;gateway-client&quot;,<br>  &quot;nbf&quot;: 1736841840,<br>  &quot;scope&quot;: [<br>    &quot;openid&quot;,<br>    &quot;profile&quot;,<br>    &quot;email&quot;<br>  ],<br>  &quot;roles&quot;: [<br>    &quot;ADMIN&quot;,<br>    &quot;USER&quot;<br>  ],<br>  &quot;iss&quot;: &quot;http://127.0.0.1:9000&quot;,<br>  &quot;exp&quot;: 1736842140,<br>  &quot;iat&quot;: 1736841840,<br>  &quot;jti&quot;: &quot;d272d8a5-17a3-46c5-ba9f-6815d2c97c64&quot;<br>}</pre><ul><li>Username-Password Login JWT Payload</li></ul><pre>{<br>  &quot;sub&quot;: &quot;afeefrazickamir@gmail.com&quot;,<br>  &quot;aud&quot;: &quot;gateway-client&quot;,<br>  &quot;nbf&quot;: 1736841765,<br>  &quot;scope&quot;: [<br>    &quot;openid&quot;,<br>    &quot;profile&quot;,<br>    &quot;email&quot;<br>  ],<br>  &quot;roles&quot;: [<br>    &quot;ADMIN&quot;,<br>    &quot;USER&quot;<br>  ],<br>  &quot;iss&quot;: &quot;http://127.0.0.1:9000&quot;,<br>  &quot;exp&quot;: 1736842065,<br>  &quot;iat&quot;: 1736841765,<br>  &quot;jti&quot;: &quot;7113f1fa-34f5-4e0b-aa63-b4cde40ed180&quot;<br>}</pre><p>Therefore, to maintain JWT consistency, we need to set such fields using values from the user repository.</p><p>Our login page doesn’t look too great, though. In <a href="https://ritviknag.com/markdown-to-medium/part4link">Part 4</a>, we’ll cover customizing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7c65e35194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Authorization Server — Public Client PKCE Authorization code flow (with refresh tokens)]]></title>
            <link>https://medium.com/@afeefrazickamir/spring-authorization-server-public-client-pkce-authorization-code-flow-with-refresh-tokens-ac2763080898?source=rss-82928ac48e88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2763080898</guid>
            <dc:creator><![CDATA[Afeef Razick]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 12:39:59 GMT</pubDate>
            <atom:updated>2025-01-18T12:39:59.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Authorization Server — Public Client PKCE Authorization code flow (with refresh tokens)</h3><h4>This is Part 2 of ‘Spring Authorization Server : 0–90’ series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaP8Q3nfUUnp56Sn2S-Kvg.jpeg" /><figcaption>For an AI generated image, this is pretty good imo</figcaption></figure><p>If you haven’t read <a href="https://medium.com/@afeefrazickamir/spring-authorization-server-0-90-03d996d5c5a7">Part 1</a>, I recommend starting there, as this guide is part of a series and builds upon the concepts introduced earlier.</p><p>You can find all the code for this series in this <a href="https://github.com/AfeefRazick/spring-authorization-server-guide">Github repo</a>. The branch for this guide is part-2/public-client-pkce-auth-code.</p><p>While <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce">PKCE</a>, is a recommendation in the current OAuth 2.0 standard, it becomes a requirement under the OAuth 2.1 specification.</p><p>As explained in Part 1, this section will cover configuring PKCE for public clients, as the client<em>secret</em>basic authentication method is not secure for such clients.</p><p>Although it is generally not recommended for public clients to participate in the OAuth2 flow, obtaining an access token in the browser is permitted by Spring Authorization Server and other implementations of the RFC specification. This allowance is based on the expectation that access tokens are designed to have short lifespans.</p><p>Although this is the case, requiring users to log in every 5 minutes is not user-friendly. To address this, we need a way to silently refresh the access token without user intervention.</p><p>Some interesting solutions exist, such as those implemented by frontend libraries like oidc-client-ts. These libraries use an iframe to perform silent token refreshes. Instead of relying on a refresh token, the iframe executes the authorization code flow by redirecting to the authorization server. The existing session (via session cookies) on the auth server is used to issue a new access token without requiring the user to log in again.</p><p>This solution once again requires the authorization server to be on the same domain as the client. If they are not, there are workarounds, but they introduce increased security vulnerabilities. For more details, you can refer to this <a href="https://stackoverflow.com/questions/72026554/silent-renew-doesnt-work-on-spring-authorization-server-and-react-client">Stack Overflow discussion</a>.</p><p>Ultimately, we must resort to allowing the SPA to obtain a refresh token (a feature enabled by the Spring team in 2024 — <a href="https://github.com/spring-projects/spring-authorization-server/pull/1432">here is the PR</a>). However, storing the refresh token in local storage or session storage is not secure and is strongly discouraged. The impact of a stolen refresh token can be far more detrimental due to its longer lifespan.</p><p>To mitigate these risks, techniques such as rotating refresh tokens — where a new refresh token is issued with each refresh request — can be implemented. This approach limits the potential damage of a stolen refresh token by invalidating old tokens upon use.</p><p>Lets get started. First lets configure CORS to allow requests from the public client to the authorization server.</p><pre>// SecurityConfig.java<br>private final static String PUBLIC_CLIENT_HOST_URL = &quot;http://localhost:5173&quot;;<br> <br>@Bean<br>CorsConfigurationSource corsConfigurationSource() {<br>    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>    CorsConfiguration config = new CorsConfiguration();<br>    config.addAllowedOrigin(PUBLIC_CLIENT_HOST_URL);<br>    config.addAllowedHeader(&quot;*&quot;);<br>    config.addAllowedMethod(&quot;*&quot;);<br>    config.setAllowCredentials(true);<br>    source.registerCorsConfiguration(&quot;/**&quot;, config);<br>    return source;<br>}</pre><p>Ensure CORS is enabled in both security filter chains to apply the default CORS configuration.</p><pre>// SecurityConfig.java<br>http<br>      // ... other configuration<br>      .cors(Customizer.withDefaults())</pre><p>Add the OAuth2 public client to the RegisteredClientRepository. Ensure the authentication method is NONE and PKCE is enabled.</p><pre>// SecurityConfig.java<br> <br>private final static String PUBLICCLIENTID = &quot;public-client&quot;;<br> <br>// @formatter:off<br>RegisteredClient publicWebClient = RegisteredClient<br>        .withId(UUID.randomUUID().toString())<br>        .clientId(PUBLICCLIENTID)<br>        .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) // authentication method set to &#39;NONE&#39;<br>        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)<br>        .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)<br>        .redirectUri(PUBLICCLIENT_HOSTURL + &quot;/callback&quot;)<br>        .postLogoutRedirectUri(PUBLICCLIENT_HOSTURL + &quot;/logout&quot;)<br>        .scope(OidcScopes.OPENID)<br>        .scope(OidcScopes.PROFILE)<br>        .scope(OidcScopes.EMAIL)<br>        .clientSettings(ClientSettings.builder().requireProofKey(true).build()) // enable PKCE<br>        .build();<br>// @formatter:on<br> <br>return new InMemoryRegisteredClientRepository(webClient, publicWebClient);</pre><p>With this setup, our SPA can now obtain access tokens via the authorization code flow. Next, we need to enable the SPA to obtain refresh tokens.</p><p>Spring provides a default implementation of the <a href="https://github.com/spring-projects/spring-authorization-server/blob/main/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2RefreshTokenGenerator.java">OAuth2RefreshTokenGenerator</a>. However, this implementation includes a condition that prevents issuing refresh tokens to public clients (when the authentication method is null).</p><p>To address this, we can define a custom implementation of OAuth2RefreshTokenGenerator, omitting the restriction on issuing refresh tokens to public clients.</p><pre>// OAuth2PublicClientRefreshTokenGenerator.java<br>public class OAuth2PublicClientRefreshTokenGenerator implements OAuth2TokenGenerator&lt;OAuth2RefreshToken&gt; {<br> <br>    private final StringKeyGenerator refreshTokenGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);<br> <br>    @Nullable<br>    @Override<br>    public OAuth2RefreshToken generate(OAuth2TokenContext context) {<br>        if (!OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {<br>            return null;<br>        }<br> <br>        Instant issuedAt = Instant.now();<br>        Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive());<br>        return new OAuth2RefreshToken(this.refreshTokenGenerator.generateKey(), issuedAt, expiresAt);<br>    }<br>}</pre><p>Next, we need to add our custom refresh token generator to the DelegatingOAuth2TokenGenerator.</p><pre>// SecurityConfig.java<br>@Bean<br>OAuth2TokenGenerator&lt;OAuth2Token&gt; tokenGenerator(JWKSource&lt;SecurityContext&gt; jwkSource) {<br>    JwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);<br>    JwtGenerator jwtAccessTokenGenerator = new JwtGenerator(jwtEncoder);<br>    jwtAccessTokenGenerator.setJwtCustomizer(oauth2AccessTokenCustomizer); // jwt customizer from part 1 (optional)<br> <br>    return new DelegatingOAuth2TokenGenerator(<br>                      jwtAccessTokenGenerator,<br>                      new OAuth2PublicClientRefreshTokenGenerator() // add customized refresh token generator<br>    ); <br>}</pre><p>With this, our public client should now be able to receive refresh tokens.</p><p>To test this, let’s set up a SPA web app as the public client. The <a href="https://github.com/authts/oidc-client-ts">oidc-client-ts</a> library is a popular, framework-agnostic OAuth2 library for JS/TS projects. Since React is one of the most widely used frontend frameworks, I will use it for this example. For better integration, we’ll use <a href="https://github.com/authts/react-oidc-context">react-oidc-context</a>, a wrapper around oidc-client-ts that simplifies managing authentication state and lifecycle.</p><p>I’ll follow the <a href="https://github.com/authts/react-oidc-context/blob/main/README.md">Getting Started</a> guide provided by them.</p><p>First, let’s install the necessary dependencies:</p><pre>npm install oidc-client-ts react-oidc-context</pre><p>Next, let’s add our OIDC configuration and the AuthProvider to main.tsx. This will set up the authentication context for our application:</p><pre>// main.tsx<br>const CLIENT_ID = &quot;public-client&quot;;<br>const AUTHSERVERURL = &quot;http://127.0.0.1:9000&quot;;<br>const HOST_URL = window.location.origin;<br> <br>const oidcConfig: UserManagerSettings = {<br>  authority: AUTHSERVERURL,<br>  clientid: CLIENTID,<br>  redirecturi: HOSTURL + &quot;/callback&quot;,<br>  response_type: &quot;code&quot;,<br>  scope: &quot;openid profile email&quot;,<br>};<br> <br>createRoot(document.getElementById(&quot;root&quot;)!).render(<br>  &lt;StrictMode&gt;<br>    &lt;AuthProvider {...oidcConfig}&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/StrictMode&gt;,<br>);</pre><p>Next, let&#39;s add some lifecycle methods to App.tsx.</p><pre>// App.tsx<br>import { useAuth } from &quot;react-oidc-context&quot;;<br> <br>function App() {<br>  const auth = useAuth();<br> <br>  switch (auth.activeNavigator) {<br>    case &quot;signinSilent&quot;:<br>      return &lt;div&gt;Signing you in...&lt;/div&gt;;<br>    case &quot;signoutRedirect&quot;:<br>      return &lt;div&gt;Signing you out...&lt;/div&gt;;<br>  }<br> <br>  if (auth.isLoading) {<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br> <br>  if (auth.error) {<br>    return &lt;div&gt;Oops... {auth.error.message}&lt;/div&gt;;<br>  }<br> <br>  if (auth.isAuthenticated) {<br>    return (<br>      &lt;div&gt;<br>        Hello {auth.user?.profile.sub}{&quot; &quot;}<br>        &lt;button onClick={() =&gt; void auth.removeUser()}&gt;Log out&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br> <br>  return &lt;button onClick={() =&gt; void auth.signinRedirect()}&gt;Log in&lt;/button&gt;;<br>}<br> <br>export default App;</pre><p>When we run our React app and click the login button, we&#39;re redirected to the auth server login page. After entering our credentials, we return to the callback page. If you check the network tab, you&#39;ll see that the /oauth2/token endpoint is hit, where the SPA sends the authorization code as a parameter. The response includes a refresh token.</p><figure><img alt="Browser Network tab of oauth2/token endpoint response of json type with feilds access_token, refresh_token, scope, id_token, token_type, expires_in" src="https://cdn-images-1.medium.com/max/635/1*02sd5qV1OsoH1OkcOKWa5A.png" /></figure><p>However, if we attempt to obtain an access token by hitting the /oauth2/token endpoint and providing the refresh token, the request will fail, and we’ll be redirected to /login on the auth server. The oidc-client-ts library, when automaticSilentRenew is set to true, will attempt to silently renew the token 1 minute before the access token expires. By default, the access token&#39;s time-to-live is 5 minutes. To observe this behavior, we&#39;ll reduce the accessTokenTimeToLive to about 70 seconds in the token settings of the auth server.</p><pre>// SecurityConfig.java<br>RegisteredClient publicWebClient = RegisteredClient<br>        // ... other configuration<br>        .tokenSettings(<br>                TokenSettings.builder()<br>                        .accessTokenTimeToLive(Duration.ofSeconds(70))<br>                        .build()<br>        )</pre><p>You can also test this via Postman or cURL to confirm. (Be sure to replace the relevant values, such as authserverurl, clientID, and refresh_token, with your own.)</p><pre>curl --location &#39;http://127.0.0.1:9000/oauth2/token&#39; \<br>--header &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br>--header &#39;Cookie: JSESSIONID=BE95D161C4EB1F5D45FEAE1AE5081643&#39; \<br>--data-urlencode &#39;granttype=refreshtoken&#39; \<br>--data-urlencode &#39;client_id=public-client&#39; \<br>--data-urlencode &#39;refresh_token=SInTDYU8XZcTQtFyQ5LzREXRTFG3f9m85ybguc71WgeJ10akXnht2JXS3gJMEecVwGqKPctFSiOhUlka7Dl-uRhRR8Tfb1ElKipyhhlEftDghI8Dys5FXPzGgVJB9pRt&#39;</pre><p>This is because, although we have configured our authorization server to issue a refresh token to a public client, the default behavior of the Spring Authorization Server is to reject a token refresh attempt from a public client. An access token cannot be refreshed via a refresh token when the authentication_method is set to NONE. In this case, a public client can only obtain a new access token by performing the authorization code flow again.</p><p>If you’re familiar with Spring Security architecture, you’ll know that there is one <a href="https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html#servlet-authentication-providermanager">authentication manager</a> per filter chain. This authentication manager can have a list of authentication converters and providers, where the authentication converters run first to extract an authentication token from the HTTP servlet request, and the providers then verify this token.</p><p>By default, Spring Security provides a <a href="https://github.com/spring-projects/spring-authorization-server/blob/main/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverter.java">PublicClientAuthenticationConverter</a> and a <a href="https://github.com/spring-projects/spring-authorization-server/blob/main/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProvider.java">PublicClientAuthenticationProvider</a>. These implementations allow a public client to obtain an access token via the PKCE authorization code flow. However, they do not allow refresh tokens to be used for generating access tokens for public clients (ClientAuthenticationMethod.NONE). Therefore, we will need to provide additional implementations of the converter and provider to enable this behavior. I will use the existing implementations mentioned above and adjust them to support this functionality.</p><p>For the converter, we’ll adapt it for the refresh token grant type instead of the authorization code flow, which also means removing the PKCE requirement.</p><pre>// PublicClientRefreshTokenAuthenticationConverter.java<br>public class PublicClientRefreshTokenAuthenticationConverter implements AuthenticationConverter {<br> <br>    @Nullable<br>    @Override<br>    public Authentication convert(HttpServletRequest request) {<br>        // implementation is taken from PublicClientAuthenticationConverter<br>        // ---&gt; removed the check for grant type being AUTHORIZATION_CODE<br>        // ---&gt; removed the PKCE requirement<br>        // ---&gt; added a check to verify if the token request is a refresh token request<br>        // ---&gt; added a check to verify that the token request has no client_secret (ensure no authentication method)<br><br>        // grant_type (REQUIRED)<br>        String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);<br>        if (!AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(grantType)) {<br>            return null;<br>        }<br> <br>        // client_secret (Should not be present)<br>        String clientSecret = request.getParameter(OAuth2ParameterNames.CLIENT_SECRET);<br>        if (!StringUtils.hasText(clientSecret)) {<br>            return null;<br>        }<br><br>        MultiValueMap&lt;String, String&gt; parameters = &quot;GET&quot;.equals(request.getMethod()) ? getQueryParameters(request) : getFormParameters(request);<br> <br>        // client_id (REQUIRED for public clients)<br>        String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID);<br>        if (!StringUtils.hasText(clientId) || parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {<br>            throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);<br>        }<br> <br>        parameters.remove(OAuth2ParameterNames.CLIENT_ID);<br> <br>        Map&lt;String, Object&gt; additionalParameters = new HashMap&lt;&gt;();<br>        parameters.forEach((key, value) -&gt; additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0])));<br> <br>        return new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.NONE, null, additionalParameters);<br>    }<br> <br>    // helper method that can be found in OAuth2EndpointUtils<br>    static MultiValueMap&lt;String, String&gt; getQueryParameters(HttpServletRequest request) {<br>        Map&lt;String, String[]&gt; parameterMap = request.getParameterMap();<br>        MultiValueMap&lt;String, String&gt; parameters = new LinkedMultiValueMap&lt;&gt;();<br>        parameterMap.forEach((key, values) -&gt; {<br>            String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : &quot;&quot;;<br>            if (queryString.contains(key) &amp;&amp; values.length &gt; 0) {<br>                for (String value : values) {<br>                    parameters.add(key, value);<br>                }<br>            }<br>        });<br>        return parameters;<br>    }<br> <br>    // helper method that can be found in OAuth2EndpointUtils<br>    static MultiValueMap&lt;String, String&gt; getFormParameters(HttpServletRequest request) {<br>        Map&lt;String, String[]&gt; parameterMap = request.getParameterMap();<br>        MultiValueMap&lt;String, String&gt; parameters = new LinkedMultiValueMap&lt;&gt;();<br>        parameterMap.forEach((key, values) -&gt; {<br>            String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : &quot;&quot;;<br>            // If not query parameter then it&#39;s a form parameter<br>            if (!queryString.contains(key) &amp;&amp; values.length &gt; 0) {<br>                for (String value : values) {<br>                    parameters.add(key, value);<br>                }<br>            }<br>        });<br>        return parameters;<br>    }<br>}</pre><p>For the provider, the only adjustment needed is to remove the PKCE requirement.</p><pre>// PublicClientRefreshTokenAuthenticationProvider.java<br>@Slf4j<br>public final class PublicClientRefreshTokenAuthenticationProvider implements AuthenticationProvider {<br> <br>    private static final String ERROR_URI = &quot;https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1&quot;;<br> <br>    private final RegisteredClientRepository registeredClientRepository;<br> <br>    public PublicClientRefreshTokenAuthenticationProvider(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService) {<br>        Assert.notNull(registeredClientRepository, &quot;registeredClientRepository cannot be null&quot;);<br>        Assert.notNull(authorizationService, &quot;authorizationService cannot be null&quot;);<br>        this.registeredClientRepository = registeredClientRepository;<br>    }<br> <br>    @Override<br>    public Authentication authenticate(Authentication authentication) throws AuthenticationException {<br>        // implementation is taken from PublicClientAuthenticationProvider<br>        // ---&gt; removed the PKCE requirement<br> <br>        OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication;<br> <br>        if (!ClientAuthenticationMethod.NONE.equals(clientAuthentication.getClientAuthenticationMethod())) {<br>            return null;<br>        }<br> <br>        String clientId = clientAuthentication.getPrincipal().toString();<br>        RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(clientId);<br>        if (registeredClient == null) {<br>            throwInvalidClient(OAuth2ParameterNames.CLIENT_ID);<br>        }<br> <br>        log.trace(&quot;Retrieved registered client&quot;);<br> <br>        if (!registeredClient.getClientAuthenticationMethods().contains(clientAuthentication.getClientAuthenticationMethod())) {<br>            throwInvalidClient(&quot;authentication_method&quot;);<br>        }<br> <br>        log.trace(&quot;Validated client authentication parameters&quot;);<br> <br>        log.trace(&quot;Authenticated public client&quot;);<br> <br>        return new OAuth2ClientAuthenticationToken(registeredClient, clientAuthentication.getClientAuthenticationMethod(), null);<br>    }<br> <br>    @Override<br>    public boolean supports(Class&lt;?&gt; authentication) {<br>        return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication);<br>    }<br> <br>    private static void throwInvalidClient(String parameterName) {<br>        OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALIDCLIENT, &quot;Client authentication failed: &quot; + parameterName, ERRORURI);<br>        throw new OAuth2AuthenticationException(error);<br>    }<br>}</pre><p>Let’s add the converter and provider to our authorization server configuration within the authorization server security filter chain.</p><pre>// SecurityConfig.java<br>http<br>      // ... other configuration<br>      .with(authorizationServerConfigurer, authorizationServer -&gt;<br>              authorizationServer<br>                      // ... other configuration<br>                      .clientAuthentication(clientAuthenticationConfigurer -&gt;<br>                             clientAuthenticationConfigurer<br>                                     .authenticationConverter(new PublicClientRefreshTokenAuthenticationConverter())<br>                                     .authenticationProvider(<br>                                             new PublicClientRefreshTokenAuthenticationProvider(<br>                                                     registeredClientRepository(),<br>                                                     new InMemoryOAuth2AuthorizationService() // replace with your AuthorizationService implementation if you have one<br>                                             )<br>                                     ) <br>                      )<br>      )</pre><p>Now, restart the auth server, and you should be able to verify that calls to the /oauth2/token endpoint with the refresh token grant type are successful.</p><p>Earlier, we discussed how rotating refresh tokens on each refresh can mitigate security risks. We can achieve this by disabling the reuse of refresh tokens in the public-client&#39;s OAuth2 client token settings.</p><pre>// SecurityConfig.java<br>RegisteredClient publicWebClient = RegisteredClient<br>        // ... other configuration<br>        .tokenSettings(<br>                TokenSettings.builder()<br>                        .reuseRefreshTokens(false)<br>                        .build()<br>        )</pre><p>We’ve now achieved PKCE flow with refresh tokens. However, there are a few improvements we can make on the SPA. I won’t go into detail as it&#39;s outside the scope of this discussion.</p><ul><li>You can use onSigninCallback to remove the leftover parameters from the URL.</li><li>react-oidc-context provides an HOC, withAuth, which can be used to implement private routes.</li><li>Return the user to the page they were on (or attempting to access) before redirection: There are several ways, a simple and straightforward approach is to define the onBeforeSignin argument on the withAuth HOC to store the current pathname in local storage. Then, in onSigninCallback or on the callback page, you can retrieve and remove the pathname from local storage and navigate to it.</li></ul><p>As mentioned earlier, Spring Authorization Server is not primarily designed with this flow in mind, so some issues remain. While we’ve enabled support for both public and confidential clients, other areas of the OAuth2 spec, like token revocation, will require similar custom configurations. I hope this guide prepares you for any additional configurations you may need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2763080898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Authorization Server : 0–90]]></title>
            <link>https://medium.com/@afeefrazickamir/spring-authorization-server-0-90-03d996d5c5a7?source=rss-82928ac48e88------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d996d5c5a7</guid>
            <category><![CDATA[google-login]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Afeef Razick]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 12:23:22 GMT</pubDate>
            <atom:updated>2025-01-19T15:32:59.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Authorization Server : 0–90</h3><h4>You almost made it to prod!!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaP8Q3nfUUnp56Sn2S-Kvg.jpeg" /><figcaption>For an AI generated image, this is pretty good imo</figcaption></figure><p>This series is designed to take you 90% of the way with Spring Authorization Server, covering essential concepts and implementations. The remaining 10% largely involves moving in-memory stores to durable storage like a database, which is quite straight forward and so it will not be covered. The focus here is on mastering core Spring Authorization Server principles.</p><p>My motivation to write this series is the immense amount of time I had to invest in achieving certain aspects of this flow. Much of that time was spent due to some misunderstanding of the bigger picture, as most online guides focused only on specific subtopics and were not very useful beyond a tutorial level. Because of this, you may find this article lengthy and overly in-depth, but I promise to keep it as concise as possible.</p><p>Note: This is not a beginner’s guide. The content assumes familiarity with Spring and related technologies to maintain focus on the Spring Authorization Server.</p><ul><li><a href="https://medium.com/@afeefrazickamir/spring-authorization-server-0-90-03d996d5c5a7">Part 1 — Oauth2 Authorization Code Flow — Confidential Client</a></li><li><a href="https://medium.com/@afeefrazickamir/spring-authorization-server-public-client-pkce-authorization-code-flow-with-refresh-tokens-ac2763080898">Part 2 — PKCE Authorization code flow — Public Client (with refresh tokens)</a></li><li><a href="https://medium.com/@afeefrazickamir/spring-authorization-server-social-login-with-customized-jwt-4e7c65e35194">Part 3 — Social login (with customized jwt)</a></li><li><a href="https://medium.com/@afeefrazickamir/spring-authorization-server-customized-login-page-589df124d26f">Part 4 — Customized login page</a></li></ul><p>You can find all the code for this series in this Github repo. <a href="https://github.com/AfeefRazick/spring-authorization-server-guide">https://github.com/AfeefRazick/spring-authorization-server-guide</a></p><h3>Prerequisites</h3><p>This guide assumes you:</p><ul><li>Have a good understanding of Spring and how it works.</li><li>Are familiar with OAuth2, specifically the Authorization Code Grant Flow.</li></ul><p>Despite the prerequisites, I’ll give a quick explanation of what we’re trying to achieve to clear up some common misconceptions — ones I personally struggled with when starting out.</p><p>Our resource servers (e.g., books-service) should require authentication using an access token, likely a JWT. The web-app, whether a SPA (public client) or SSR (confidential client), needs authentication to communicate with the resource servers. Since OAuth2 is delegated authorization, the auth server can run independently in a separate container, cluster, or domain.</p><p>Firstly, it’s important to understand that the approach for a public client differs from that of a confidential client. Most security experts, including the Spring Security team, strongly recommend that public clients should not participate in the OAuth2 flow (I share the same opinion). Instead we must use confidential clients to communicate with the authorization server. Here’s why:</p><p>The OAuth2 authorization code flow requires the oauth2 client to present a “CLIENT SECRET” to identify itself. This is crucial because the authorization server can have many clients (e.g., BFF server, terminal client, third-party API user). The client secret must be securely stored, which can only be done in a confidential client. Public clients, like those in browsers, have no secure way to store secrets (local/session storage are accessible to javascript, and HTTP-only cookies can only be used securely across the same domain name, which is not likely to be the case in a delegated authorization environment). As a result, public clients must use the <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce">PKCE flow</a>, which does not require a client secret.</p><p>Additionally, once a public client is authorized, it cannot securely store sensitive OAuth2 tokens (e.g., access/refresh tokens).</p><p>Furthermore, once an access token is granted, it cannot be revoked until it expires, which means once it has been given out to a public client, there is no way to invalidate it.</p><p>With a confidential client, the OAuth2 authorization code flow mainly occurs on the server side, with the browser only used to provide credentials on the auth server login page. The confidential client maintains a session token with the browser, exchanging it for an OAuth2 token on each request, which is then passed to the resource servers. For a deeper dive into this pattern, check out this article on the <a href="https://www.baeldung.com/spring-cloud-gateway-bff-oauth2">benefits of this pattern</a></p><p>In fact, if you inspect the application tab of websites from major tech companies like Google, you’ll notice they don’t store JWTs or access tokens in the browser. Instead, they use session tokens.</p><p>In Part 1, we’ll set up the OAuth2 authorization code flow with a confidential OAuth2 client. For simplicity, I’ve chosen an API gateway application as the confidential client, but it could also be a BFF. Parts 2, 3, and 4 in the series are independent, so you can choose them based on your needs.</p><p>DISCLAIMER: Spring authorization server requires quite a bit of effort and tinkering to be bought up and running for a production environment.</p><h3>Part 1 — Spring Authorization Server — Oauth2 Authorization Code Flow — Confidential Client</h3><p>The branch for this guide is part-1/oauth2-authorization-code-flow.</p><p>I’m starting with a Gradle Groovy Spring Boot boilerplate, but a Maven project works just as well. Here are my default dependencies:</p><pre>// build.gradle<br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}</pre><p>The first step is to add some Spring dependencies. I’ll also include Lombok for convenience.</p><pre>// build.gradle<br>dependencies {<br>    // ...other dependencies<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &quot;org.springframework.boot:spring-boot-starter-security&quot;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-authorization-server&#39;<br>    compileOnly &#39;org.projectlombok:lombok&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok&#39;<br>}</pre><p>Let’s specify the port for our application:</p><pre># application.yml<br>server:<br>  port: 9000</pre><p>Now we can start configuring our authorization server. First, let’s define our client repository, which will manage the clients that our authorization server provides authorization to. There are many settings you can configure for each client, but below is a minimal configuration that should work fine.</p><p>In a production environment, this repository should ideally manage and store registered clients in a database. However, for this demo, we will use an in-memory store. 🤡</p><pre>// SecurityConfig.java<br>@Configuration<br>public class SecurityConfig {<br> <br>    private final static String GATEWAYCLIENTID = &quot;gateway-client&quot;;<br>    private final static String GATEWAYCLIENT_HOSTURL = &quot;http://localhost:8080&quot;;<br> <br>    @Bean<br>    public RegisteredClientRepository registeredClientRepository() {<br>        // @formatter:off<br>        RegisteredClient webClient = RegisteredClient<br>                .withId(UUID.randomUUID().toString())<br>                .clientId(GATEWAYCLIENTID)<br>                .clientSecret(passwordEncoder().encode(&quot;secret&quot;))<br>                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENTSECRETBASIC)<br>                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)<br>                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)<br>                .redirectUri(GATEWAYCLIENT_HOST_URL + &quot;/login/oauth2/code/&quot; + GATEWAY_CLIENTID)<br>                .postLogoutRedirectUri(GATEWAYCLIENT_HOSTURL + &quot;/logout&quot;)<br>                .scope(OidcScopes.OPENID)  // openid scope is mandatory for authentication<br>                .scope(OidcScopes.PROFILE)<br>                .scope(OidcScopes.EMAIL)<br>                .build();<br>        // @formatter:on<br>        return new InMemoryRegisteredClientRepository(webClient);<br>    }<br>}</pre><p>Next, we configure the Spring Security filter chains.</p><ul><li>The first filter chain is for authorization server-specific configurations.</li><li>The second filter chain handles application-specific configurations, such as additional endpoints.</li></ul><pre>// SecurityConfig.java<br>@Bean<br>@Order(1) // security filter chain for the authorization server<br>public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {<br>    // @formatter:off<br> <br>    // applyDefaultSecurity method deprecated as of spring security 6.4.2, so we replace it with below code block<br>    // -- STARTS HERE<br>    OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =<br>            OAuth2AuthorizationServerConfigurer.authorizationServer();<br> <br>    http<br>            .securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())<br>            .with(authorizationServerConfigurer, authorizationServer -&gt;<br>                    authorizationServer.oidc(Customizer.withDefaults()) // enable openid connect<br>            )<br>            .authorizeHttpRequests((authorize) -&gt; authorize.anyRequest().authenticated());<br>    // -- ENDS HERE<br> <br>    http<br>            .exceptionHandling((exceptions) -&gt; // If any errors occur redirect user to login page<br>                    exceptions.defaultAuthenticationEntryPointFor(<br>                            new LoginUrlAuthenticationEntryPoint(&quot;/login&quot;),<br>                            new MediaTypeRequestMatcher(MediaType.TEXT_HTML)<br>                    )<br>            )<br>            // enable auth server to accept JWT for endpoints such as /userinfo<br>            .oauth2ResourceServer(resourceServer -&gt; resourceServer.jwt(Customizer.withDefaults()));<br>    // @formatter:on<br> <br>    return http.build();<br>}<br> <br>@Bean<br>@Order(2) // security filter chain for the rest of your application and any custom endpoints you may have<br>public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {<br>    // @formatter:off<br>    http<br>            .formLogin(Customizer.withDefaults()) // Enable form login<br>            .authorizeHttpRequests(authorize -&gt; authorize.anyRequest().authenticated());<br>    // @formatter:on<br> <br>    return http.build();<br>}</pre><p>Next, define a PasswordEncoder bean to salt and hash passwords:</p><pre>// SecurityConfig.java<br>@Bean<br>public PasswordEncoder passwordEncoder() {<br>    return new BCryptPasswordEncoder();<br>}</pre><p>To enable login functionality, provide a user store with user credentials. For this guide, we’ll use an in-memory user store, but you can adapt it to fetch user details from a database if needed.</p><pre>// SecurityConfig.java<br>@Bean<br>UserDetailsService users() {<br>    // @formatter:off<br>    UserDetails user = User.builder()<br>            .username(&quot;prime&quot;)<br>            .password(&quot;agen&quot;)<br>            .passwordEncoder(passwordEncoder()::encode)<br>            .roles(&quot;USER&quot;)<br>            .build();<br>    // @formatter:on<br>    return new InMemoryUserDetailsManager(user);<br>}</pre><p>Now, let’s test the auth server.</p><ol><li>Open your browser and navigate to the root of the server (e.g., localhost:9000/). You should be redirected to the login page since you’re not authenticated.</li><li>Enter your credentials on the login page.</li></ol><figure><img alt="Screenshot of login page with credentials entered, username is ‘prime’ password is hidden" src="https://cdn-images-1.medium.com/max/566/1*hDIc1JyFH5sZ1JnYTLZMjQ.png" /></figure><p>3. After logging in, you should see the white label error screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*G1O5Tn8rB75a_KEHM-idyg.png" /></figure><p>This whitelabel error appears because there’s no resource at the root URL. It’s simply the default HTML returned for a 404 error.</p><p>So far, we’ve only interacted with the auth server itself. No tokens have been issued because we haven’t logged in on behalf of a client application. Instead, the auth server has managed our identity using its own session token, which is established between the browser and the server. By default, Spring uses the JSESSIONID token, which is produced by Tomcat.</p><p>I’ve set up a separate gradle project called api-service which includes an API gateway (confidential OAuth2 client) and a books-service (resource server).</p><p>Starting with the Resource Server. We’ll add the following dependencies:</p><pre>// build.gradle<br>dependencies {<br>    // ... other dependencies<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-resource-server&#39;<br>    // lombok for convenience<br>    compileOnly &#39;org.projectlombok:lombok&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok&#39;<br>}</pre><p>We’ll run it on port 8081.</p><p>Since we’ve added the OAuth2 resource server dependency, all our endpoints are authenticated by default. Therefore, the resource server expects authentication. We will now configure the resource server to accept JWT for authentication. To verify the JWT, it needs to know the public keys, so we’ll point the resource server to the authorization server.</p><pre># application.yml<br>server:<br>  port: 8081<br> <br>spring:<br>  # ... other configuration<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: http://localhost:9000</pre><p>I have a simple REST controller with one endpoint, /books. I’ve included some logic to extract the username and JWT token for demonstration purposes.</p><pre>// BookResource.java<br>@RestController<br>@RequiredArgsConstructor<br>public class BookResource {<br> <br>    @GetMapping(&quot;/books&quot;)<br>    public ResponseEntity&lt;String&gt; getBooks(Authentication authentication) { // authentication parameter is not necessary<br>        // The lines below are purely to demonstrate the existence of the jwt, you do not need them for your endpoints<br>        assert authentication instanceof JwtAuthenticationToken;<br>        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;<br>        String username = authentication.getName();<br>        String jwtString = jwtAuthenticationToken.getToken().getTokenValue();<br> <br>        return ResponseEntity.ok(&quot;Hi &quot; + username + &quot;, here are some books [book1, book2],  &quot; + &quot; also here is your jwt : &quot; + jwtString);<br>    }<br>}</pre><p>Let&#39;s set up our <a href="https://www.baeldung.com/spring-cloud-gateway-oauth2">API Gateway as an OAuth2 confidential client</a>.</p><pre>// build.gradle<br>dependencies {<br>    // ... other dependancies<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-gateway:4.2.0&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-client&#39;<br>}</pre><p>We’ll run our API Gateway on port 8080</p><p>Our API Gateway is quite simple, so we don’t need to write any code. Configuring it through application.yml is enough.</p><p>First, we’ll define our routes, and we only have one: the user service.</p><pre># application.yml<br>spring:<br>  # ...other configuration<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: book-service<br>          uri: http://localhost:8081<br>          predicates:<br>            - Path=/books/**<br>          filters:<br>            - TokenRelay # Token relay filter appends the oauth (or jwt) token to request header before forwarding requests</pre><p>Next, we can add our OAuth2 client configuration.</p><pre># application.yml<br>spring:<br>  # ... other configuration<br>  security:<br>    oauth2:<br>      client:<br>        provider:<br>          platform-auth-server:<br>            issuer-uri: http://localhost:9000<br>        registration:<br>          gateway-client:<br>            provider: platform-auth-server<br>            client-id: gateway-client<br>            client-secret: &quot;secret&quot;<br>            client-authentication-method: clientsecretbasic<br>            authorization-grant-type: authorization_code<br>            redirect-uri: http://localhost:8080/login/oauth2/code/gateway-client<br>            scope:<br>              - openid<br>              - profile<br>              - email</pre><p>Once the user has been authorized, just like our Auth Server, the API Gateway also issues a JSESSIONID to the user and stores the OAuth2/JWT tokens in the session, associating them with the JSESSIONID. In subsequent requests, the JSESSIONID is sent as an HTTP-only cookie.</p><p>However, our downstream resource server, books-service, is stateless and has no knowledge of this session and can only verify the authenticity of the JWT. This is where the token relay filter comes in. It exchanges the session token with the associated OAuth2 tokens and appends them to the request header before passing the request to downstream services</p><p>Although we have all our applications configured correctly, if we try the login flow, we will encounter some errors. This is because, although our auth server and API gateway are running on different ports, the browser sees them both as one application since they are both running on the same domain, ‘localhost’.</p><p>Both the API gateway and the auth server use the same token name by default, ‘JSESSIONID’. As a result, whenever the API gateway sets its session token, the browser overrides the session token set by the auth server, and vice versa.</p><p>To fix this, we can go ahead and run our auth server on a different domain name, like <a href="http://127.0.0.1/">http://127.0.0.1</a>. localhost is simply an alias for this IP address, but the browser still views them as two different domains, so it serves our purpose. We will need to tell the auth server its own address.</p><pre># application.yml (auth-server)<br>server:<br>  port: 9000<br>  address: 127.0.0.1</pre><p>Then, we replace any mention of the auth server URL in the other applications.</p><pre># application.yml (api-gateway)<br>spring:<br>  # ... other configuration<br>    platform-auth-server:<br>      issuer-uri: http://127.0.0.1:9000</pre><pre># application.yml (books-service)<br>spring:<br>  # ... other configuration<br>    resourceserver:<br>      jwt:<br>        issuer-uri: http://127.0.0.1:9000</pre><p>If you test this setup now, you should be able to access the resource server’s /books endpoint via the API Gateway at localhost:8080. You will be redirected to the Auth Server&#39;s login screen. After entering your credentials, you will be redirected back to the /books endpoint. All subsequent requests to this endpoint will remain authenticated without requiring another login at the Auth Server.</p><p>Let’s copy the JWT token you see on the /books endpoint and paste it into <a href="https://jwt.io/">jwt.io</a>. You’ll notice that the decoded JWT payload appears as follows:</p><pre>{<br>  &quot;sub&quot;: &quot;prime&quot;,<br>  &quot;aud&quot;: &quot;gateway-client&quot;,<br>  &quot;nbf&quot;: 1735996802,<br>  &quot;scope&quot;: [<br>    &quot;openid&quot;,<br>    &quot;profile&quot;,<br>    &quot;email&quot;<br>  ],<br>  &quot;iss&quot;: &quot;http://127.0.0.1:9000&quot;,<br>  &quot;exp&quot;: 1735997102,<br>  &quot;iat&quot;: 1735996802,<br>  &quot;jti&quot;: &quot;4dde1b42-5379-4b59-b97b-dd522e545ec7&quot;<br>}</pre><p>This is fine, but typically, we want to store more information in the JWT. Let’s explore how to add custom claims.</p><p>To customize our JWT, we need to provide an implementation of OAuth2TokenCustomizer to the Authorization Server.</p><pre>// Oauth2AccessTokenCustomizer.java<br>@RequiredArgsConstructor<br>@Component<br>public class Oauth2AccessTokenCustomizer implements OAuth2TokenCustomizer&lt;JwtEncodingContext&gt; {<br> <br>    @Override<br>    public void customize(JwtEncodingContext context) {<br>        if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {<br>            context.getClaims().claims(claims -&gt; {<br>                Object principal = context.getPrincipal().getPrincipal();<br>                User user = (User) principal;<br> <br>                Set&lt;String&gt; roles = AuthorityUtils.authorityListToSet(user.getAuthorities()).stream().map(c -&gt; c.replaceFirst(&quot;^ROLE_&quot;, &quot;&quot;)).collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));<br>                claims.put(&quot;roles&quot;, roles);<br> <br>                // I have only added the roles to the JWT here as I am using the limited fields<br>                // on the UserDetails object, but you can add many other important fields by<br>                // using your applications User class (as shown below)<br> <br>                // claims.put(&quot;email&quot;, user.getEmail());<br>                // claims.put(&quot;sub&quot;, user.getId());<br>            });<br>        }<br>    }<br>}</pre><p>Let’s define a token generator bean in the security configuration class. This will be a delegating token generator, enabling us to generate the appropriate token type for each scenario (e.g., JWT access token, refresh token, opaque token, OIDC token, etc.). We’ll pass the access token generator, along with the customizer we just defined, into this token generator.</p><pre>// SecurityConfig.java<br>@RequiredArgsConstructor<br>@Configuration<br>public class SecurityConfig {<br>    // ... other configuration<br> <br>    private final Oauth2AccessTokenCustomizer oauth2AccessTokenCustomizer;<br> <br>    @Bean<br>    OAuth2TokenGenerator&lt;OAuth2Token&gt; tokenGenerator(JWKSource&lt;SecurityContext&gt; jwkSource) {<br>        JwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);<br>        JwtGenerator jwtAccessTokenGenerator = new JwtGenerator(jwtEncoder);<br>        jwtAccessTokenGenerator.setJwtCustomizer(oauth2AccessTokenCustomizer);<br> <br>        return new DelegatingOAuth2TokenGenerator(jwtAccessTokenGenerator);<br>    }<br>}</pre><p>Let’s run our auth server again and check the new JWT.</p><pre>{<br>  &quot;sub&quot;: &quot;prime&quot;,<br>  &quot;aud&quot;: &quot;gateway-client&quot;,<br>  &quot;nbf&quot;: 1735999618,<br>  &quot;scope&quot;: [<br>    &quot;openid&quot;,<br>    &quot;profile&quot;,<br>    &quot;email&quot;<br>  ],<br>  &quot;roles&quot;: [<br>    &quot;USER&quot;<br>  ],<br>  &quot;iss&quot;: &quot;http://127.0.0.1:9000&quot;,<br>  &quot;exp&quot;: 1735999918,<br>  &quot;iat&quot;: 1735999618,<br>  &quot;jti&quot;: &quot;a5d3092c-de55-465e-8153-a4341e4d8754&quot;<br>}</pre><p>As you can see, the roles field has been added with the &quot;User&quot; role for prime.</p><p>You can technically run this setup; however, restarting the servers will result in lost login information. Additionally, this setup is not suitable for scaling with multiple instances of the API Gateway or Authorization Server. To make it production-ready, move the following to durable storage:</p><ul><li>Registered Client Repository: for OAuth2 clients</li><li>UserDetailsService: for user login store</li><li>OAuth2AuthorizationService: for tokens</li><li>JWK Source: for RSA keys pairs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d996d5c5a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying an Express.js MongoDB Application on AWS Lambda with Serverless Framework]]></title>
            <link>https://awstip.com/deploying-an-express-js-mongodb-application-on-aws-lambda-with-serverless-framework-289c39891a3f?source=rss-82928ac48e88------2</link>
            <guid isPermaLink="false">https://medium.com/p/289c39891a3f</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Afeef Razick]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 15:32:25 GMT</pubDate>
            <atom:updated>2024-01-29T19:32:53.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Step-by-Step Guide to AWS Lambda with Serverless Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5blW8CdZ_PrFKbw7RV3soQ.jpeg" /></figure><p>As I was seeking a free, long-term solution for deploying a backend application, I stumbled upon AWS Lambda. However, I couldn’t find a comprehensive guide tailored for beginners to deploy an Express.js MongoDB application, so I decided to write my own!</p><p>Big thanks to <a href="https://medium.com/u/cb816bf9ab75">Nanthushan Yogeswaran</a> for testing out the guide.</p><h4><strong>Introduction</strong></h4><p>This article is a guide on — well, you read the title. There are many approaches to the steps below, but this is the one I personally found easy to understand, and I hope you will too.</p><p>In this guide the Serverless Framework will use a few AWS services, namely Lambda, API Gateway, S3, CloudFormation and CloudWatch.</p><p>If you follow the guide below, it should cost you nothing to deploy — at least according to the AWS Free Tier as of the writing of this article. If you are reading this years into the future, that may have changed. In any case, you might want to check the <a href="https://aws.amazon.com/free/?gclid=CjwKCAiA75itBhA6EiwAkho9e_MeEf9OswrncXazfPKza-NqIeEJsrGWCvHRT1vSA-yX9MGh1iourBoCbMEQAvD_BwE&amp;trk=2738afd4-9401-4d18-8e3e-1b1c194dea07&amp;sc_channel=ps&amp;ef_id=CjwKCAiA75itBhA6EiwAkho9e_MeEf9OswrncXazfPKza-NqIeEJsrGWCvHRT1vSA-yX9MGh1iourBoCbMEQAvD_BwE:G:s&amp;s_kwcid=AL!4422!3!509606977827!p!!g!!aws%20amazon%20com!12618685604!120373367976&amp;all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc&amp;awsf.Free%20Tier%20Types=*all&amp;awsf.Free%20Tier%20Categories=*all">AWS Free Tier</a> to confirm.</p><h4>Prerequisites</h4><ol><li>You’ll need an AWS account to provide credentials to the Serverless Framework.</li><li>Ensure you have Node.js installed on your device, and a working understanding of Express.js and MongoDB.</li></ol><h4>Set Up Your Express.js Application</h4><p>Ideally, you should have your own Express.js project ready for deployment. However, if you’re experimenting, you can set up some <a href="https://expressjs.com/en/starter/hello-world.html">boilerplate code</a> or clone the <a href="https://github.com/AfeefRazick/my-lambda-demo">repository specifically set up for this project</a>. Switch to the “starter” branch for the starter code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*X5OzJKpxcCLwV1WLUKk-Gg.png" /><figcaption>Directory structure for my-lambda-demo</figcaption></figure><p>The index.js file contains some boilerplate code. Ensure cors is enabled as shown below to avoid some extremely <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">confusing errors.</a></p><pre>// index.js<br><br>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;; # enable cors<br>const app = express();<br><br>app.use(cors()); # enable cors<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.json(&quot;Lamba function is running!&quot;);<br>});<br><br>app.listen(5000, () =&gt; {<br>  console.log(&quot;Server is running on port 5000&quot;);<br>});</pre><h4>Configuring AWS credentials</h4><p>Having set up the application, the next step is to obtain AWS user credentials for the Serverless Framework by creating an AWS user account and access keys.</p><p>To begin, head over to the AWS console and search for IAM (Identity and Access Management).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zEmJDSZATYO0lE2Qf0Dv5A.png" /></figure><p>Navigate to the “Users” tab on the left-hand side panel and click on “Create user”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQVbm-6XSDGycXL0kyTIbA.png" /></figure><p>You can now name the IAM user. I’ll use “serverless-framework” as it will be used by the Serverless Framework, but feel free to choose any name you prefer. This IAM user will only need programmatic access so click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*DLD-uO6Tlj9hkeE9cyFxrQ.png" /></figure><p>In this step, grant the IAM user with permissions to access specific AWS resources. Choose “Attach policies directly”, then search for “AdministratorAccess” and select that policy. This policy will allow the IAM user to access all AWS resources in your account (It is best practice to select more restrictive policies, however this is not an IAM tutorial, therefore is sufficient for a non-production environment). Now, click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*uQo2STDOdm-od2lgEMsQKg.png" /></figure><p>The next page should look something like this, if so, click “Create user”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*6_JR34g3qv0pBxhSxg1sjw.png" /></figure><p>You have created your IAM user! The only thing left is to obtain the access keys. To do this, select the IAM user you just created, in my case “serverless-framework” and click “Create access key”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*212XiYL-Jiqig83XtheulQ.png" /></figure><p>Select “Command Line Interface (CLI)” and check the confirmation at the bottom. Then click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*7vny9SSjWpfoluf-NVQU4A.png" /></figure><p>Skip the description for the access key and click “Create access key”.</p><p>Finally, save both keys in a secure location and DO NOT share them with anyone. Ensure you save your Secret access key immediately as you cannot retrieve this key after navigating away from the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*12WJyROudshGChByh8ou_Q.png" /></figure><h4>Configuring AWS cli</h4><p>If you have already installed and configured AWS CLI credentials, you can skip this step.</p><p>To get started, install the AWS CLI by following the steps <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">here</a>. After installation, configure credentials by running the command aws configure in the terminal. Enter your details appropriately as shown below. More information can be found in the <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html#getting-started-quickstart-new-command">AWS user guide</a>.</p><pre>aws configure<br>AWS Access Key ID [None]: AKIA4IQ7F929D7G9S7F9<br>AWS Secret Access Key [None]: sd4gsFSGDFQ4pEckqFJ9hI93GyduSr7vU4<br>Default region name [None]: ap-south-1<br>Default output format [None]: json</pre><h4>Configuring Serverless</h4><p>Alright, it’s finally time to set up Serverless. To do so, we have a few more steps ahead.</p><p>To install serverless globally, run the following command:</p><pre>npm install -g serverless</pre><p>Next, enter the AWS IAM user credentials you just obtained in the terminal. Note: you can use the command serverless and sls interchangeably.</p><pre>sls config credentials --provider aws --key YOUR_ACCESS_KEY --secret YOUR_SECRET_KEY --profile YOUR_PROFILE_NAME<br><br># for example, I will be running <br>sls config credentials --provider aws --key AKIA4IQ7F929D7G9S7F9 --secret sd4gsFSGDFQ4pEckqFJ9hI93GyduSr7vU4 --profile serverless-framework</pre><p>Now that serverless has been provided with credentials, there are few changes to be made to the index.js file. Make sure your terminal is located in the project directory. If not, navigate to the project directory using the ‘cd’ command. An additional package serverless-http is needed to wrap your application, to install, run the following command:</p><pre>npm install serverless-http</pre><p>Import serverless and replace app.listen() in index.js as shown below.</p><pre>// index.js <br><br>import serverless from &quot;serverless-http&quot;;<br>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;;<br>const app = express();<br><br>app.use(cors());<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.json(&quot;Lamba function is running!&quot;);<br>});<br><br>export const handler = serverless(app)</pre><p>Then, create a serverless.yml file in the root of your directory which the serverless framework will use as instructions to deploy your application. Follow the comments to make appropriate changes.</p><pre># serverless.yml<br><br>service: my-lambda-demo # any name you prefer, ideally the project name <br><br>provider:<br>  name: aws<br>  runtime: nodejs20.x # node.js version your application is made for<br>  memorySize: 128 # appropriate memory size in mb for your application<br>  stage: dev<br>  region: ap-south-1 # region where resources will be deployed<br><br>functions:<br>  lambda-demo: # &lt;- name your function, any name you prefer<br>    handler: src/index.handler # relative path to lambda function from root<br>    events:<br>      - httpApi: ANY /<br>      - httpApi: &quot;ANY /{proxy+}&quot;</pre><p>Congratulations! You’ve reached the final step. To deploy, run command:</p><pre>sls deploy</pre><p>If everything goes smoothly, you should see a result similar to this. Click on the first link provided to test your Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*s48zOJjfmqUcn_odfpx6mQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*no9gTsBtSR9Xt-fyEGX9Vg.png" /></figure><p>Ideally, do not hardcode this link anywhere, to reduce the likelihood of bot attacks. To help keep the number of requests within the free tier. My endpoint above has been deleted after publishing this article.</p><p>If your endpoint didn’t return the expected result, double-check your endpoint paths or read the <strong>Debugging</strong> section at the bottom of this article.</p><h4>Setting up MongoDB connection</h4><p>In this step we’ll look at how to setup a MongoDB connection in a serverless environment. Connecting to a database from a serverless runtime is a little bit different from regular servers, to find out why this is the case, read <a href="https://stackoverflow.com/a/52939516/21266146">this</a>.</p><p>Here’s a typical Mongoose connection: while you can hard-code the database connection URI, it’s not best practice, so I’ll use an environment variable. For more information on setting up ENV variables, read <a href="https://www.freecodecamp.org/news/how-to-use-node-environment-variables-with-a-dotenv-file-for-node-js-and-npm/">this</a>.</p><pre>mongoose.connect(process.env.MONGODB_URI)<br>        .then(() =&gt; {<br>          console.log(&quot;Connected to MongoDB server successfully&quot;);<br>        })<br>        .catch((err) =&gt; {<br>          console.log(err);<br>        });</pre><p>Assuming you’ve already run sls deploy, and deployed your function, you can head over to that function in the AWS Lambda console. In the “Configuration” tab select “Environment variables” and click “Edit”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qz-7-QeVkTfp4zKI85l2Mw.png" /></figure><p>Enter the variable name you used and the connection URI and click “Save”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*Kr2IAGOaqgsb48B0lVX9fA.png" /></figure><p>The code for the connection will stay the same, but we want the connection to be established once and then reused. To achieve this, you can create a middleware function that runs before every request to check if the connection has already been established. Here is the final index.js file.</p><pre>// index.js<br><br>import serverless from &quot;serverless-http&quot;;<br>import mongoose from &quot;mongoose&quot;;<br>import express from &quot;express&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br>import cors from &quot;cors&quot;;<br>const app = express();<br><br>app.use(cors());<br><br>// ⬇️ the change to be made ⬇️<br>app.use(async (req, res, next) =&gt; {<br>  if (mongoose.connection.readyState === 0) {<br>    await mongoose<br>      .connect(process.env.MONGODB_URI)<br>      .then(() =&gt; {<br>        console.log(&quot;Connected to MongoDB server successfully&quot;);<br>      })<br>      .catch((err) =&gt; {<br>        console.log(err);<br>      });<br>  } else {<br>    console.log(<br>      &quot;Connection already established, reusing the existing connection&quot;<br>    );<br>  }<br>  next();<br>});<br>// ⬆️ the change to be made ⬆️<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.json(&quot;Lambda function is running!&quot;);<br>});<br><br>export const handler = serverless(app);</pre><p>Now, run sls deploy once again aaanndd…. congratulations! You’ve finally deployed your application. If something went wrong… read below.</p><h4>Debugging</h4><p>If you faced any issues before deployment, head over to Stack Overflow.</p><p>You may have managed to deploy your backend application, but your endpoints don’t return the expected result. Some common errors are “Cannot GET /” or “{‘message’: ‘Internal server error’}” or an authentication failed error. To troubleshoot, navigate to the AWS console, search for “CloudWatch”, and monitor the logs of each request, then grab the error message and head over to Stack Overflow.</p><p>So, that is to say, if you face any issues, good googling💀.</p><h4>References</h4><p><a href="https://prasadlakshan.medium.com/configuring-aws-credentials-using-serverless-framework-1b53f0989af4">prasadlakshan.medium.com/configuring-aws-credentials-using-serverless-framework-1b53f0989af4</a></p><p><a href="https://www.serverless.com/blog/serverless-express-rest-api/">www.serverless.com/blog/serverless-express-rest-api/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289c39891a3f" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-an-express-js-mongodb-application-on-aws-lambda-with-serverless-framework-289c39891a3f">Deploying an Express.js MongoDB Application on AWS Lambda with Serverless Framework</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>