<?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 Zoltan Arvai on Medium]]></title>
        <description><![CDATA[Stories by Zoltan Arvai on Medium]]></description>
        <link>https://medium.com/@zoltanarvai?source=rss-ba2ae61e3a1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3PUBO-2-zeGdUwuEURQbLA.jpeg</url>
            <title>Stories by Zoltan Arvai on Medium</title>
            <link>https://medium.com/@zoltanarvai?source=rss-ba2ae61e3a1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:02:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zoltanarvai/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[API authentication with Phoenix, Auth0 and Guardian — Part 2]]></title>
            <link>https://medium.com/@zoltanarvai/api-authentication-with-phoenix-auth0-and-guardian-part-2-f76797327251?source=rss-ba2ae61e3a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f76797327251</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Zoltan Arvai]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 22:58:11 GMT</pubDate>
            <atom:updated>2019-03-23T22:58:11.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>API authentication with Phoenix, Auth0 and Guardian — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*wRJhx44mb2sBR10g7FEGDg.jpeg" /><figcaption>Machine to Machine authentication has it’s complexities</figcaption></figure><p>In <a href="https://medium.com/@zoltanarvai/api-authentication-with-phoenix-auth0-and-guardian-part-1-43797eac4bda">Part 1</a> we explored why we want to use Auth0, username and password to acquire a token for authenticating with APIs in Machine to Machine communication typically across system boundaries. We also built a sample application to sign in and acquire a token.</p><p>In this article we’ll configure Guardian and use the token to validate our user as part of our Phoenix request pipelines and create an identity.</p><h3>Setting up Guardian</h3><p>Typically clients will send an HTTP request using the Authorization HTTP header in such format:</p><pre># HTTP header<br>Authorization: Bearer JWT_TOKEN_GOES_HERE</pre><p>Once the header is sent we need to:</p><ul><li>(Optional) Check if the token is backlisted / revoked</li><li>Decrypt the token</li><li>Validate the structure of the token</li><li>Validate the Signature of the token</li><li>Check the expiry</li><li>Assign the newly acquired identity to the request</li></ul><p>I don’t know about you, but I definitely don’t want to implement and test such functionality. Lucky for us there are quite a few libraries out there that’ll do this for us. One of the more popular ones is <a href="https://hex.pm/packages/guardian"><strong>Guardian</strong></a>.</p><p>Using Guardian is pretty simple. We need to configure the Guardian module with the algorithm, audience and the secret key, so it can validate the signature. Now there is a tricky bit here. Guardian will try to extract the “resource” from the claims. This resource could be a user, that based on the subject you load from your User DB or something along these lines. In our demo case we’ll just build a simple Identity object that wraps the user Id.</p><p>The Identity could look like the following, but again, this can easily be any implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/923cd88c8b72a9e175df44e7f817960f/href">https://medium.com/media/923cd88c8b72a9e175df44e7f817960f/href</a></iframe><p>Now we need to get Guardian to build this identity from the token’s claims. We can easily achieve this by creating a custom Guardian module with a callback function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85aab40b45f17bd021ef777947bea7c0/href">https://medium.com/media/85aab40b45f17bd021ef777947bea7c0/href</a></iframe><p>The exciting part is the resource_from_claims function. The function parameter is the claim object which has the subject field. In case of Auth0 this has the format of auth0|id. We match on the pattern and return theIdentity with the id.</p><p>Now we have the Auth.Guardian module, time to configure it. Add the following in your dev.ex config file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11aa879c5288b98ae9a2404bf4d2a351/href">https://medium.com/media/11aa879c5288b98ae9a2404bf4d2a351/href</a></iframe><p>With the configuration above we make sure that:</p><ul><li>we are using our custom Guardian module</li><li>we use the buil-in JWT module for token verification</li><li>we also verify the issuer</li><li>we verify the signature</li></ul><p>We have one last thing to do. Setup a pipeline for authenticated requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23d8e5875236147daf79fcf9bb8edf65/href">https://medium.com/media/23d8e5875236147daf79fcf9bb8edf65/href</a></iframe><p>We define a set of plugs:</p><ul><li><strong>VerifyHeader</strong> — to make sure that the authorisation HTTP header is in place with the right format. In our case it’ll check if the header has the “Bearer xyz” value</li><li><strong>EnsureAuthenticated</strong> — to make sure a valid token has been provided and it has been verified successfully</li><li><strong>LoadResource</strong> — we’ll try to load the resource after the token has been validated. In our example the custom guardian module has the resource_from_claims method implemented to return the identity based on the subject inside the claim.</li><li><strong>assign_current_identity</strong> — Finally we’ve added a custom plug, that makes sure the the loaded resource is available on conn.assigns under the :current_identity key.</li></ul><p>There is one more thing worth mentioning here. The error handler configured during use Guardian.Plug.Pipeline. This module simply handles errors happening during the pipeline and verification process. See the <a href="https://github.com/zoltanarvai/orders-sample"><strong>order-samples</strong></a><strong> </strong>repository for more information on how to implement the handler.</p><p>Now that we have Guardian set up, we can simply define and use a private pipeline for authenticated requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85c46eeeca98a0eaf04192460e3224cb/href">https://medium.com/media/85c46eeeca98a0eaf04192460e3224cb/href</a></iframe><p>It’s that simple :) If you wan’t to see the full example with tests please visit the <a href="https://github.com/zoltanarvai/orders-sample">order-samples GitHub repo.</a></p><p>In Part 3 we’ll look at limiting access based on authorisation rules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f76797327251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API authentication with Phoenix, Auth0 and Guardian — Part 1]]></title>
            <link>https://medium.com/@zoltanarvai/api-authentication-with-phoenix-auth0-and-guardian-part-1-43797eac4bda?source=rss-ba2ae61e3a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/43797eac4bda</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[auth0]]></category>
            <dc:creator><![CDATA[Zoltan Arvai]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 22:49:05 GMT</pubDate>
            <atom:updated>2019-03-23T22:59:54.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>API authentication with Phoenix, Auth0 and Guardian — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*wRJhx44mb2sBR10g7FEGDg.jpeg" /><figcaption>Machine to Machine authentication has complexities too</figcaption></figure><p>It’s quite a common scenario that we are building an API that’ll be consumed by external applications and clients (machine to machine) who want to integrate with our backend. In many cases authentication and authorisation is an important element of this integration. When the OAuth flow is just too complex and inconvenient / not a viable solution the old username / password authentication method can still shine (especially when another API is consuming ours).</p><p>So what do we want?</p><ul><li>Authenticate calls to make sure our APIs are only accessed through the appropriate credentials</li><li>Make sure with every request that the resource can be accessed by the caller</li><li>Control the level of access to certain operations (read / write / manage, etc.)</li><li>Capability to revoke access to a compromised token</li><li>A secure and reliable solution end to end</li></ul><p>If you don’t need the above functionality then rolling your own implementation might be fine, however in my experience with production grade public APIs the requirements above are quite common.</p><p>So what are we going to build?</p><ul><li>We’ll implement an API with a sign-in endpoint that’ll use Auth0 to authenticate users and issue JWT tokens with appropriate claims (Part 1)</li><li>We’ll use this token to issue requests to our APIs, and use Guardian to verify it (<a href="https://medium.com/@zoltanarvai/api-authentication-with-phoenix-auth0-and-guardian-part-2-f76797327251">Part 2</a>)</li><li>Use Plugs and Guardian to limit resource access based on permissions (Part 3)</li></ul><p><strong>Side note:</strong> I’ll assume you are somewhat familiar with Elixir, Phoenix and Plugs, so I’ll focus on explaining on how to integrate Guardian and Auth0 into your Phoenix app</p><p>If you want to jump directly to the solutions, you can find the repository <a href="https://github.com/zoltanarvai/orders-sample">here.</a></p><h3>Setting up Auth0</h3><p><a href="https://auth0.com/">Auth0</a> is a fully managed identity solution. It manages storing users and credentials, metadata in a secure way. It deals with authentication, managing and issueing tokens while providing scale and high availability.</p><p>After signing up, setup our API application in Auth0:</p><ul><li>Create a new API called OrdersSample</li><li>Use <strong>HS256</strong> signing algorithm (os RS256, however using the PK will be different in this case)</li><li>Add a new permission: read:orders</li><li>Make a note of your Signing Secret (API page), ClientID and Client Secret (Application page)</li><li>On the Test Application Settings page, at the bottom, select Advanced Settings and <strong>choose Password inside Grant Type</strong>s. (see picture below)</li><li>Create a new user on the Users &amp; Roles page, <strong>assign the permission read:orders</strong> from OrdersSample.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e_-S2P-5JrdyUV62XQ2Jg.png" /><figcaption>Make sure to enable Password grant type</figcaption></figure><p><strong>Side note:</strong> In the background Auth0 has setup a connection (to a database) to store users and credentials, a connected test application for your API that defines the ClientID and the Client Secret. You can configure this to your needs, use an external database, define password policies, roles, etc.</p><p>Ultimately you want to see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48hq0Z2nUsC-lRutwX1GLg.png" /><figcaption>Configure user on the OrdersSample API with permission read:orders</figcaption></figure><p><strong>Side note:</strong> Auth0 recommends that machine to machine authentication should be using the Auth0 tenant directly to obtain the access token. This is an OK approach when this is happening between APIs within the same system / company. When the partner who uses the API is external then having a proxy API which owns the ClientID and ClientSecret is a much safer approach. Additionally Guardian can use its own database to blacklist access tokens. Having this control “in-house” will pay off. However if this is not something you want to do you can skip the section about Sign-In with Auth0 and jump to Part 2.</p><h3>Setting up your Phoenix application</h3><p>After you generate your <a href="https://phoenixframework.org/">Phoenix</a> application, include the <a href="https://hexdocs.pm/guardian/introduction-overview.html">Guardian</a> library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f4c551614d8b5890b7a9c9d7f849a8f/href">https://medium.com/media/6f4c551614d8b5890b7a9c9d7f849a8f/href</a></iframe><p>Now you need to create a configuration for accessing Auth0 to be able to log in. <strong>The values for production should be in environment variables</strong>, for development and testing purposes it’s fine to hard-code them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd5d5de05af9c7ca45d3795c3c007a61/href">https://medium.com/media/dd5d5de05af9c7ca45d3795c3c007a61/href</a></iframe><h3>Implementing Sign-In with Auth0</h3><p>In this section we’ll create the following components:</p><ul><li>Credentials module to define a schema for username / password and validate it</li><li>TokenResult module to encapsulate the access_token and the expires_in fields</li><li>Auth module to call Auth0 APIs and perform login. Accepts a Credentialsstruct and returns a TokenResult struct.</li></ul><p>Let’s start with the Credentials module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9eccf77783e1ee5616208221b759cb/href">https://medium.com/media/9d9eccf77783e1ee5616208221b759cb/href</a></iframe><p>This needs some explanations :)</p><ul><li>We are using embedded_schema that is great for input validations with Phoenix. Basically we get a struct on steroids. We need to turn off setting primary keys because by default an id field is added.</li><li>Unfortunately embedded schemas don’t define typespecs so we need to do that manually.</li><li>Inside the validate function, apply_action(:insert} applies the changeset to the map and outputs the {:ok, %Credentials{}}tuple. Without invoking this function we get back the changeset instead. In case of errors we get the changeset in the {:error, %Ecto.Changeset{}}tuple.</li><li>Passwords sent to our APIs are Base64 encoded so we need to decode and validate the password.</li></ul><p>Let’s see the TokenResult:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af4a918d5bee20f0a9a9b07620014c1/href">https://medium.com/media/1af4a918d5bee20f0a9a9b07620014c1/href</a></iframe><p>This module is fairly straightforward. It has some type specifications and two fields that we need at the moment: access_token and expires_in. Later to make our solution more robust we could also support refresh tokens. However in practice in case of API integrations periodic logins and caching the token is more then enough by the client-side.</p><p>Now let’s see the Auth module, that talks to Auth0:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35b5b4248cef040c9831ffe5964c054/href">https://medium.com/media/d35b5b4248cef040c9831ffe5964c054/href</a></iframe><p>So what’s happening here?</p><ul><li>In sign_in/1 we call Auth0 using HTTP. Inside build_payload we need to prepare the payload for the <a href="https://auth0.com/docs/api/authentication#resource-owner-password">Resource Owner Password</a> authentication flow.</li><li>We expect errors 401, 403 and everything else. 403 can be returned when we don’t have access to a given scope, that we consider a :forbidden scenario. Everything else we can translate as :unauthorized while providing a bit more context on the error in our logs</li><li>In case of a successful response we just take the access_token and expires_in fields and return the TokenResult</li></ul><p>All we need now is to define the usual stuff: routes, controllers, view. I’ll leave this bit of code up to you, I’ll show you the controller code, alternatively you can pull the entire project (with tests!) from GitHub. See link at the top.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1010297748cc95909f45efa11059138/href">https://medium.com/media/b1010297748cc95909f45efa11059138/href</a></iframe><h3>Troubleshooting</h3><p>At this point your app should be working correctly. In case Auth0 returns you the following error:<em> 403, “Authorization server not configured with default connection.”:</em></p><ul><li>Go to your<strong> Account / Settings / General</strong>, then for the <strong>Default Directory</strong> add the connection name that has been used for you application. In my case it’s called: <strong>Username-Password-Authentication</strong><em>. </em>Hit save, and you should be good to go.</li></ul><p>In <a href="https://medium.com/@zoltanarvai/api-authentication-with-phoenix-auth0-and-guardian-part-2-f76797327251">Part 2</a> we’ll explore how to use Guardian to validate the token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43797eac4bda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>