<?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 Praveen Jayakody on Medium]]></title>
        <description><![CDATA[Stories by Praveen Jayakody on Medium]]></description>
        <link>https://medium.com/@pkjwrites?source=rss-b533a17917c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LrZky5TTEaJIJ96DbqT3SA.jpeg</url>
            <title>Stories by Praveen Jayakody on Medium</title>
            <link>https://medium.com/@pkjwrites?source=rss-b533a17917c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 20:25:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pkjwrites/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[Pairing Strapi with another Backend]]></title>
            <link>https://medium.com/nolooptech/pairing-strapi-with-with-another-backend-7f8d5e9a1754?source=rss-b533a17917c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f8d5e9a1754</guid>
            <category><![CDATA[strapi]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[cms]]></category>
            <dc:creator><![CDATA[Praveen Jayakody]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 16:54:43 GMT</pubDate>
            <atom:updated>2024-03-05T05:12:25.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pairing Strapi with a separate backend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMlHIRuTikzVXzTik02IvA.png" /></figure><p><em>In this article, we discover what Strapi is briefly and then explore an architecture where we have a CMS as well as a separate backend. This article specifically talks about a NestJS backend, but it can be applied to any type of backend.</em></p><h3>What is Strapi?</h3><p>One way to sum up Strapi is that it provides the tools to create different content types and create content using the said content types.</p><p>Examples for content type can be an article schema (which contains fields like article, author, content…etc), author schema (which contains fields like name, articles…etc). And content created using these types could be a specific article under a named author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGKKu-VfwjrNbESvO_GepA.png" /><figcaption>Content type editor showing the article schema</figcaption></figure><h3>Strapi architecture</h3><p>Content types can only be created or edited when Strapi is running in development mode. The interesting part about content types is that these are not stored in the database. Instead they are stored as JSON files in the src folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*LxOrHqpPPCWN6_pPyhgONQ.png" /><figcaption>Part of the folder structure showing the content type schema JSON</figcaption></figure><p>This means that content types are managed using version control (since they are part of the repo). To sync new content types to your production deployment, you need to pull from the version control.</p><h3>Setting up Strapi</h3><p>One way to get started is to create a repo using a <a href="https://github.com/strapi/strapi-cloud-template-blog">template from Strapi </a>. However, if you want to setup a Strapi with TypeScript support:</p><ol><li>yarn create strapi-app my-project --ts</li><li>yarn to install packages</li><li>Copy the provided .env.example and rename it to a new .env</li><li>Add database credentials to .env file</li></ol><pre># DB<br>DATABASE_CLIENT=postgres # If using a Postgres DB<br>DATABASE_HOST=test.postgres.database.azure.com<br>DATABASE_USERNAME=sampleuser<br>DATABASE_PASSWORD=pwd<br>DATABASE_SSL=true</pre><p><strong>Gotcha</strong>: if the database is a Postgres one, you might have to manually install pg package by running yarn add pg to install the driver.</p><p>Next, run yarn develop to start Strapi in auto reload mode. Access the admin portal using <a href="http://localhost:1337/admin/auth/register-admin">http://localhost:1337/admin</a> During the first time login, you will be prompted to create an admin user.</p><h3>Collection types and adding content</h3><p>A new collection type can be created by clicking on <em>Content-Type Builder</em><strong><em> </em></strong>and then <em>Create new collection type. </em>When you are creating a new collection type, you are given the option to add API IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p232IQdjpp2DURczdHygnw.png" /><figcaption>First dialog shown when creating a new collection type</figcaption></figure><p>Once you press on <em>Continue</em>, you are shown the screen below where you can certain fields of different types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffs46pPwDCwv_nWNQ8-WfA.png" /><figcaption>Add fields to a collection type (article)</figcaption></figure><p>And remember, creating a new content type will add new files in our code. Don’t forget to commit these!</p><p>After saving this, you can go to the <em>Content Manager</em> to add content from the type we just created (i.e. we can create new articles). Select the <em>Collection Type</em> as <em>Article</em>. You will be shown a list of existing articles (if any) and a <em>Create new entry</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SK0Zgn_tRh5Itn9Pg1CLCQ.png" /><figcaption>Screen to create a new article from our collection type</figcaption></figure><h3>Strapi endpoints</h3><p>Now that we have our content schema and content in place, how do we retrieve these from our ReactJS or React Native app?</p><p>Strapi has a REST API and a GraphQL API. In this article we will be looking at the REST API. How the REST API nomenclature is laid out can be accessed at <a href="https://docs.strapi.io/dev-docs/api/rest#endpoints">https://docs.strapi.io/dev-docs/api/rest#endpoints</a>.</p><p>By default, API needs to have an authentication of some sort. An API token can be created by going to <em>Settings</em> and then <em>API Tokens</em>. When creating API tokens, you are given the ability to control exactly what permissions and content is accessible by the token.</p><p>On each endpoint, the token should be sent on the Authorization header as a Bearer token (ex: Bearer &lt;api-token&gt;)</p><h3>Authentication and Users</h3><p>The issue with the API token method of authorisation is that we cannot differentiate between individual users. This situation arises in scenarios where the CMS is only part of the application.</p><p>Let’s say that you have a separate NestJS backend where there are certain user tiers. Tier A users can only access Silver Tier articles while Tier B users can access both Silver and Gold Tier articles.</p><p>Then we have the React app which consumes the content from our Strapi application but authenticates with the NestJS backend. How do we do permission management on Strapi end of things?</p><p>One option (the option that we will be looking at in this article) is to have a user on the Strapi server for every user on our NestJS backend. When a user authenticates with the NestJS backend, we can get a JWT token for the Strapi user as well.</p><p>This means that on the React app, there will be two JWTs:</p><ol><li>A JWT to send with requests to our NestJS backend</li><li>Another JWT to send with requests to our Strapi CMS</li></ol><p>The entire login flow and requesting flow can be summarised as the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*93FNPaM7S2hFA0OszviXIQ.png" /><figcaption>Login flow and requesting flow</figcaption></figure><h3>Custom authentication endpoint</h3><p>To create a custom Strapi endpoint, use yarn strapi generate with the API named <em>server-auth</em>. A new folder will be generated and in this folder, change <em>routes/server-auth.ts</em> and change the route path to <em>/auth/server</em>.</p><p>Change the newly created router, controller, and service as follows</p><pre>/* routes/server-auth.ts */<br><br>export default {<br>  routes: [<br>    {<br>     method: &#39;POST&#39;,<br>     path: &#39;/auth/server&#39;,<br>     handler: &#39;server-auth.auth&#39;,<br>     config: {<br>       policies: [],<br>       middlewares: [],<br>     },<br>    },<br>  ],<br>};</pre><pre>/* controllers/server-auth.ts */<br><br>export default {<br>  auth: async (ctx, next) =&gt; {<br>    try {<br>      // INFO: parsing<br>      const email: string = ctx.request.body.email;<br><br>      // INFO: validation<br>      if (!email) {<br>        ctx.throw(400, &#39;Email is required&#39;);<br>      }<br><br>      await strapi.service(&#39;api::server-auth.server-auth&#39;).auth(ctx, email);<br>    } catch (err) {<br>      ctx.throw(400, &#39;Could not authenticate&#39;, err);<br>    }<br>  },<br>};</pre><pre>/* services/server-auth.ts */<br><br>export default {<br>  auth: async (ctx, email: string): Promise&lt;void&gt; =&gt; {<br>    const userList = await strapi.entityService.findMany(&#39;plugin::users-permissions.user&#39;, {<br>      filters: {<br>        email,<br>      },<br>    });<br><br>    if (userList.length === 0) {<br>      ctx.throw(400, &#39;User not found&#39;);<br>      return;<br>    }<br><br>    const user = userList[0];<br><br>    const token = await strapi.plugins[&#39;users-permissions&#39;].services.jwt.issue({ id: user.id });<br>    ctx.body = {<br>      user: {<br>        id: user.id,<br>        email: user.email,<br>        createdAt: user.createdAt,<br>        updatedAt: user.updatedAt,<br>        blocked: user.blocked,<br>      },<br>      access_token: token,<br>    };<br>  },<br>};</pre><p>By default, this API route is created as a private route. This means that the API token which we use to call this endpoint (possibly from our NestJS server) needs to have permission to access this endpoint. To grant this permission, create (or modify an existing token) to have the permission to access this endpoint (which would have appeared now):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eJ-PgrKzdvSIbELFpQxEQ.png" /><figcaption>Grant permission to call our custom API</figcaption></figure><p><strong>Make sure you do not expose this API token!</strong> Because it has the power to authenticate any user by just providing the email address! However, in our use case, we will only be using this particular endpoint from the server.</p><p><em>P.S. I wrote this article while setting it up for a project so there might be gaps in the instructions. Do reach out to me with questions or feedback and I will make sure to answer them!</em></p><p><em>Special thanks to </em><a href="https://medium.com/u/dd3a57a184ec"><em>Thashwini Wattuhewa</em></a><em> for a great intro session into Strapi :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f8d5e9a1754" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nolooptech/pairing-strapi-with-with-another-backend-7f8d5e9a1754">Pairing Strapi with another Backend</a> was originally published in <a href="https://medium.com/nolooptech">NoLoopTech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication with Next.js 13 and Next Auth]]></title>
            <link>https://medium.com/ascentic-technology/authentication-with-next-js-13-and-next-auth-9c69d55d6bfd?source=rss-b533a17917c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c69d55d6bfd</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[credentials]]></category>
            <category><![CDATA[nextjs-13]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Praveen Jayakody]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:20:18 GMT</pubDate>
            <atom:updated>2023-07-04T07:20:18.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoIk9ylkOBAAyjrw5Iwnrg.png" /></figure><p>Next.js is a robust SSR framework that offers server-side rendering and static site generation for enhanced performance. Pair it with <a href="https://next-auth.js.org/">Next Auth</a>, a versatile authentication solution, and you have a powerful duo for secure user authentication.</p><p>Today we will explore how to create a login flow that authenticates users to an external API. Users will login using their email address and password after which a JWT is generated. The JWT is stored as a cookie which means that it is sent with all the next requests (pun intended). We have several ways to policy authentication and authorization with Next Auth. We can enforce it on the middleware level, in a server component using Next AuthgetServerSession or even on the client side using useSession from Next Auth</p><p>Next Auth supports both the Next.js 13 <a href="https://nextjs.org/blog/next-13-4#nextjs-app-router">app router</a> structure as well as the pages router. This article will be using the app router path. The application structure is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*vQYDOu2mDCcjOTCbVv9A-A.png" /><figcaption>Application diagram for the entire system</figcaption></figure><p>In this article we will only explore a relatively specific use case with a custom external API. However, Next Auth supports a plethora of authentication techniques like FusionAuth, Google Sign-in, OAuth…etc</p><h3>External API structure</h3><p>The external API has an authentication endpoint POST /api/auth/login which accepts a username and password pair in the request body. If authentication was successful, the request to the external API will send a 200 status response, otherwise a 4xx response.</p><p>The JSON response body of a successful authentication request will contain a user object and a token object like the sample response below:</p><pre>{<br>    &quot;user&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;username&quot;: &quot;john.doe@mailinator.com&quot;,<br>        &quot;email&quot;: &quot;john.doe@mailinator.com&quot;,<br>        &quot;fullname&quot;: &quot;John Doe&quot;,<br>        &quot;role&quot;: &quot;SUPER&quot;,<br>        &quot;createdAt&quot;: &quot;2021-05-30T06:45:19.000Z&quot;,<br>        &quot;name&quot;: &quot;John Doe&quot;<br>    },<br>    &quot;token&quot;: &quot;ey...&quot;<br>}</pre><p>Every subsequent response to the external API needs to have the token sent in the Authorization header as a Bearer token.</p><p>Now that we have sufficient context in place, let’s get into the code (finally!)</p><h3>Install Next Auth</h3><p>Step 0 is adding the Next Auth NPM package to your project. You can choose to do a yarn add next-auth or a npm install next-auth .</p><p>Next you will need to add a secret to your env file. Although during development you could leave this empty, during production it would raise an error. More information on how this can be added is available at <a href="https://next-auth.js.org/configuration/options#secret">the official Next Auth documentation</a>.</p><h3>Credential provider</h3><p>Using Next Auth, you can provide the user one or more login options (ex: credential login and social login). Each login method is enabled using its relevant <em>provider</em>. We will be using the <a href="https://next-auth.js.org/configuration/providers/credentials">credential provider</a> which is useful when there is an existing system to authenticate users against (in our case this is the external API).</p><p>Implementing an authentication flow with Next Auth is truly a breeze. Create a file /app/api/auth/[…nextauth]/route.ts<em>.</em> The [...nextauth] is kind of a catch-all route for requests beginning with /api/auth/*. The content should be as follows:</p><pre>import { authenticate } from &quot;@/services/authService&quot;<br>import NextAuth from &quot;next-auth&quot;<br>import type { AuthOptions } from &quot;next-auth&quot;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;<br><br>export const authOptions: AuthOptions = {<br>  providers: [<br>    CredentialsProvider({<br>      name: &#39;Credentials&#39;,<br>      credentials: {<br>        email: { label: &quot;Email&quot;, type: &quot;text&quot; },<br>        password: { label: &quot;Password&quot;, type: &quot;password&quot; }<br>      },<br>      async authorize (credentials, req) {<br>        if (typeof credentials !== &quot;undefined&quot;) {<br>          const res = await authenticate(credentials.email, credentials.password)<br>          if (typeof res !== &quot;undefined&quot;) {<br>            return { ...res.user, apiToken: res.token }<br>          } else {<br>            return null<br>          }<br>        } else {<br>          return null<br>        }<br>      }<br>    })<br>  ],<br>  session: { strategy: &quot;jwt&quot; }<br>}<br><br>const handler = NextAuth(authOptions)<br><br>export { handler as GET, handler as POST }</pre><p>We can add multiple sign in methods (if needed) to the providers: [] array, but here, we have added only the credential provider with a few configurations. The credentials object determine what fields will be shown on the login screen. And yes, Next Auth comes built-in with a simple default login screen accessible at &lt;your Next.js server&gt;/api/auth/signin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjukMt-06X3wGvSc2YN0Og.png" /><figcaption>The default Next Auth login page</figcaption></figure><p>The keys in the credential object will be used as the names for the input fields. And any other HTML properties (ex: label and type) can be provided per-field too. If you need to create a totally custom page, fret not, you can do so by defining your own pages as mentioned in the <a href="https://next-auth.js.org/configuration/pages">Next Auth documentation</a>.</p><p>The next point of interest is the authorize(credentials, req) callback. The credentials object will contain the key-value mapping for the submitted form (in this case, accessible via credentials.email and credentials.password). The req object will contain details about the request so it is possible to maybe check the IP address or user-agent during the authorization process. The authenticate() function sends a request to the external API and returns undefined (if the request failed) or the success response (provided earlier in the article). If the authorize() method returns null Next Auth translates that as meaning authentication has failed and shows a message on the sign in form accordingly.</p><p>To use the credential provider, it is necessary to set the session strategy as jwt . Either way, we need JWT as the session mechanism, so it’s all good!</p><h3>Next Auth middleware</h3><p>Now that we have a sign in page and all, we will create a protected route to test our login flow with. We will first look how we can enforce it at the middleware level.</p><p>Next Auth has a built-in middleware called withAuth . To use this, create a new file in the root called middleware.ts with the following content:</p><pre>import { withAuth } from &quot;next-auth/middleware&quot;<br><br>// middleware is applied to all routes, use conditionals to select<br><br>export default withAuth(<br>  function middleware (req) {<br>  },<br>  {<br>    callbacks: {<br>      authorized: ({ req, token }) =&gt; {<br>        if (<br>          req.nextUrl.pathname.startsWith(&#39;/protected&#39;) &amp;&amp;<br>          token === null<br>        ) {<br>          return false<br>        }<br>        return true<br>      }<br>    }<br>  }<br>)</pre><p>The authorized callback is invoked to check if the user is authorized (duh!). This means that we can add our own rules based on the information in req and token . In this use case, users can only access routes that start with /protected only if they have been authenticated (to be precise, if a token is available). If we return false the middleware will redirect to the sign in page (specifically the &lt;your Next.js server&gt;/api/auth/signin route from earlier unless you have defined a custom route). Later on, we will see how we can attach the user object from the external API onto the token so that we can do role-based access control as well!</p><h3>Access the session in a serverside component</h3><p>What if we want to show a sign in button on a page? We should be able to get the authentication status at the component level (server component level). We can create a page /app/public/page.tsx with the following code:</p><pre>import { getServerSession } from &quot;next-auth/next&quot;<br>import type { NextRequest } from &quot;next/server&quot;<br>import { authOptions } from &quot;@/app/api/auth/[...nextauth]/route&quot;<br><br>export default async function Protected (req: NextRequest): Promise&lt;any&gt; {<br>  const session = await getServerSession(authOptions)<br><br>  return (<br>    &lt;div className=&#39;grid grid-cols-2 text-white p-4&#39;&gt;<br>      &lt;div&gt;<br>        {<br>          session !== null<br>            ? &lt;h1 className=&#39;leading-loose text-[15rem] font-extrabold text-accent&#39;&gt;<br>                Hi {session?.user.name}!<br>              &lt;/h1&gt;<br>            : &lt;a className=&#39;btn btn-primary&#39; href=&#39;/api/auth/signin&#39;&gt;Sign in&lt;/a&gt;<br>        }<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Since this URL does not start with /protected, it will not be affected by our Next Auth middleware from earlier. Using getServerSession we can get the current session (or null if the user is not signed in). This way, we can show a ‘Sign in’ button if the user is not logged in or a greeting with the user’s name if they are indeed logged in.</p><h3>Access the session in a client side component</h3><p>Next Auth has a useSession hook that can be used to get session data and authenticated status on the client side. Before this hook can be used, the components must be wrapped in a SessionProvider because behind the scenes, it uses React Context.</p><p>We can create a file /app/context/client-provider.tsx with the following content:</p><pre>&#39;use client&#39;<br><br>import { SessionProvider } from &quot;next-auth/react&quot;<br><br>export default function Provider ({<br>  children,<br>  session<br>}: {<br>  children: React.ReactNode<br>  session: any<br>}): React.ReactNode {<br>  return &lt;SessionProvider session={session}&gt;<br>    {children}<br>  &lt;/SessionProvider&gt;<br>}</pre><p>We can then use this on a server side component (most probably the root layout.tsx)</p><pre>import &#39;@/app/globals.css&#39;<br>import React from &#39;react&#39;<br>import { Montserrat } from &#39;next/font/google&#39;<br>import Provider from &quot;@/app/context/client-provider&quot;<br>import { getServerSession } from &quot;next-auth/next&quot;<br>import { authOptions } from &quot;@/app/api/auth/[...nextauth]/route&quot;<br><br>const montserrat = Montserrat({ subsets: [&#39;latin&#39;] })<br><br>export const metadata = {<br>  title: &#39;Create Next App&#39;,<br>  description: &#39;Generated by create next app&#39;<br>}<br><br>export default async function RootLayout ({<br>  children<br>}: {<br>  children: React.ReactNode<br>}): React.ReactNode {<br>  const session = await getServerSession(authOptions)<br><br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={`${montserrat.className} bg-primary min-h-screen min-w-screen`}&gt;<br>        &lt;Provider session={session}&gt;<br>          {children}<br>        &lt;/Provider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><p>Why can’t we wrap the SessionProvider itself in the layout.tsx ? Since SessionProvider uses React Context (without defining the boundary using &quot;use client”), it can’t be imported into a server side component. Why not use it in a client component then? The SessionProvider needs to be provided the session object which can only be obtained using getServerSession, which, you guessed it, is a server side function! The pattern we can follow in a situation like this is to create a new client side component (client-provider.tsx in this case) to accept the <em>server side object</em> that needs to be passed, as a prop. We can import this new component into the layout.tsx (which is a server side component) and pass the session obtained from getServerSession() onto the session prop!</p><p>Now since all of that is taken care of, we can use useSession inside a client component:</p><pre>&#39;use client&#39;<br><br>import { useSession } from &quot;next-auth/react&quot;<br>import React, { useState } from &quot;react&quot;<br><br>export default function ClientSideRoot (): any {<br>  const { data: session } = useSession()<br><br>  const [shown, setShown] = useState&lt;boolean&gt;(false)<br>  const clickHandler = (): void =&gt; {<br>    setShown(!shown)<br>  }<br><br>  return (<br>    &lt;div className=&#39;grid grid-cols-2 text-white p-4&#39;&gt;<br>      &lt;div&gt;<br>        &lt;h1 className=&#39;leading-loose text-[15rem] font-extrabold text-accent&#39;&gt;<br>          Hi {session?.user.name}!<br>        &lt;/h1&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;p&gt;Protected client page&lt;/p&gt;<br>        &lt;button className=&quot;btn btn-primary&quot; onClick={clickHandler}&gt;Toggle&lt;/button&gt;<br>        {shown<br>          ? &lt;pre&gt;{JSON.stringify(session, null, 2)}&lt;/pre&gt;<br>          : null<br>        }<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Customize session token content</h3><p>By default, the session token will contain the basic name and email. But in our use case, we have other data (like the role and external API token) that needs to persist on the session. Next Auth is customizable and offers <em>callbacks</em> to modify the session content. We can edit the Next Auth configuration in /app/api/auth/[…nextauth]/route.ts :</p><pre>  // ... <br>  session: { strategy: &quot;jwt&quot; },<br>  callbacks: {<br>    async session ({ session, token, user }) {<br>      const sanitizedToken = Object.keys(token).reduce((p, c) =&gt; {<br>        // strip unnecessary properties<br>        if (<br>          c !== &quot;iat&quot; &amp;&amp;<br>          c !== &quot;exp&quot; &amp;&amp;<br>          c !== &quot;jti&quot; &amp;&amp;<br>          c !== &quot;apiToken&quot;<br>        ) {<br>          return { ...p, [c]: token[c] }<br>        } else {<br>          return p<br>        }<br>      }, {})<br>      return { ...session, user: sanitizedToken, apiToken: token.apiToken }<br>    },<br>    async jwt ({ token, user, account, profile }) {<br>      if (typeof user !== &quot;undefined&quot;) {<br>        // user has just signed in so the user object is populated<br>        return user as JWT<br>      }<br>      return token<br>    }<br>  }<br>}</pre><p>The jwt() callback is called with user when the user first logs in. The user object will be populated with the object that is returned from the authorize function. The object that is returned from the jwt callback is what will be saved on the session cookie.</p><p>The session() callback receives the session cookie content in its token parameter. Whatever is returned from this callback is what will be presented when useSession or getServerSession is called.</p><p>This way we can customize the token content too. Now that we have access to the apiToken both on the server side and client side, we have the flexibility of initiating authenticated fetch requests from either context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c69d55d6bfd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascentic-technology/authentication-with-next-js-13-and-next-auth-9c69d55d6bfd">Authentication with Next.js 13 and Next Auth</a> was originally published in <a href="https://medium.com/ascentic-technology">Ascentic Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting an Electron app ready for macOS distribution]]></title>
            <link>https://medium.com/ascentic-technology/getting-an-electron-app-ready-for-macos-distribution-2941fce27450?source=rss-b533a17917c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2941fce27450</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[Praveen Jayakody]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 14:28:17 GMT</pubDate>
            <atom:updated>2022-10-13T14:28:17.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1pzMyBUoiBDKHwjTw5Mxg.png" /></figure><h3>Easy start!</h3><p>If you are from a JavaScript background, you would have found it extremely easy to develop a cross platform desktop app using Electron. After developing it on Windows, your curiosity piqued and probably tried to run the project on macOS. Much to your amazement it builds and runs perfectly fine on macOS too!</p><p>The logical next step is to give your <em>Amazing App.exe</em> to your friend. This would have gone well too — the process for creating a distributable using <a href="https://www.electronforge.io/">Electron Forge</a> is quite straightforward. Much to your dismay, the perfectly functioning macOS app that ran on your Mac, faces an alarming message when your friend downloads it and tries to run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*1An6Pj_2jrXMriGL.png" /><figcaption>You only get two options and one of them is delete the app!</figcaption></figure><p>Neither options provided include an option to use the app. In fact, the alert suggests that you immediately move it to the bin!</p><h3>App notarization on macOS</h3><p>The single reason for this mishap is that the generated <em>Amazing App.app</em> macOS bundle has not been signed. You can read about the signing process and how it upholds app integrity at the <a href="https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution">official Apple documentation</a>. This article looks at doing just that — so you can create an Electron app that anyone can download! After following the instructions here, you can generate a macOS app that gives the below alert (like almost all other macOS software downloaded from a web page):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PXUIt3d8SGTJiX6g.png" /><figcaption>A better prompt</figcaption></figure><h3>Requirements</h3><p>To follow through with this guide, you should have an Electron project that runs and builds fine on macOS. Most steps in notarization process require Xcode 10 or later and macOS 10.13.6 or later. You need a paid Apple developer for app notarization. We will use <a href="https://www.electronforge.io/">Electron Forge</a> to build and package the app. Their documentation covers both scenarios where you are creating a new <em>forge</em>-based project as well as adding Electron Forge support to an existing one.</p><p>We are going with Electron Forge because it has built in support to handle the notarization process. We just need to configure it!</p><h3>Configuring Electron Forge</h3><p>Add an entry called forge in the config object of the package.json file. Add the string build-scripts/forge.config.js to this key. After this, your package.json file should look a bit like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2a795e7d67442bfe1060bdfddd7739/href">https://medium.com/media/9a2a795e7d67442bfe1060bdfddd7739/href</a></iframe><p>This instructs forge to use the configuration that we will define at forge.config.js in the build-scripts folder.</p><p>This file should look a bit like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd6c4a0074fbfa3d7873ba7c7999cb76/href">https://medium.com/media/bd6c4a0074fbfa3d7873ba7c7999cb76/href</a></iframe><p>There probably will be other configuration settings including name...etc. If you already had a configuration, you can copy those settings over to this file.</p><h3>Electron app signing</h3><p>The osxSign object configures the app signing procedure. hardenedRuntime option requests the signing procedure to add protections against certain exploits like code injection, hijacking...etc (more details at the <a href="https://developer.apple.com/documentation/security/hardened_runtime">official Apple documentation</a>). The identity option is automatically deduced if you have signed in to your Apple developer account on Xcode. You will also have to add a signing certificate (of type <em>Developer ID Application</em>) on Xcode. To do this open Xcode → Preferences → Accounts → Select your Apple ID → Manage Certificates... → Add button → Developer ID Application → Done. The screenshot below should be of help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*SKc1SAsoMR-1XMPb.png" /></figure><p>It is required to add a list of all permissions the app would access in its lifetime. This is done using the entitlements.plist file inside our build-scripts folder. A minimal entitlements.plist file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f984a83f993c67c3b3fe6b0579a9c4/href">https://medium.com/media/42f984a83f993c67c3b3fe6b0579a9c4/href</a></iframe><p>For versions older than Electron 12, the com.apple.security.cs.allow-jit was required - it is advised to not use it anymore if it can be avoided. Add any other permissions that your Electron app might need, for example, microphone access and camera access as described <a href="https://www.electronforge.io/guides/code-signing/code-signing-macos#signing-and-notarizing-macos-builds">here</a>.</p><h3>Notarization</h3><p>The osxNotarization object configures the notarization process. The notarization process uploads almost all constituents of the macOS app to the Apple notary service. So be ready for an upload of no less than 60 MB when it comes to an Electron app! If the notary service detects no issue, the service sends a ticket. This ticket is attached onto the app bundle. For a more insightful explanation about the process, you can look into the <a href="https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution">Apple&#39;s official documentation on app notarization</a>. Not to worry, we just need to provide the osxNotarization configuration. Electron Forge takes care of the rest!</p><p>Under the hood, Electron Forge uses <a href="https://www.npmjs.com/package/electron-notarize#method-notarizeopts-promisevoid">electron-notarize plugin for notarization</a>. The tool option can be either notarytool or legacy. We will use notarytool as this is faster and has more authentication methods (to ensure that our app bundle is uploaded securely and privately). The most convenient method is to use the <em>API key</em> authentication method. We store the API keys in a separate file build-keys.json inside the build-scripts folder. This is so that we can commit the forge.config.js file to version control without having to commit the API keys too. In short, the sole purpose of the API keys is to let notarytool upload the app bundle on our behalf.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a84c9894229c69ddcb77ef36fc86ce7d/href">https://medium.com/media/a84c9894229c69ddcb77ef36fc86ce7d/href</a></iframe><p>Firstly, <a href="https://appstoreconnect.apple.com/">sign in to your App Store Connect</a> account using a web browser. Go to <em>Users and Access</em>. Click on the <em>Keys</em> tab and then on the <em>App Store Connect API</em>. Next, click on the add button and generate an API key with <em>App Manager</em> access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q8Dv7Ivuvd13o9yk.png" /></figure><p>Download the API key — remember that you can only do this once! So store a backup securely in a safe place. Do not commit this file. And point the apiKey option to this file. Next, fill in the apiKeyId and the apiIssuer options.</p><h3>Gotchas</h3><p>If you have an advanced packaging configuration that copies files to within the app bundle. Make sure that Amazing App.app/Contents/MacOS folder has only the executable. Having any other files in this directory could fail the notarization process. Any extra resources should go in the aptly names Resources folder within app package.</p><h3>Done!</h3><p>That’s about it for the whole configuration process! You can generate a macOS app bundle using yarn make or the relevant make command as defined in packageConfig.json. To verify that the notarization process was successful, you can run</p><pre>spctl -a -vvv -t install &quot;Amazing App.app&quot;</pre><p>Finally, if all has gone well, you should see a response like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*-NfJdN36thqDpa4M.png" /></figure><p><em>Thanks to Sachintha for the thumbnail!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2941fce27450" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascentic-technology/getting-an-electron-app-ready-for-macos-distribution-2941fce27450">Getting an Electron app ready for macOS distribution</a> was originally published in <a href="https://medium.com/ascentic-technology">Ascentic Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>