<?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 Stijn Janssens on Medium]]></title>
        <description><![CDATA[Stories by Stijn Janssens on Medium]]></description>
        <link>https://medium.com/@stijn.janssens_6508?source=rss-fd70f8880065------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mvhEKzV-56Q_HOuy</url>
            <title>Stories by Stijn Janssens on Medium</title>
            <link>https://medium.com/@stijn.janssens_6508?source=rss-fd70f8880065------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:29:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stijn.janssens_6508/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[From Idea to Implementation: Building an MCP Server for our Data Product Portal]]></title>
            <link>https://medium.com/datamindedbe/from-idea-to-implementation-building-an-mcp-server-for-our-data-product-portal-f130e71c0a21?source=rss-fd70f8880065------2</link>
            <guid isPermaLink="false">https://medium.com/p/f130e71c0a21</guid>
            <category><![CDATA[data-product-portal]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Stijn Janssens]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 10:49:07 GMT</pubDate>
            <atom:updated>2026-03-17T11:28:04.560Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past weeks I’ve been experimenting with building an <strong>MCP (Model Context Protocol) server</strong> for our <a href="https://github.com/conveyordata/data-product-portal">Data Product Portal</a>. The portal is a platform for building and managing data products and datasets, both from a consumer and a producer perspective. Currently we provide an API with a UI on top. In this article we explore the possibilities of adding an MCP to that equation, allowing you to talk directly to your data using natural language.</p><p>What began as a small proof of concept quickly evolved into a deeper dive into the vision of MCP as well as the technical challenges of building it. By the end of this blogpost, you’ll know why MCP is worth exploring, what pitfalls to avoid, and how you can start experimenting with your own.</p><h3>Why even bother with an MCP?</h3><p>Before diving into how MCP helps, let me briefly explain what the <strong>Data Product Portal</strong> is.</p><p>It’s our open-source platform to manage, govern and build all data products and datasets in your organisation. You can see ownership, lifecycle status, lineage between products, and which users have which roles. In short: it’s the single place where data producers and consumers go to <strong>understand and manage the data landscape</strong>.</p><p>It’s a powerful tool but currently we are limited in how we can interact with it.</p><ul><li>If you’re technical, you can hit the <strong>API</strong>, but then you need to know schemas, endpoints, and query parameters.</li><li>If you’re less technical, you rely on the <strong>graphical frontend.</strong> This frontend is accessible, but often requires lots of clicking, filtering, and searching before you find what you need. This is a problem that becomes worse when using the tool at scale.</li></ul><p>That’s why we wanted to introduce Generative AI as a third option to interact with portal. By exposing the Data Product Portal to agentic systems, you unlock <strong>the possibility to interact using natural language</strong>. Especially for the non-technical users of the portal, such as business users or C-level stakeholders, the third option allows complex queries to be performed without having to click through the UI.</p><p>Imagine trying to answer the question: <em>“Which data products are managed by user X”.</em> If your portal contains hundreds of data products, finding this information in the frontend might be tricky. But the MCP will give you a nice summary in seconds.</p><p>That’s where MCP comes in. It’s a protocol that lets you <strong>host your own AI-aware services</strong> and make them available to LLMs. Suddenly, instead of a chatbot that guesses, you get an assistant that actually knows.</p><p>With MCP you get:</p><ul><li><strong>Specialization</strong> → tools that understand your company’s unique language.</li><li><strong>Control</strong> → hosted in your environment, with your security rules.</li><li><strong>Integration</strong> → directly call APIs, fetch lineage, check ownership.</li><li><strong>Scalability</strong> → add more services over time, forming an ecosystem of specialized agents.</li></ul><h3>An MCP server for data products</h3><p>Imagine being able to ask:</p><ul><li><em>“What datasets does our marketing team own, and who has access to them?”</em></li><li><em>“Show me the lineage of the customer table used in last quarter’s sales reports.”</em></li><li><em>“Which data products are currently in deprecated lifecycle status?”</em></li></ul><p>Instead of navigating complex UI screens or pulling API documentation, the AI can directly query the MCP server and return an answer in plain English. The portal transforms from a passive catalog into an <strong>active assistant</strong> that understands your questions in context.</p><p>This is why companies are excited. C<strong>ompanies don’t just want AI, they want AI that understands <em>their business processes</em>.</strong> MCP servers make that possible by combining generative models with company-specific context, making data governance and discovery dramatically more approachable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZmhTCfyLtMm8yo5ICiZ_A.png" /><figcaption><a href="https://www.dataminded.com/what-we-do/data-product-workshop">https://www.dataminded.com/what-we-do/data-product-workshop</a></figcaption></figure><h3>See it in Action</h3><p>It’s much easier to understand when you see the assistant talk directly to the Data Product Portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9p4bhDnxN0AlI0LQjkTWYw.gif" /><figcaption>MCP server in action: Natural language questions are asked to query the live data of the Data Product Portal</figcaption></figure><h3>Our path to building an MCP server</h3><p>First we looked at <strong>Generic LLMs</strong>, trying to manually build an agentic system with <a href="https://ai.pydantic.dev/">Pydantic AI</a>. These are quick to use, but shallow. They don’t know your data, your lineage, or your terminology. The hackathon was short and unfruitful. We found out that the initial prompt has an enormous impact on the resulting performance. Even with an elaborate system prompt we did not manage to have a higher than 30% success rate on queries. Most of the time the answers were hallucinated because the system did not have enough tools to learn the necessary context.</p><p>That’s why I implemented the server using <a href="https://gofastmcp.com/getting-started/welcome">FastMCP</a>.</p><p>When you build an MCP server, you have a few options:</p><ul><li><strong>Auto-generate tools from OpenAPI specs</strong></li><li><strong>Hand-code the server logic directly</strong></li><li><strong>Vibe code your way to success</strong></li></ul><p>I tried all of the above options, neither of them was the correct solution in my case. Below is what worked (and didn’t).</p><h3>Why I Didn’t Use OpenAPI</h3><p>My first instinct was to reuse our <strong>FastAPI OpenAPI spec</strong>. Every endpoint instantly became a tool. Sounds great, right?</p><p>In practice: not so much. Our backend was not designed with agentic systems in mind, which means that most of the endpoints are not relevant or not meant to be used by AI.</p><p>The result was <strong>bloated, noisy, and confusing</strong> for the LLM. It couldn’t pick the right tool, and we as developers lost control.</p><p>On top of that, most AI clients struggled with overly large tool descriptions. Sometimes the free models couldn’t even call the tool without reaching their limit of tokens.</p><p>So I went another way: I <em>vibecoded</em> the MCP tools by hand. I only exposed what actually mattered. And surprisingly, it worked much better.</p><p>Later on, I refactored the code to reuse the already existing service layer. This way we minimize the boilerplate code and make sure the MCP server and regular API endpoints use the same logic.</p><p>💡 <strong>Tip if you try this</strong>: start small. Don’t expose your whole API. Pick the 3–5 most valuable tools and get those working first.</p><h3>Wrestling With OAuth</h3><p>If you want your MCP server to be used in production, <strong>OAuth is non-negotiable</strong>. Without it, the MCP server is just an open endpoint and anyone could query it! The server wouldn’t know who you are. With OAuth in place, the MCP server can do the same thing the Data Product Portal already does:</p><ul><li>Ask the user to log in,</li><li>Know who they are,</li><li>And tailor results based on their identity and permissions.</li></ul><p>That’s worth the effort: once you log in, the MCP server only shows you the datasets, products, and roles you’re allowed to see. This feels integrated, similar to what we expect from any API.</p><p>Unfortunately, the implementation process was not smooth-sailing. I came across a lot of challenges and the documentation (I used version 2.10.6 of fastmcp) was lacking at the time.</p><p>This is a snippet of some of the extra routes you have to implement. You only find this in obscure git issues. If you want to look at the full code, please have a look <a href="https://github.com/conveyordata/data-product-portal/blob/main/backend/app/mcp/router.py">here</a>. It feels cumbersome to implement these methods ourselves because this is information that our OAuth provider (in our case AWS Cognito) already serves. However you can not link to this information in your BearerAuthProvider , or I did not figure out how to.</p><pre>@router.get(&quot;/.well-known/oauth-authorization-server&quot;)<br>def oauth_metadata() -&gt; JSONResponse:<br>    &quot;&quot;&quot;OAuth 2.1 Authorization Server Metadata.&quot;&quot;&quot;<br>    return JSONResponse(<br>        {<br>            &quot;issuer&quot;: get_oidc().authority,<br>            &quot;authorization_endpoint&quot;: get_oidc().authorization_endpoint,<br>            &quot;token_endpoint&quot;: get_oidc().token_endpoint,<br>            &quot;jwks_uri&quot;: get_oidc().jwks_uri,<br>            &quot;registration_endpoint&quot;: f&quot;{settings.HOST.rstrip(&#39;/&#39;)}/api/register&quot;,<br>            &quot;response_types_supported&quot;: [&quot;code&quot;],<br>            &quot;code_challenge_methods_supported&quot;: [&quot;S256&quot;],<br>            &quot;token_endpoint_auth_methods_supported&quot;: [&quot;client_secret_post&quot;],<br>            &quot;grant_types_supported&quot;: [&quot;authorization_code&quot;, &quot;refresh_token&quot;],<br>        }<br>    )</pre><p>Next to the undocumented endpoints that were required, other issues popped up as well:</p><h4><strong>Local vs. Production differences</strong></h4><p>ModelInspector and FastMCP behaved differently in debug versus real runs, especially around expected routes. What worked locally suddenly broke in production and vice versa.</p><h4><strong>Library instability</strong></h4><p>Both <em>fastmcp</em> and <em>authlib</em> have quirks. Version differences often meant inconsistent or buggy behavior. Some things that worked in one release stopped working in the next. Here the local versus production runs also showed different results, making debugging a real struggle.</p><h4><strong>Listening to random ports vs. AWS Cognito</strong></h4><p>FastMCP’s OAuth flow assumes <strong>a random available port</strong> for callbacks. This doesn’t play nicely with <strong>AWS Cognito</strong>, which requires redirect URLs to be registered upfront. We had to use static ports for callbacks, which is far from ideal and complicates deployments.</p><p>In the <a href="https://github.com/conveyordata/data-product-portal/blob/main/mcp/remote_proxy.py">proxy client</a>, I rewrote the OAuth logic to open a fixed port, instead of a random available one. That way I could fix the redirect url, which Cognito requires.</p><pre># Setup OAuth client <br>redirect_port = 57453     <br>redirect_uri = f&quot;&lt;http://localhost&gt;:{redirect_port}/callback&quot;</pre><p>It does not help that AWS Cognito has zero information in the error messages.</p><p>Together, these issues meant that OAuth integration took far longer than expected and it’s still an area that could benefit from more robust library support.</p><p>💡 <strong>Tips to get started</strong>:</p><ul><li>Don’t set up your OAuth immediately for MCP. Make sure you have a working OAuth setup for easier technologies, such as FastAPI. I knew upfront that my OAuth provider and backend configuration was correct and not the issue, because it was already working for FastAPI.</li><li>Lock your dependency versions. These libraries are still in very active development and OAuth is hard to test, but easy to break. Don’t just trust “latest”.</li><li>If you’re on AWS Cognito, make sure to use a <strong>dedicated static redirect URL.</strong></li><li>Use your existing service layer: once authentication works, the rest of the server can reuse the same permission checks as your API. Because we use the same OAuth configuration, both my backend and the MCP server parse the JWT tokens in the same way. No logic is duplicated and the MCP server uses the exact same internal users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3FY1GTv7OU3_dACUEjKNw.gif" /><figcaption>OAuth in action, do note the fixed redirect port.</figcaption></figure><p>It looks like there is some promising new ways to setup your MCP servers with OAuth in the latest releases of <a href="https://www.jlowin.dev/blog/fastmcp-2-12">FastMCP</a>, so I hope you can skip a large part of my struggles. However, there is no built in support for AWS Cognito yet, so maybe my tips are still relevant. Let me know how the implementation worked out for you!</p><h3>Conclusion</h3><p>Despite the hurdles, the experiment worked: we now have a <strong>working MCP server for the Data Product Portal</strong>. It allows natural language exploration of data products, datasets, lineage, and user roles. It really feels like a real step forward toward AI-native data platforms.</p><p>This is still early and experimental, but I’d love to hear your feedback.</p><p>👉 <strong>Set up the Data Product Portal and connect your favourite MCP client with our server. Experience first-hand how it feels to talk to your data.</strong></p><p>You’ll find everything you need on our <a href="https://github.com/conveyordata/data-product-portal">GitHub repository</a> and official <a href="https://docs.dataproductportal.com/">Documentation page</a>. Feedback, contributions, and war stories are more than welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f130e71c0a21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/from-idea-to-implementation-building-an-mcp-server-for-our-data-product-portal-f130e71c0a21">From Idea to Implementation: Building an MCP Server for our Data Product Portal</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Product Portal Integrations 2: Helm]]></title>
            <link>https://medium.com/conveyordata/data-product-portal-integrations-2-helm-982f4a54c0f0?source=rss-fd70f8880065------2</link>
            <guid isPermaLink="false">https://medium.com/p/982f4a54c0f0</guid>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-product-portal]]></category>
            <dc:creator><![CDATA[Stijn Janssens]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 08:19:24 GMT</pubDate>
            <atom:updated>2024-12-15T15:55:48.286Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to install portal in your production environment using Helm</h4><p>Welcome to the next instalment of our Data Product Portal integrations series! If you missed it, be sure to check out our first blog post on <a href="https://medium.com/p/8d1dcdc0896e">How to integrate with OIDC</a>.</p><p>In this post, we’ll focus on installing the portal in production environments. While it’s possible to create a production-ready deployment using our Docker images, the easiest way is to use <a href="https://helm.sh/docs/">Helm</a> on an existing <a href="https://kubernetes.io/">Kubernetes</a> cluster. Using our Helm chart will allow you to be up and running in no time.</p><p>In this blog post, we’ll go over the specific configuration values in our Helm chart, what they are, and how they should be used.</p><h3>What is Helm?</h3><blockquote>Helm helps you manage Kubernetes applications — Helm Charts help you define, install, and upgrade even the most complex Kubernetes applications.</blockquote><p>We provide a Helm chart that sets up all the necessary components on your Kubernetes cluster to seamlessly interact with everything that is already there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzPG2QetR9uedV7NsPQlQQ.png" /></figure><h3>The Values File</h3><p>Helm configurations can be adapted to your custom needs through config values. You can pass these values directly to your helm install commands, but best practices suggest putting them in a values.yaml file instead. You can find this file in our codebase <a href="https://github.com/conveyordata/data-product-portal/blob/main/helm/values.yaml">here</a>.</p><p>The values.yaml file of the portal has two large sections.</p><ul><li>Configuration values that you <strong>must </strong>change.</li><li><strong>Optionally </strong>configurable values.</li></ul><h3>Mandatory Configuration Values</h3><p>These values <strong>must</strong> be updated to fit your specific environment. If you do a helm install without adjusting these values you run the risk of deploying an <em>insecure</em> version of portal, with default database passwords and badly configured CNAMEs</p><h4>OIDC</h4><p>This configuration sets up the oidc integration. For more detailed information on setting this up, refer to our <a href="https://medium.com/p/8d1dcdc0896e">previous blog post</a>.</p><pre>oidc:<br>  disabled: false<br>  client_id: id<br>  client_secret: secret<br>  authority: authority<br>  redirect_uri: host</pre><h4>PostgreSQL</h4><p>The Helm chart has built-in support for <a href="https://artifacthub.io/packages/helm/bitnami/postgresql">this PostgreSQL dependency chart</a>. If postgres_enabled: true , the Helm install will also set up a PostgreSQL database inside your Kubernetes cluster. The values under global are the configuration values for this database.</p><p>Note that we pass port as an explicit string, to prevent the Helm chart from doing bad casting.</p><p>If postgres_enabled: false then all the other values will be ignored.</p><pre>postgres_enabled: false<br>global:<br>  postgresql:<br>    auth:<br>      password: pw<br>      database: data-product-portal<br>      port: &quot;!!string 5432&quot;<br>      server: data-product-portal-postgresql<br>      username: postgres</pre><h4>Database</h4><p>This configuration specifies how the portal connects to the database. If postgres_enabled: true , use the same values as above. If postgres_enabled: false, these can be any set of values necessary to connect to your database (e.g. RDS endpoints).</p><pre>database:<br>  password: pw<br>  dbname: data-product-portal<br>  port: &quot;!!string 5432&quot;<br>  server: data-product-portal-postgresql<br>  username: postgres</pre><h4>API Key</h4><p>If enabled: true, you can use the value of key as an API key in the x-key header field to authenticate your API requests.</p><pre>api_key:<br>  enabled: false<br>  key: &quot;example&quot;</pre><h4>Conveyor</h4><p>If you have a Conveyor installation available and want to link it to the portal, provide the correct API key and secret here. If not correctly configured, it will be ignored.</p><pre>conveyor:<br>  api_key: conveyor_key<br>  secret: conveyor_secret</pre><h4>Host</h4><p>This value should be the CNAME of your portal application without a trailing slash. For example https://www.portal.com.</p><pre>host: pleaseupdateme</pre><h4>Cloudwatch</h4><p>Portal can automatically log to <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html">AWS Cloudwatch Logs</a> if your pods have the correct access rights on your linked AWS account.</p><pre>cloudwatch_enabled: true</pre><h3>Optional Configuration Values</h3><p>These values can be adjusted if you have a mature Kubernetes cluster setup and want to reuse certain volumes, change deployment details, or link your cluster to specific cloud provider features with annotations. For the initial installation these do not need to be adjusted.</p><p>We might dive deeper in these configuration values in an upcoming blogpost and learn how to add annotations to your service role for automatic AWS IAM role assumption, add annotations to your ingress controller for automatic AWS ELB creation, …</p><h3>Conclusion</h3><p>The basic set of configuration values that you should change is fairly small and easy to understand. This allows you to quickly link your production services together in a seamless integration.</p><p>As always, I hope everything is clear. Feel free to contact us through <a href="https://join.slack.com/t/dataproductportal/shared_invite/zt-2ni2gp69z-tGxMHLt7u4HfR2rbdUUavQ">our Slack community</a> if you have any questions. Stay tuned for the next bog post where we might dive deeper into these optional configuration values.</p><p>See you in the next blog post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=982f4a54c0f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/conveyordata/data-product-portal-integrations-2-helm-982f4a54c0f0">Data Product Portal Integrations 2: Helm</a> was originally published in <a href="https://medium.com/conveyordata">Conveyor Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Product Portal Integrations 1: OIDC]]></title>
            <link>https://medium.com/conveyordata/data-product-portal-integrations-1-oidc-8d1dcdc0896e?source=rss-fd70f8880065------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1dcdc0896e</guid>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[data-product-portal]]></category>
            <category><![CDATA[oidc]]></category>
            <dc:creator><![CDATA[Stijn Janssens]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 13:31:02 GMT</pubDate>
            <atom:updated>2024-12-15T15:34:59.581Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to integrate Open ID Connect with the Data Product Portal</h4><p>Hi everyone! I’m excited to introduce this new blog post series to the world. I hope to share many more posts and invite you all to join me on these adventures.</p><h4>What is the Data Product Portal?</h4><blockquote>The Data Product Portal is an open-source tool designed to help organisations build and manage data products at scale. It’s intuitive, flexible, and aimed at making data product management straightforward and effective.</blockquote><p>For more information, check out our <a href="https://medium.com/conveyordata/introducing-data-product-portal-an-open-source-tool-for-scaling-your-data-products-c05cf86afbf4">announcement blogpost</a>. It covers the <em>“why, what and how” </em>of the Data Product Portal and introduces key concepts. Throughout this series, I’ll refer to the Data Product Portal as “<em>the Portal</em>”.</p><p>The Portal is <strong>open-source! </strong>Visit our <a href="https://github.com/conveyordata/data-product-portal">Github</a> and leave a star if you like what you see. You can also join <a href="https://join.slack.com/t/dataproductportal/shared_invite/zt-2lo245t3l-bJxcAz1trqrcQNnGARWMDg">our Slack community</a> to chat with us directly.</p><h4>What is This Blog Post Series?</h4><p>The Portal is designed for easy setup. Simply run docker compose up or helm install on your K8S cluster, and you’re ready to go. This will present you with a bare-bones version of Portal. However, the Portal’s functionality becomes truly exciting when integrated with other services, such as AWS for role management or OIDC for user authentication.</p><p>This blog series will guide you through various integrations for the Portal with technical examples. Topics include integrating the Portal with OIDC, linking the Portal to AWS, and connecting to Conveyor.</p><p>Following this series will help you fully utilize the Portal by integrating it with essential technologies, creating a comprehensive hub for your data professionals.</p><p>This blogpost focuses on integration with OIDC.</p><h3>Why Do You Need OIDC Integration?</h3><p>The Portal allows large-scale data access within your organization. A crucial feature is the ability to authenticate and authorize users. By verifying user identities, the Portal can securely and correctly grant access to the appropriate data products.</p><p>Without OIDC, all users will appear as “<em>John Doe</em>”, making it impossible to differentiate access rights. Enabling OIDC is the first step to making your Portal installation more useful for your entire organization.</p><h3><strong>What is OIDC?</strong></h3><blockquote>OpenID Connect (OIDC) is an identity authentication protocol that is an extension of open authorization (OAuth) 2.0 to standardize the process for authenticating and authorizing users when they sign in to access digital services.</blockquote><p>Implementing OIDC with the Portal allows you to link the Portal to your organization’s SSO or identity provider, enabling secure user sign-in and user-specific data access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4Vu8yfPOG6U3CuSClJTfg.png" /><figcaption>Secure user sign-in with AWS Cognito</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teON4E_D-NLv0WiyRzw8Yw.png" /><figcaption>With disabled OIDC, everybody logs in as John Doe automatically</figcaption></figure><h3>How to Integrate OIDC with the Portal</h3><h4>Supported Providers</h4><p>The Portal has been tested with <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html">AWS Cognito</a> but should work with other OIDC providers with minimal code changes. As an <a href="https://github.com/conveyordata/data-product-portal">open-source project</a>, contributions to support additional OIDC providers are welcome.</p><p>OIDC returns identity , refresh and access tokens. Providers may vary in the information they pass in tokens, and the application depends on this information, so integrating a new provider might require some code changes there as well.</p><p>The claims our provider is required to pass are at least email, family_name and name.</p><h4>Cognito setup</h4><p>While I won’t cover the complete setup of a Cognito user pool (you can find that <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html">here</a>), here are the key points for the Portal:</p><ul><li>Add email, family_name and name to the required_attributesin your user pool.</li><li>Create an app integration and note the client ID and secret.</li><li>Find the authority URL using the format:</li></ul><pre>https://cognito-idp.&lt;COGNITO_REGION&gt;.amazonaws.com/&lt;COGNITO_USER_POOL_ID&gt;</pre><ul><li>Set the correct callback URLs</li></ul><p>I will dive deeper into these steps below.</p><p>Portal makes use of <strong>Cognito User Pools. </strong>When creating your user pool, make sure to add at least email, family_name and name to the required_attributes. These claims are used in portal.</p><p>Your user pool will need exactly one <strong>app integration</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtY2PjLMQz05v9YSlA9zfw.png" /><figcaption>Go to the app integration tab to create a new integration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Zbyw0dvPNglZSbra0hxZg.png" /><figcaption>We need exactly one app integration</figcaption></figure><p>When you click on this app integration you can find out the client ID and secret of your app client. These values are important below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*RrKg2dNWCx3nymmy-6pXsg.png" /><figcaption>Opening the app integration shows you the Client ID and secret</figcaption></figure><p>The last value you need to find is the authority url. In case of Cognito you can create it with the following template.</p><pre>https://cognito-idp.&lt;COGNITO_REGION&gt;.amazonaws.com/&lt;COGNITO_USER_POOL_ID&gt;<br># example<br>https://cognito-idp.us-east-1.amazonaws.com/us-east-1_AB12ZQfCb</pre><p>For other OIDC providers we require the URL that hosts the .well-known/openid-configuration file of your provider.</p><h4>Callback URLs</h4><p>The Portal requires specific callback URLs allowed by Cognito. These are necessary for both local development and production deployment. Ensure the following URLs are in your allowed sign-out callback list:</p><p>For local development:</p><pre>http://localhost:3000/<br>http://localhost:3000/logout/<br>http://localhost:5050/<br>http://localhost:5050/api/auth/device/callback/</pre><p>For production (HOST is the CNAME of your application — the DNS record that maps the alias name of your application to it’s true or canonical domain name):</p><pre>https://&lt;HOST&gt;/<br>https://&lt;HOST&gt;/api/auth/device/callback/<br>https://&lt;HOST&gt;/logout/</pre><p>The following list needs to be added to the allowed sign-out callback list.</p><pre>http://localhost:3000/logout/ # For local development<br>https://&lt;HOST&gt;/logout/</pre><h3>Integrating OIDC Locally / Docker Integration</h3><h4>Backend</h4><p>When running the portal locally, most of the integration of external services happens in a .env configuration file.<br>Running docker compose up uses .env.docker by default. If you want to build your dockers locally for deploying, you need to create a .env file in the root of the project. Please refer to the <a href="https://github.com/conveyordata/data-product-portal/blob/main/backend/README.md#configuration-env-file">README</a> in backend/ for further explanation.</p><p>Make sure the following configuration values are present in the .env file used in your Docker deployment pipeline. The values can be derived from your Cognito user pool as explained above.</p><pre>OIDC_CLIENT_ID=&lt;ID&gt; # Cognito Client ID<br>OIDC_CLIENT_SECRET=&lt;SECRET&gt; # Cognito client secret<br>OIDC_AUTHORITY=&lt;AUTH_URL&gt;<br>OIDC_REDIRECT_URI=http://localhost:3000/,http://localhost:8080/ # For local dev<br>OIDC_DISABLED=false</pre><h4>Frontend</h4><p>The frontend docker used when running locally or when executing npm dev uses a config.js file. Please refer to the <a href="https://github.com/conveyordata/data-product-portal/blob/main/frontend/README.md#configuration-configlocaljs-file">README</a> in frontend/ for further explanation on how to set this up. The file should contain the following code:</p><pre>const config = (() =&gt; {<br>    return {<br>        API_BASE_URL: &quot;http://localhost:5050&quot;,<br>        OIDC_DISABLED: false,<br>        OIDC_CLIENT_ID: &quot;&lt;CLIENT_ID&gt;&quot;,<br>        OIDC_CLIENT_SECRET: &quot;&lt;CLIENT_SECRET&gt;&quot;,<br>        OIDC_AUTHORITY: &quot;&lt;AUTH_URL&gt;&quot;,<br>        OIDC_REDIRECT_URI: &quot;http://localhost:3000/&quot;,<br>        OIDC_POST_LOGOUT_REDIRECT_URI: &quot;http://localhost:3000/&quot;<br>    }<br>})();</pre><h3>Integrating OIDC in Your Production Installation</h3><p>The easiest way to deploy portal in a production environment is through <a href="https://helm.sh/">Helm</a>. You can enable OIDC in Helm by passing the following configuration in the values.yaml file provided through Helm.</p><p>Make sure your values.yaml contains the following entries.</p><pre>oidc:<br>  disabled: false<br>  client_id: &lt;client_id&gt;<br>  client_secret: &lt;client_secret&gt;<br>  authority: &lt;auth_url&gt;<br>  redirect_uri: &lt;host&gt; #including trailing /</pre><h3>Conclusions</h3><p>Setting up OIDC support for your Portal deployment is straightforward. Adjust the .env and config.local.js files for local development, or pass values in values.yaml for Helm installs.</p><p>Let me know if this tutorial was clear and feel free to reach out with questions. Join us on <a href="https://github.com/conveyordata/data-product-portal">Github</a> or in <a href="https://join.slack.com/t/dataproductportal/shared_invite/zt-2lo245t3l-bJxcAz1trqrcQNnGARWMDg">our Slack community</a>. Stay tuned for the next installment of this series!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1dcdc0896e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/conveyordata/data-product-portal-integrations-1-oidc-8d1dcdc0896e">Data Product Portal Integrations 1: OIDC</a> was originally published in <a href="https://medium.com/conveyordata">Conveyor Data</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Device Flow]]></title>
            <link>https://medium.com/datamindedbe/demystifying-device-flow-ae15854bac24?source=rss-fd70f8880065------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae15854bac24</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[device-flow]]></category>
            <category><![CDATA[cognito]]></category>
            <dc:creator><![CDATA[Stijn Janssens]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 12:57:27 GMT</pubDate>
            <atom:updated>2024-07-09T12:57:27.564Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing OAuth 2.0 Device Authorization Grant with AWS Cognito and FastAPI</h4><p>Have you ever wondered how the Netflix app on your smart TV knows which account is linked to it? Or why you should scan a QR code when the TV requires you to link to your app? In this blogpost we will dive deep into the Device Authorization Grant protocol, which is exactly what Netflix uses. We will implement this protocol ourselves from scratch.</p><p>In this blogpost we will implement OAuth Device Authorization Grant using AWS Cognito and FastAPI. At the end, you will be able to log into your app from devices with limited browser accessibility.</p><p>We implemented this flow for authenticating a Golang CLI that interacts with the Data Product Portal, our brand new open-source project. You can find more information in the <a href="https://medium.com/conveyordata/introducing-data-product-portal-an-open-source-tool-for-scaling-your-data-products-c05cf86afbf4">announcement blogpost</a> or on our <a href="https://github.com/conveyordata/data-product-portal">Github</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27uPtge1xs0xiGKGjoH-ww.gif" /><figcaption>Device Authorization Grant in action in our application, a CLI tool connecting to Data Product Portal</figcaption></figure><h3>What is Device Authorization Grant?</h3><p>The OAuth 2.0 Device Authorization Grant, is a standardized way of authorizing headless devices. Headless devices are devices with no web browsers and/or limited capability for inputting text. Authorizing with Device Authorization Grant is meant for use on devices that don’t have an easy way of entering text, such as a TV, as it stops you from having to input passwords on that device. Famous examples of Device Authorization Grant include</p><ul><li>logging into the AWS CLI (headless device) through SSO</li><li>connecting your smart TV (headless device) to your Netflix account</li><li>connecting your printer (headless device) to your printer OEM account</li></ul><p>In Device Authorization Grant, the headless device shows a QR code or a URL where the user can then complete authentication using a secondary device (like a smartphone).</p><p>In this blog post, we are going to implement a FastAPI backend for handling Device Authorization Grant with AWS Cognito.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*q7af3WDeI1rlTwr8h9sp5Q.png" /><figcaption>An Example of Netflix’s Device Authorization Grant</figcaption></figure><h3>Two flows</h3><p>A schematic representation of the full Device Authorization Grant can be found below.</p><p>The Device Authorization Grant consists of two separate parts or flows that run partially in parallel: 1) The <em>headless device flow </em>and 2) The <em>browser flow</em>.</p><p>Next to that, four different actors all play a role in the Device Authorization Grant.</p><h4>Different actors</h4><p>Before we dive into the two flows, let’s briefly discuss all the actors that play a part.</p><ul><li>User: The actor that initiates the authentication request on the headless device and performs the actual authentication on a secondary device.</li><li>Headless Device: Device that wants to be authenticated, e.g. smart TV or CLI.</li><li>Cognito: authorization server</li><li>Backend: authorization client, an API hosting the endpoints for Device Authorization Grant. This is what we will implement during this blogpost.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMEw63OPb73kdqwhnkxCBg.png" /><figcaption>Schematic representation showing the different actors and calls in Device Authorization Grant</figcaption></figure><h4>The headless device flow</h4><p>The <em>“Headless Device”</em>, such as your smart TV or CLI, will prompt you with a user code and a verification URL. We will call this the first flow, it originates from the headless device, after you make clear you want to authenticate the device, e.g. by pressing the Login button on your smart TV, or by typing the commandaws sso login.</p><h4>The <em>browser</em> flow</h4><p>The second flow is initiated by you, as the acting user, when you navigate to the verification URL, provided by the headless device flow. This can be done in a variety of ways: Netflix shows you a QR code to scan with your phone, CLIs can automatically open your browser, or you could simply retype the URL in your browser. When you load the URL you are first requested to confirm that the user code shown on the headless device matches, or you should input the provided user code yourself, and then you are required to authenticate to the API that you try to use. This authentication will in our case be handled by AWS Cognito, our OAuth identity provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Z6DMjKkLCL9l265FBXgaqw.png" /><figcaption>The User has to confirm that the code matches with the code displayed on the headless device</figcaption></figure><h4>Continuous polling by the headless device flow</h4><p>While the user is trying to authenticate in a browser, the headless device flow continues in parallel. The headless device polls the authorization client — this is the backend we will implement — to check if the authentication succeeded and when that is the case it requests the actual id, access (and optionally refresh) token from the identity provider. The backend stores different verification codes to ensure the identity provider that the original requester of the authorization codes now fetches the tokens. This polling should start immediately after the user code, device code and verification uri are created and should be done periodically (typically 5 seconds delay or less). Polling frequently enough will result in the headless device knowing quickly when it is correctly authenticated and ensures a smooth user experience.</p><p>Upon successful retrieval of the access tokens, the Device Authorization Grant is concluded. The headless device can now access your API securely by authorizing requests with a JWT Bearer token.</p><p>The full documentation and explanation of Device Authorization Grant can be found in <a href="https://datatracker.ietf.org/doc/html/rfc8628">the following RFC</a>.</p><h3>Why implement Device Authorization Grant yourself?</h3><blockquote>Our authorization server, AWS Cognito, as well as many other authorization servers, unfortunately do not support a flow for headless devices. So in this blogpost, we will implement this ourselves. As there is already a standardized, well-thought out API for this called the Device Authorization Grant, we use this as inspiration (on top of the authorization code grant, and even though we are not implementing an authorization server). This requires (temporary) state.</blockquote><p>Some OAuth clients have Device Authorization Grant ready to go with the endpoints they provide. However, if you decided on using AWS Cognito as your authorization authority, you are out of luck.</p><p>The only mention that AWS gives about Device Authorization Grant is the following <a href="https://aws.amazon.com/blogs/security/implement-oauth-2-0-device-grant-flow-by-using-amazon-cognito-and-aws-lambda/">blog post</a>, which uses JavaScript and AWS Lambda. Sure, it is a starting point, but it might not fit in your current architecture or technology stack.</p><h4>Our application and technology stack</h4><p>We have developed <a href="https://medium.com/conveyordata/introducing-data-product-portal-an-open-source-tool-for-scaling-your-data-products-c05cf86afbf4">“Data Product Portal”</a>, a data engineering tool with a web UI frontend and a FastAPI-based backend. Our tool will also be accessible through a Go CLI. This CLI is the reason we need Device Authorization Grant.</p><p>The provided code samples will assume you have a working demo application running with FastAPI, including a small database component. You can follow the <a href="https://fastapi.tiangolo.com/tutorial/">excellent documentation</a> to achieve this or look at my <a href="https://github.com/stijn-janssens/cognito-fastapi-device-flow">Github</a> for a working example.</p><p>This blog post does not cover the setup of AWS Cognito or the setup of AWS Cognito with FastAPI. We will only look at implementing Device Authorization Grant given a working AWS Cognito setup.</p><h3>Implementation</h3><p>Let’s dive into the real work. We will focus only on the relevant parts related to Device Authorization Grant. We will look specifically at implementing the Backend actor.</p><p>A full working code example, including all of the basic setups, can be found <a href="https://github.com/stijn-janssens/cognito-fastapi-device-flow">here</a>.</p><h4>Cognito setup</h4><p>We assume your application already has a working AWS Cognito setup. Basic instructions can be found <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html">here</a>. Make sure to integrate your FastAPI application as an app in your user pool. In the code below we will reference this configuration like this.</p><pre>from app.core.auth.oidc import oidc</pre><p><em>oidc</em> is a model that has the following attributes, filled in by Cognito.</p><pre>client_id<br>client_secret<br>authority<br>redirect_uri<br>configuration_url # The .well-known/openid-configuration url<br><br># These can be fetched from configuration_url<br>authorization_endpoint<br>token_endpoint<br>userinfo_endpoint<br>jwks_keys</pre><h4>Project structure</h4><p>We will create four files, following the structure FastAPI recommends when working in bigger projects:</p><ul><li>model.py This file reflects the Pydantic model in our database. We will not include this code in the blogpost. You can find an example in <a href="https://github.com/stijn-janssens/cognito-fastapi-device-flow">my Github Repo</a></li><li>schema.py This file contains the Pydantic model used by FastAPI to return responses or get request parameters. The Pydantic model is fairly simple. We will not include this code in the blogpost. You can find an example in <a href="https://github.com/stijn-janssens/cognito-fastapi-device-flow">my Github Repo</a></li><li>router.py This file defines the available API calls</li><li>service.py This file implements the functionality behind these calls</li></ul><h4>Requesting a device token on the headless device (Headless device flow)</h4><p>This call will be made from the headless device to our backend. We request a new device token. This call will generate a <em>device_code</em>, unique to our device, a <em>user_code</em> to verify in the browser and a <em>url</em> to navigate to for authentication. This looks like this in router.py<em> </em>and service.py . Code shown here is pseudo-code and only shows some relevant concepts, please refer to the Github repo for the actual full implementation.</p><pre># router.py<br>router = APIRouter(prefix=&quot;/device&quot;) # include this in your main router<br><br>@router.post(&quot;/device_token&quot;)<br>async def get_device_token(<br>    client_id: str,<br>    # During device flow we authenticate with Basic HTTP Auth to pass client ID and secret<br>    auth_client_id: Annotated[str, Depends(verify_auth_header)],<br>    scope: str = &quot;openid&quot;,<br>    db: Session = Depends(get_db_session),<br>):<br>    return DeviceFlowService().get_device_token(auth_client_id, client_id, db, scope)</pre><pre># service.py<br>class DeviceFlowService:<br>    def generate_device_flow_codes(<br>        self, db: Session, client_id: str, scope: str = &quot;openid&quot;<br>    ) -&gt; DeviceFlow:<br>        # Generate a new DeviceFlowModel<br>        # This generates the device_code, user_code for a scope<br>        # It saves the new devicecodes to the db<br>        device_flow = DeviceFlowModel(<br>            client_id=client_id,<br>            scope=scope,<br>            max_expiry=utc_now() + timedelta(seconds=1800),<br>            oidc_redirect_uri=oidc.redirect_uri,<br>            last_checked=utc_now(),<br>        )<br>        db.add(device_flow)<br>        db.commit()<br><br>        return DeviceFlow.model_validate(device_flow)</pre><h4>Browser-Backend Communication (Browser flow)</h4><p>Here we implement four possible calls.</p><ul><li>Landing page for confirming / denying a user code</li><li>The confirm call</li><li>The deny call</li><li>The callback after the user is authenticated</li></ul><pre># router.py<br><br># Base url for /device route. The landing page.<br># Show User code and allow confirm / deny by user.<br>@router.get(&quot;&quot;, include_in_schema=False)<br>async def request_user_code_processing(<br>    code: str, request: Request, db: Session = Depends(get_db_session)<br>):<br>    return DeviceFlowService().request_user_code_processing(code, request, db)<br><br># User code does not match or request was unintended. Deny the device flow<br>@router.get(&quot;/deny&quot;, include_in_schema=False)<br>...<br><br># User code matches and we want to authorize.<br>@router.get(&quot;/allow&quot;, include_in_schema=False)<br>...<br><br># Callback for after the authentication in the browser completes<br>@router.get(&quot;/callback&quot;, include_in_schema=False)<br>...</pre><pre># service.py<br>    def request_user_code_processing(<br>        self, user_code: str, request: Request, db: Session<br>    ):<br>        # Get all device flows with matching user code<br>        device_flows = db.get(DeviceFlow, user_code)<br><br>        # Make sure there is only one<br>        ...<br>        device_flow = device_flows[0]<br><br>        # Only valid state is PENDING<br>        if device_flow.status in (<br>            DeviceFlowStatus.EXPIRED,<br>            DeviceFlowStatus.AUTHORIZED,<br>            DeviceFlowStatus.DENIED,<br>        ):<br>            raise ValueError(&quot;The device code has already been expired or been used&quot;)<br>        # There is an expiry on device code requests.<br>        if utc_now() &gt; device_flow.max_expiry:<br>            device_flow.status = DeviceFlowStatus.EXPIRED<br>            db.commit()<br>            raise ValueError(&quot;User Code has expired&quot;)<br>        # User code is valid<br>        # Generate a nice screen with allow / deny buttons<br>        ...<br>        # Out of scope for this blogpost. This renders a jinja template to present the 2 buttons<br>        return HTMLResponse(...)<br><br>    # What happens when user presses deny<br>    def deny_device_flow(self, device_code: str, db: Session):<br>        device = db.get(DeviceFlowModel, device_code)<br>        device.status = DeviceFlowStatus.DENIED<br>        db.commit()<br>        return RedirectResponse(&quot;/&quot;)<br><br>    # When we allow the device flow. <br>    # First generate some code challenges,<br>    # these get passed to Cognito to ensure no tampering<br>    # We also generate a state for the device request<br>    # Afterward we redirect to Cognito for authentication.<br>    # The redirect URI after cognito authentication links back to our callback<br>    def allow_device_flow(self, client_id: str, device_code: str, db: Session):<br>        code_verifier = uuid4().hex<br>        hash = sha256(code_verifier.encode(&quot;utf-8&quot;)).digest()<br>        code_challenge = urlsafe_b64encode(hash).decode(&quot;utf-8&quot;).replace(&quot;=&quot;, &quot;&quot;)<br><br>        state = uuid4().hex<br><br>        device = db.get(DeviceFlowModel, device_code)<br>        device.authz_state = state<br>        # Code verifier is used later to check we are the original requesters for the token.<br>        device.authz_verif = code_verifier<br>        db.commit()<br><br>        return RedirectResponse(<br>            status_code=302,<br>            url=(<br>                f&quot;{oidc.authorization_endpoint}?&quot;<br>                f&quot;response_type=code&amp;client_id={client_id}&quot;<br>                f&quot;&amp;scope={device.scope}&amp;&quot;<br>                f&quot;redirect_uri={oidc.redirect_uri}api/auth/device/callback/&quot;<br>                f&quot;&amp;state={state}&amp;scope={device.scope}&amp;code_challenge_method=S256&quot;<br>                f&quot;&amp;code_challenge={code_challenge}&quot;<br>                f&quot;&amp;identity_provider={oidc.provider.name}&quot;<br>            ),<br>        )<br><br>    # Callback after cognito authentication.<br>    # Check that Cognito returned state equals saved device request state<br>    def process_authz_code_callback(self, authz_code: str, state: str, db: Session):<br>        devices = (<br>            db.query(DeviceFlowModel).filter(DeviceFlowModel.authz_state == state).all()<br>        )<br>        if len(devices) != 1:<br>            raise NonUniqueDevicecodeException()<br><br>        device = devices[0]<br>        device.authz_code = authz_code<br>        # As of now we can fetch the token back from the headless device<br>        device.status = DeviceFlowStatus.AUTHORIZED<br>        db.commit()<br>        # Some more Jinja content, out of scope.<br>        return HTMLResponse(...)</pre><h4>Fetching the JWT token (Headless device flow)</h4><p>The final call can be made from the headless device and runs in parallel with the browser-backend communication flow. After the initial request for a device code, this call will be made intermittently to the backend until it succeeds. See diagram above.</p><pre># router.py<br><br>@router.post(&quot;/jwt_token&quot;)<br>async def get_jwt_token(<br>    request: Request,<br>    client_id: str,<br>    device_code: str,<br>    grant_type: str,<br>    auth_client_id: Annotated[str, Depends(verify_auth_header)],<br>    db: Session = Depends(get_db_session),<br>):<br>    return DeviceFlowService().get_jwt_token(<br>        request, auth_client_id, client_id, device_code, grant_type, db<br>    )</pre><pre># service.py<br><br>def get_jwt_token(<br>        self,<br>        request: Request,<br>        auth_client_id: str,<br>        client_id: str,<br>        device_code: str,<br>        grant_type: str,<br>        db: Session,<br>    ):<br>        # This is the only grant type allowed for device code<br>        if grant_type != &quot;urn:ietf:params:oauth:grant-type:device_code&quot;:<br>            raise HTTPException(<br>                status_code=status.HTTP_401_UNAUTHORIZED,<br>                detail=&quot;POST Call on /jwt_token invalid: incorrect grant type&quot;,<br>            )<br>        assert self._verify_auth_header(auth_client_id, client_id)<br>        return self.fetch_jwt_tokens(request, db, device_code, client_id)<br><br>def fetch_jwt_tokens(<br>        self, request: Request, db: Session, device_code: str, client_id: str<br>    ):<br>        # Make sure there only exists a single, still valid device code request<br>        device_flow = db.get(DeviceFlowModel, device_code)<br>  <br>        ... # Same checks on validity and expiry of device flow<br>        <br>        if utc_now() &lt;= device_flow.last_checked + timedelta(<br>            seconds=device_flow.interval<br>        ):<br>            # We should not DOS our API for device code requests.<br>            device_flow.last_checked = utc_now()<br>            db.commit()<br>            raise ValueError(f&quot;Client makes too much API calls {utc_now()},\<br>                {device_flow.last_checked}&quot;)<br><br>        # This is the happy path. We still have a valid device code<br>        # and we are on time for checking the status.<br>        device_flow.last_checked = utc_now()<br>        db.commit()<br>        if device_flow.status in (<br>            DeviceFlowStatus.AUTHORIZATION_PENDING,<br>            DeviceFlowStatus.DENIED,<br>        ) or (<br>            device_flow.status == DeviceFlowStatus.AUTHORIZED<br>            and not device_flow.authz_code<br>        ):<br>            # The user has not yet authenticated, or the request has been denied.<br>            # This exception needs to be handled correctly by the headless device.<br>            # Either check again in some seconds or break off the authorization process.<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST, detail=device_flow.status<br>            )<br>        elif (<br>            device_flow.status == DeviceFlowStatus.AUTHORIZED and device_flow.authz_code<br>        ):<br>            # Happy flow, the user has correctly authenticated and all the codes match<br>            # Make a request to the cognito token endpoint.<br>            # With this request the code and verifier will be checked.<br>            # This makes sure that we are the original requesters<br>            response = httpx.post(<br>                oidc.token_endpoint,<br>                headers={<br>                    &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>                    &quot;Authorization&quot;: request.headers.get(&quot;Authorization&quot;),<br>                },<br>                data={<br>                    &quot;grant_type&quot;: &quot;authorization_code&quot;,<br>                    &quot;client_id&quot;: client_id,<br>                    &quot;redirect_uri&quot;: f&quot;{oidc.redirect_uri}api/auth/device/callback/&quot;,<br>                    &quot;code&quot;: device_flow.authz_code,<br>                    &quot;code_verifier&quot;: device_flow.authz_verif,<br>                },<br>            )<br>            # Result will be access and (optionally) refresh tokens with the scope provided in the beginning.<br>            data = response.json()<br>            self.logger.debug(data)<br>            # Expire so we can&#39;t use this device request again<br>            device_flow.status = DeviceFlowStatus.EXPIRED<br>            db.commit()<br>            return data<br>        else:<br>            raise ValueError()</pre><p>That’s it! Congratulations! You have now implemented a working OAuth Device Authorization Grant. Enjoy the ability to log in from headless devices to your API.</p><h3>Conclusion</h3><p>For a full implementation of Device Authorization Grant, visit my Github at <a href="https://github.com/stijn-janssens/cognito-fastapi-device-flow">https://github.com/stijn-janssens/cognito-fastapi-device-flow</a></p><p>Let’s briefly summarize: First of all we talked about the what, why and how of Device Authorization Grant. Secondly you have learned to implement Device Authorization Grant on your backend. In order to do that you need to implement the browser flow, the headless device flow and store authorization codes in between. You can style the look and feel of the different landing pages as you prefer. Feel free to try it out for yourself!</p><p>Make sure to refer to the <a href="https://datatracker.ietf.org/doc/html/rfc8628">official OAuth 2.0</a> and <a href="https://aws.amazon.com/blogs/security/implement-oauth-2-0-device-grant-flow-by-using-amazon-cognito-and-aws-lambda/">Cognito documentation</a> for more detailed information and further customization options.</p><p>A production-grade implementation of this Device Authorization Grant can be found in our open-source Data Product Portal. Feel free to fork our <a href="https://github.com/conveyordata/data-product-portal">Github</a>. Device authorization grant can be found <a href="https://github.com/conveyordata/data-product-portal/tree/main/backend/app/core/auth/device_flows">here.</a></p><p>Thanks for reading all the way to the end :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae15854bac24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/demystifying-device-flow-ae15854bac24">Demystifying Device Flow</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>