<?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 Nathan Meibergen on Medium]]></title>
        <description><![CDATA[Stories by Nathan Meibergen on Medium]]></description>
        <link>https://medium.com/@nmeibergen?source=rss-690544b082bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2bAyM3pqRT48sLBLGHP98g.jpeg</url>
            <title>Stories by Nathan Meibergen on Medium</title>
            <link>https://medium.com/@nmeibergen?source=rss-690544b082bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:19:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nmeibergen/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[Why I created “And Notes — &”]]></title>
            <link>https://nmeibergen.medium.com/why-i-created-and-notes-e02ffeffabea?source=rss-690544b082bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e02ffeffabea</guid>
            <category><![CDATA[notetaking]]></category>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[notes]]></category>
            <dc:creator><![CDATA[Nathan Meibergen]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 10:38:59 GMT</pubDate>
            <atom:updated>2022-07-11T10:38:59.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I created “And <em>Notes</em> — &amp;”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeccZDJmx1NXw2HkNYjOtQ.png" /></figure><p>I am a note taker, but a fairly unstructured one. I remember one day sitting down at my dining room table with over a hundred sticky notes, trying to find some structure and insights. It ended up with me stacking them neatly on top of each other and putting them back into the kitchen drawer: Let’s try again another day!</p><p>Structuring notes and finding meaning in them is hard. But I really believe that putting stuff on ‘paper’ <em>can</em> be very meaningful.</p><p>That’s why I decided to take matters into my own hands. I created the app “And Notes — <strong>&amp;</strong>”.</p><p><em>My vision is that </em><strong><em>&amp; </em></strong><em>should be simple and insightful, allow me to capture anything in my life, and help me feel in control of my notes.</em></p><p>And so I started off with 3 goals in mind:</p><ol><li><strong>Structure</strong> I believe notes intrinsically have a structure which changes and grows organically over time. I’d like to have a natural adaptable structure. My focus should be on note taking, not on structuring!</li><li><strong>Insights</strong> A bunch of notes should provide you with insights. I want to be able to ‘look’ at any cross section of my notes and ‘understand’ what they are about.</li><li><strong>High level view</strong> I want a higher level view of my notes. Something that helps me recognise my notes in an instant and discover patterns.</li></ol><h3>Structure</h3><h4>Automated Folder Structure</h4><p>In traditional note taking apps you roughly have two options. The app either requires structure or it doesn’t. If it does require structure I wish you good luck: a structure that is suitable today may be inefficient tomorrow. In my experience I always end up with one folder/tag which is called ‘to organise’, which of course never gets organised. On the other hand, you have the unstructured apps. These apps usually result in a long list of notes, maybe with a tag here and there but nothing I’d call a real structure.</p><p>That’s why I created <strong>&amp;</strong> to be hybrid. Simply add tags to a note and <strong>&amp;</strong> will determine a suitable structure. I call this the <em>Automated Folder Structure</em>. In essence it’s fairly simple: The tags that occur most frequently can be seen as the top folders. Once you filter on such a tag you can proceed to drill down into the next most frequent tags. This is a folder structure! The difference is that you did not have to make this structure, it simply happened. All you need to do is determine suitable tags for a note, which is a much easier task than creating a structure.</p><p>Looking at the example below in which I drilled down towards <strong>recipe/salad </strong>and find the next layer of folders — the specific kitchens. It is really helpful.</p><p>Notice how <strong>&amp;</strong> filters out deeper subfolders like ‘<em>dates</em>’ which is used for the <em>Delicious broccoli salad. </em>Why? Because ‘<em>dates</em>’ almost exclusively occur inside the middle eastern cuisine — at least in my recipes — and will thus be shown as a subfolder inside the folder ‘<em>middle eastern’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rHE8V10jZd_jbEbCMnQpA.png" /><figcaption><em>Automated Folder Structure</em> in action for recipes.</figcaption></figure><p><strong>General structure tip </strong>Try to create small notes instead of long notes. When creating smaller notes your tags can be more precise benefiting the Automated Folder Structure. Example: for each movie I want to watch I create a separate note. This allows me to specify the genre of the movie as a tag, resulting in a list of genres in the Automated Folder Structure.</p><h4>Actionable notes</h4><p>There is another feature that naturally improves structure in <strong>&amp;</strong>: <em>actionable notes</em>.</p><p><strong>&amp;</strong> allows you to mark your notes with an a<em>ction</em>. Actions are labels of verbs that can start with ‘<em>to’</em>, like <em>watch</em>, <em>eat</em>, <em>read</em> or <em>go-to</em>. The action will then be shown as a yellow/orange label on the note. Just like <em>eat </em>in the previous example. Once a note has become actionable you can mark it as completed.</p><p>The actions will provide a <strong>natural segmentation: </strong>at each set of filters you can directly view the underlying actions, ordered by frequency. As the amount of actions you’ll have is naturally not going to be very large you’ll get a manageable overview.</p><p>Look at the image below where I filtered on the tag ‘<em>health’</em>. Next I opened up my action list. I now immediately see all my actions related to ‘<em>health’. </em>For example,<em> </em>there are a couple of things I still want to <em>research</em>, some things to <em>google, </em>some other things to <em>buy </em>and<em> </em>things I want to <em>remind</em> myself off .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8L8_nNkpoMw872c7ueMUA.png" /><figcaption>My list of actions related to health.</figcaption></figure><h3>Insights</h3><p>The core of most note taking apps is helping you create notes. And there are many on the market that do very well. However, if you are left with questions like:</p><p><em>How many notes did I take (in a period)? —</em> <em>How productive am I? — Am I doing certain actions often enough? — What are my notes mainly about?</em></p><p>Then you might benefit from the insights that <strong>&amp;</strong> gives you.</p><h4>Insights at any cross section</h4><p>I believe insights should be core to the note taking experience. Therefore I created insights literally one swipe away from the list of notes: On the home screen you see the list of all your notes and all filter options. Allowing you to filter to a tag/action combination, loved notes, notes with an image, etc. Now simply swipe to the right and you get the insights screen for this exact filtered cross section. Here you can drill down in the charts and swipe back to see the corresponding notes whenever you want. It’s completely integrated.</p><p>At the insights screen I provide insights such as:</p><ul><li><strong>Productivity</strong><em> </em>how many notes with an action label were created and how many were completed?</li><li><strong>Writing Power</strong><em> </em>how many notes did you take over time?</li><li><strong>Distribution </strong>what are your notes about?</li></ul><p>And these can be viewed for any filtered selection of your notes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnmLTEHUWQkLC6ZEH3YYEA.png" /><figcaption>The productivity overview which is just one swipe away from your note list.</figcaption></figure><h4>Repeatable Notes</h4><p>Marking a note as <em>completed</em> is a straightforward concept. I noticed however that marking something as <em>completed</em> is often not enough. Therefore I introduce the repeatable note which allows you to mark a note as <em>done again</em>. This has two benefits.</p><ol><li>It feels very <strong>natural</strong>: say you want to read your book more frequently. Then create a note that says ‘<em>Read my book’ </em>and each time you do so, mark it as <em>repeated</em>.</li><li>It provides additional <strong>insights</strong> as it allows you to track anything! For the ‘book read’-case: You can see over time when you read your book, and maybe discover that reading your book is something you only do in the weekends.</li></ol><p>But it gets even better because it allows you to track multiple notes simultaneously. Say I want to exercise more often. Then create notes with the action label <em>exercise </em>and state what you want to do, for example, ‘do a workout in the morning’, ‘try to do a yoga every day’ or ‘going for a walk’. Now, in a single graph you can see whether you are exercising frequently enough, see the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H3_aRicjj5y9W4ZoYKuYw.png" /><figcaption>In this repeatable insight you see how many notes, marked with the action ‘<em>exercise’, were repeated over time.</em></figcaption></figure><h3>High level view</h3><p>My final goal is to create something that allows me to get a high level view of my notes that helps me recognise my notes directly and discover patterns.</p><p>This brings me to the <strong>Tag Network</strong>. When creating notes with tags, the tags used in the same note are in some sense related. Because I was using the app already for some time I had a bunch of tagged notes at my disposal. So I started to play around with algorithms to determine a network of tags that I would deem useful and insightful. I remember very vividly when I finally ‘discovered’ such algorithm. The rest of the day I took off to enjoy this milestone.</p><p>The result is an interactive tag network that you can enjoy looking at or use to identify interesting clusters and relations. But it also allows you to filter your notes: You can tap the tags or their relationships. To quickly access the Tag Network simply pull the grey lever directly above the filter bar — look at the previous images and you will see the lever, its always there.</p><p>In the figure below you see the lever pulled up, but not completely: You can still see a note. In the tag network you see all tags highlighted that occur together with the tag <em>diary</em> because we filtered on that tag. The larger and more orange the tag, the more often it occurs throughout your notes. And not surprisingly you will see clusters forming around these tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDDDflUMMI9IYwwrU9MFIA.png" /><figcaption>A part of my Tag Network. The highlighted nodes are those that occur together with the tag diary.</figcaption></figure><p>It’s just such a nice and practical view. I enjoy it every time!</p><p>For me <strong>&amp;</strong> is a game changer in my note taking experience: I finally feel comfortable in taking notes. I don’t have to bother about structure, it gives me insights and a sense of control which I never felt before. I sincerely hope that you will feel the same.</p><p>For more information about <strong>&amp;</strong> you can check our <a href="https://andnotes.app/">website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e02ffeffabea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional permissions for GraphQL, Neo4j and React]]></title>
            <link>https://nmeibergen.medium.com/conditional-permissions-for-graphql-neo4j-and-react-12289996e877?source=rss-690544b082bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/12289996e877</guid>
            <dc:creator><![CDATA[Nathan Meibergen]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 12:54:52 GMT</pubDate>
            <atom:updated>2020-12-04T18:09:32.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build conditional permissions for the GRANDstack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lNgYUDRX22tAHQTc2lSXA.jpeg" /></figure><p>If you got to this article, you are probably looking for a way to implement non-static permissions into your GRANDstack application. Permission - or scopes - are usually in the form of object:action, however in some situations that’s just not enough: what you might need is object:action <strong>if</strong> a user has some relationship to the object. This is what I call a conditional permission. It might seem like a trivial requirement. Unfortunately it is not.</p><p>In this article I’ll show you how to implement conditional permissions such that</p><ol><li>Your graphQL API is secured; and</li><li>Your REACT front-end is well integrated, that is, you don’t want to show a button to a user that is not allowed to use it!</li></ol><p>My package graphql-auth-user-directives has a new feature that allows for an easy implementation of such conditional permissions. If you haven’t used this package before I strongly advice you to first go through the basics of this package before diving into this more advanced topic. The basics are described in detail in <a href="https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790">my previous article</a>.</p><p>The starting point for this article assumes you already have an authorization flow based on JSON web tokens (JWTs) integrated for your GRANDstack application.</p><p>Feel free to immediately dive into the <a href="https://github.com/nmeibergen/rbac-demo">Github repo</a>.</p><h4>Conditional permission — an example</h4><p>Let’s start with an example of what a conditional permission is. Consider the following authorization scheme:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5962071c2c165991b5f27c0b6818f66/href">https://medium.com/media/f5962071c2c165991b5f27c0b6818f66/href</a></iframe><p>The idea behind this scheme would be such that an admin can create a new book and if he/she wants to edit <em>a</em> book he/she can. However, what if we only want to allow an admin to edit a book they created themselves? What we need is a conditional permission, let’s write this as: book:edit:isOwner. This notation implies that after the second colon we write the condition. You can read this as: an admin can edit a book <strong>if</strong> it is owner.</p><p>Next I’ll show you all the steps you need to take to implement the conditional permissions.</p><h3>Configuration</h3><p>Let’s configure the conditional permissions based on the example we just presented: I will show you how to implement a mutation to edit books, where we allow admins access if they are owner of the book.</p><h4>Create a scheme with conditional permissions</h4><p>First, update the authorization scheme to include some conditional permission as needed for your case. Below is an example of how you could implement multiple such conditions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214f2e0f457eca6648d949e042f59018/href">https://medium.com/media/214f2e0f457eca6648d949e042f59018/href</a></iframe><p>You can use capital letters if you want, or use a space of the colon, that’s all fine.</p><p>Adapt these scopes at the place where you store them, that is, if you use Auth0 to store scopes, change them there, if you use any other way of storing the scopes use that. The important thing here is that in the end the decrypted JWT token should contain scopes. I’d suggest using the approach explained in my <a href="https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790">previous article</a>, but that’s not required.</p><h4>Define your graphQL schema</h4><p>We just show an example of the editBooks mutation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5ec0d5700ed26a710e3c316ac16361e/href">https://medium.com/media/f5ec0d5700ed26a710e3c316ac16361e/href</a></iframe><p>To do this, we assume that</p><ol><li>You imported and configured the graphql-auth-user-directives package already: this allows you to use the directive @hasScope</li><li>You use the neo4j-graphql-js package, for this, among others, allows for the @cypher directive.</li></ol><p>As you can see we don’t have to specify the conditions: the package will understand that if the provided permission is book:edit it should check all conditions assigned to the user, for example, for an admin it will check isOwner and created. If any of these conditions are valid the admin will be able to access this mutation. Clearly, if you’d like to specify an exact conditional permission in the GraphQL schema you are free to do so, for example, there is nothing wrong in specifying a mutation with @hasScope(scopes:[&quot;book:edit:isOwner&quot;]) (I’m not sure when that would make sense, but the package will understand what you mean).</p><h4>Define the query for a condition</h4><p>The package graphql-auth-user-directives exports a function called conditionalQueryMap. This is a javascript Map object which as a key takes the condition and as value a function. Take the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/018d3efd91ff740f877be135f868ea90/href">https://medium.com/media/018d3efd91ff740f877be135f868ea90/href</a></iframe><p>There is a logic to this example:</p><ol><li>The key is a combination of the object in question, in this case book, and the condition, in this case isOwner. The notation will always be of the form: object:condition, where these are related to how you have defined these in your scheme — all white spaces are removed.</li><li>The value is a function that takes two arguments: the user and an objectId. The user that you’ll have at your disposal is the one that has been decoded by the JWT decoder (for more info please see my <a href="https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790">previous article</a>). The objectId is the id of the object that is under consideration. Wait, what? I know, it needs some extra explanation, see the next subsection.</li><li>The query ends with a WITH statement that defines the variable is_allowed. You <strong>must</strong> end the query that you return with a WITH statement that defines the variable is_allowed. The reason being that if you have multiple conditions that should be verified we want to do this in a single query to Neo4j. All conditions are concatenated in such fashion that if an is_allowed is found to be true for one single condition the resulting user is provided access.</li></ol><h4>On the objectId</h4><p>Let’s go back to the example of editing books if you are an owner, that is, the permission/scope books:edit:isOwner. What do we mean by objectId and what is the object under consideration? Well, when you define your graphQL schema you will define queries and mutations. For this example the editing of books will be a mutation as shown in the above defined graphQL schema. There are two things you might note in this mutation:</p><ol><li>This mutation is all about performing an action on some object. The action is editing, and the object is the book. This is also the logic that we use for the scope.</li><li>To perform this mutation we are providing an id, and it makes sense that this is the book id. This is what we mean with the objectId that is being passed into the value of the conditionalQueryMap.</li></ol><p>Usually the id is easily identifiable by the graphql-auth-user-directives because it is simply called the argument id or uid. However, maybe in your case you use another identifier. If you’d like to change the identifier you can set the following environment variable:</p><pre>export OBJECT_IDENTIFIER=&quot;&lt;your_ids&gt;&quot; # defaults to &quot;id, uid&quot;</pre><p>Note that, just as in the default case you can provide multiple identifiers, separated by a ,. The order is important in that it will first look for the first identifier followed by the second, etc.</p><h3>Integrating the permissions into your React front-end</h3><p>If you made the above configurations for your case you will have an graphQL API secured with conditional permissions, however at some point you may also want to implement these permissions into your front-end. For example: suppose again the book:edit:isOwner permission. In your front-end you might want to create a button to show the user that he/she can edit the book, but clearly, only if this user is the owner of the book. Of course, with the above configuration you already made sure that only owners can call the corresponding mutation, however the front-end should also be aware of this permission. How to proceed?</p><p>The graphql-auth-user-directives packages exposes a function to check conditional permissions. This is what enables you to verify conditional permission by creating a GrahQLquery to check permissions in the front-end. Let’s implement this.</p><p>The idea for this implementation is that we will create an access-control component, that surrounds any piece of React code that you’d like to secure. This access-control component will check whether access is granted or not. It will do so by calling a React hook. Let’s start by creating the React hook.</p><h4>Create a React hook to check permissions</h4><p>The react hook that we create can be used in the access-control, but also in places where you don’t need an access-control but merely want to know whether some permission is satisfied. The hook is called useCheckRules and is defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe5fabc3971d8651cb4d2cf6b2561bd/href">https://medium.com/media/3fe5fabc3971d8651cb4d2cf6b2561bd/href</a></iframe><p>Let’s walk through the code. We start by defining a query to verify conditional permission with Apollo. In the next subsection we will show the graphQL API for this query.</p><p>The useCheckRules hook is called with the argument action and objectId. The action refers to the <strong>non-conditional permission</strong> that you’d like to verify, for example,book:edit and the objectId refers to the id of the object in case (see the previous section), thus the id of the book in the case.</p><p>To run this hook you’ll need user information, in particular the scopes of this user. This can be the result of decoding the user with the graphql-auth-user-directives package: at initiation of your react code the user should be retrieved from the backend including its scopes. If you use Auth0, this is just a small adaption of their useAuth0 hook.</p><p>The rest of the useCheckRules hook determines whether the user has exactly the provided permission, if so, access in granted. If it is found that the user has a conditional permission related to the action, then this conditional permission is verified in the database by means of the lazy query.</p><h4>Set up the GraphQL conditional permission check API</h4><p>As seen in the previous subsection we need the graphQL endpoint called checkConditionPermission. Create this in your graphQL schema. See the below example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddacc5d44c947e7f1c9f7f7b33bfae4c/href">https://medium.com/media/ddacc5d44c947e7f1c9f7f7b33bfae4c/href</a></iframe><p>Next, define the resolver as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c6287c875b690f8d4d9b5b3dc6025c2/href">https://medium.com/media/9c6287c875b690f8d4d9b5b3dc6025c2/href</a></iframe><p>As you can see we use the function satisfiesConditionalScopes from the graphql-auth-user-directives package that performs the check on whether the user is allowed to the object that it wishes to see.</p><h4>Create the access control component</h4><p>Finally, to put everything together, create the component AccessControl. This is a simple component that uses useCheckRules to render children or some statement if no access is allowed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7403c544b4ba2c69fdcdc994839ceb9e/href">https://medium.com/media/7403c544b4ba2c69fdcdc994839ceb9e/href</a></iframe><p>To use this acces control component all you need to do is wrap the component that you want to ‘secure’ with the AccessControl component and provide information on what to do if no access is granted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eefa649e90a48fd7fdb7afb14c97577d/href">https://medium.com/media/eefa649e90a48fd7fdb7afb14c97577d/href</a></iframe><h3>That’s it!</h3><p>If you have been able to go through all coding, you’ll have created a fully integrated authorization system for your web application. This authorization system is very flexible with regards to setting up permissions for your users, see my <a href="https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790">previous article</a>, and in addition you can now handle conditional permissions in you Neo4j database.</p><p>Thank you for reading. If you have any feedback, tips&amp;tricks or need more help, let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12289996e877" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rule-based authorisation for your GraphQL server]]></title>
            <link>https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790?source=rss-690544b082bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf81bfa60790</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Nathan Meibergen]]></dc:creator>
            <pubDate>Mon, 11 May 2020 16:01:51 GMT</pubDate>
            <atom:updated>2020-12-04T16:18:10.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build role-based authorization for your GraphQL server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeqEj-TXptwN-kkaH6YZfA.jpeg" /></figure><p>Recently I started building a question answering tool with the likes of StackOverflow. As I truly believe in graph technology for many use cases, this seemed like one with great applicability. A great journey was ahead.</p><p>I won’t dive into Neo4j, nor in building a frontend (which I have done with React), nor in building the server-side code for such tool. Instead I want to focus on authorization. Authentication identifies a user and authorization determines what a user can and cannot do.</p><p>To proceed you will need a basic understanding of the following:</p><ul><li>JavaScript</li><li>GraphQL</li><li>JWT encryption</li></ul><p>If you don’t enjoy reading, feel free to dive into the my <a href="https://github.com/nmeibergen/rbac-demo">Github repo</a> instead, where you can find the working example.</p><h3>What I wanted</h3><p>Before giving you an overview of how I went about creating role-based access control (RBAC), let’s start by what I needed.</p><p>In terms of flow: Whenever a user logs into our tool I want the user to retrieve a role. Based on that role the user is assigned a set of permissions which allows this user access to specific parts of our API. Similarly, if a user does not authenticate I want to provide that user with a ‘guest’ role, which again has a set of permissions attached to it.</p><p>The logged in user has a bunch of information in the JWT token, which I want access to within my resolvers, e.g. through accessibility in the context.</p><p>I want to have the ability to change permissions and not having to wait for JWT tokens to refresh: What we sometimes see is that specific permissions are saved in the JWT token. If at some point you want a (group of) user(s) to have less permissions, you might need to wait for tokens to expire, giving you less access control when you might need it.</p><p>I want to keep a nice separation between code development and access control management. That is, I want the ability for a developer to write code and assign permission names for all pieces of the API, while someone else can, without having to change anything in the code, assign any of these permissions to the roles.</p><p>This last point is another reason to include a guest role. You might decide that if you want to leave an endpoint accessible for anyone, you’d simply provide it no permissions in your GraphQL types. However, if at some point you’d like to grant more or less access for the guest, you will need to change the GraphQL schema. To avoid this I wanted to attach permissions to all queries/mutations, and leave it to the ‘access control manager’ to decide on permissions.</p><p>To summarise, what I needed:</p><ul><li>Separating RBAC management from backend development</li><li>Ability to quickly change permissions for a role</li><li>User information throughout my whole backend application</li><li>Guest users (users that have not logged in) to have access to clearly defined pieces of the GraphQL API</li></ul><h3>High level resulting framework</h3><p>The resulting framework heavily relies on a middleware that I have created, which will be described in more detail later.</p><h4>How it will work</h4><p>A user that comes into the tool without logging in doesn’t have a JWT token. A user that does log in will have one (if authentication succeeds that is). Any such user might try to access a GraphQL query/mutation in our API that requires some permissions. The next steps should be the result of a proper setup:</p><ol><li>If a token is provided, it will decode the token and extract the role or permissions attached to the user. If no token is provided it will attach a default role to the user, say “visitor”.</li><li>If in the previous step a role was provided, the middleware will determine the permissions of this role, given a role-based authentication scheme.</li><li>A check on whether the permissions are sufficient for the particular query/mutation that the user is trying to access.</li><li>Finally the user information (if it exists) is attached to the context for further usage.</li></ol><h4>Setup steps</h4><ol><li>Attach permissions/scopes to your queries and mutations. You can add them to all of them, also those that should be visible for unauthenticated users. You may also add them to any types and/or fields.</li><li>Create a role-based authentication scheme, specifying permissions per user.</li><li>Configure the middleware to pick up the authentication scheme and JWT secret among others.</li><li>For a user, generate a token within your authentication service (Auth0 in my case) and when requesting some query/mutation hand it over to the middleware.</li></ol><p>We shall walk through these setup steps in what comes next.</p><p>A final note before diving into the code setup is that this middleware is an extension of an existing package called graphql-auth-directives. A package that does the decoding and checks permissions/roles/authentication.</p><h3>Great, but how do I implement this?</h3><p>By means of an example I’d like to show you how you can setup the above framework. The result won’t be a fully working tool for it will be lacking a frontend and an authentication service. For the authentication service I used Auth0. How that fits in should become clear soon.</p><p>But before we start, let’s setup an example Apollo GraphQL server to work with.</p><h4>Setup your GraphQL server</h4><p>For the sake of this example I will use an index.js script with the following schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f23763a3dcff01dadb93317dcf8831/href">https://medium.com/media/a5f23763a3dcff01dadb93317dcf8831/href</a></iframe><p>The schema thus allows for querying books and authors, and one may create new books. Whenever a book is created the name of the user that created it is attached to the book property addedBy.</p><h3>1. Defining permissions in your GraphQL schema</h3><p>First install the middleware package graphql-auth-user-directives. This is my extension ofgraphql-auth-directives. It is available on npm, so you can simply run yarn add graphql-auth-user-directives. To allow usage of the package we need to import the directives into the index.js file, i.e.</p><pre>import { IsAuthenticatedDirective, HasRoleDirective, HasScopeDirective } from &quot;graphql-auth-user-directives&quot;;</pre><p>Next we need to make the new directives available in our schema. To do so add the directives in your typeDefs</p><pre>directive @hasScope(scopes: [String]) on OBJECT | FIELD_DEFINITION<br>directive @hasRole(roles: [Role]) on OBJECT | FIELD_DEFINITION<br>directive @isAuthenticated on OBJECT | FIELD_DEFINITION</pre><p>and extend the schema in makeExecutableSchema so that the schema instead becomes</p><pre>const schema = makeExecutableSchema({<br>    typeDefs,<br>    resolvers,<br>    schemaDirectives: {<br>        isAuthenticated: IsAuthenticatedDirective,<br>        hasRole: HasRoleDirective,<br>        hasScope: HasScopeDirective<br>    }<br>});</pre><p>Now that we can use the directives, we will attach permissions to our scheme, that is, for this particular example we append the queries and mutations as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f5d12c12f7ce1ef70c6a0bc34a559e4/href">https://medium.com/media/5f5d12c12f7ce1ef70c6a0bc34a559e4/href</a></iframe><p>Now anyone that tries to access the queries or the mutation must have the specified permissions.</p><h3>2. Define a role-based authorization scheme</h3><p>We don’t want everyone to be able to create new books and view the authors, that should be available for admins only. To manage our role-based permissions we create a JSON file with our authorization scheme:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a9e1426df1bc1ef95cb381ec10ac33/href">https://medium.com/media/e0a9e1426df1bc1ef95cb381ec10ac33/href</a></iframe><p>Here the visitor corresponds to a user that is not authenticated. If a user is not authenticated our middleware package graphql-auth-user-directives will attach the role visitor to the user, if you’d like to name it differently you can configure the middleware to rename it, check out the configuration section below.</p><p>So, now we have</p><ol><li>permissions/scopes for all our queries and mutations, and</li><li>an authorization scheme specified in JSON format</li></ol><h3>3. Configure the middleware</h3><h4>Specify the autorisation scheme</h4><p>All that is left is for the middleware to recognise that a certain role has a set of permissions attached to them, so that based on the required permissions the middleware will only let you in if the role has the required permissions.</p><p>This is done by providing the authorization scheme as an environmental variable. As a JSON is not a very convenient form for such variables we base64 encode it. The above authorization scheme thus becomes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/075f5a00dc3025892e961a750ffa12fb/href">https://medium.com/media/075f5a00dc3025892e961a750ffa12fb/href</a></iframe><p>Now create a new environmental variable called PERMISSIONS, e.g. add</p><pre>export PERMISSION=&lt;base64 encoded authorization scheme&gt;</pre><p>Users that are not authenticated are automatically provided with the role visitor, however if in your case that is not a suitable name you can change it by specifying the environmental variable DEFAULT_ROLE.</p><h4>Add your JWT secret</h4><p>JWT authentication works by encrypting a claim, that is, information for a specific user. This encryption results in a token that can only be decrypted given a ‘secret’ code, the JWT secret.</p><p>In order for decryption to be successful within the middleware you’ll need to provide the JWT secret as an environmental variable, e.g.</p><pre>export JWT_SECRET=&lt;you secret&gt;</pre><h4>Managing your meta data, e.g. roles and scopes</h4><p>You can add roles and/or scopes to your (decrypted) token. To assign roles you can use the property name role, roles, Role or Roles. If instead you’d like to use scopes, you may call these scope, scopes, Scope, or Scopes. In some cases you will have property names formatted as a url, e.g.</p><pre>&quot;<a href="https://www.mysite.com/role">https://www.mysite.com/role</a>&quot; : &quot;admin&quot;</pre><p>The middleware can help you extract the property role if you provide role as a meta data property. If you do so it will remove the url part and attaches &quot;role&quot;: &quot;admin&quot; to your user object instead. You can let the middleware know that role is such meta data by setting adding it to your environmental variables as</p><pre>export USER_METAS=&quot;role&quot;</pre><p>To add more of these meta data, you simply provide them comma separated to the USER_METAS variable.</p><h3>4. Generate a token and let the middleware know</h3><p>I won’t spend too much into how you should generate a token as that is part of your authentication service. In my tool I have implemented Auth0 which allows you to create roles and attach these to users with an account. As a critic might note, in Auth0 you can also setup permissions, so why bother with our JSON file? Well, because</p><ol><li>We also want to manage the permissions of our visitors, those that do not have an account and</li><li>if you change permissions in Auth0, all users that are logged in already, and thus already have a token will still retain their old permissions.</li></ol><p>When a user requests a query or mutation, the middleware will need to know what role this particular user has. This is all stored in the JWT claim and therefore it should be send together with your request in the header as follows:</p><pre>Authorization: &quot;Bearer &lt;The user JWT token goes here&gt;&quot;</pre><p>Of course, if the user is not authenticated you do not need to provide a token. The middleware will understand that there is a visitor instead.</p><h3>Let’s try an example</h3><p>Configure the middleware with the following environmental variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0348bff7b33748e8497d7af4e511447c/href">https://medium.com/media/0348bff7b33748e8497d7af4e511447c/href</a></iframe><p>This sets a JWT secret and permissions as specified above. Next create a JWT token based on the following claim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eade1141d5b4262702d2746509df315a/href">https://medium.com/media/eade1141d5b4262702d2746509df315a/href</a></iframe><p>This should be encrypted with your JWT secret. You can create such JWT claim with for example an online JWT builder, see <a href="http://jwtbuilder.jamiekurtz.com/">here</a>. The token I created looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fb58944f1b4d221ec3936a3dd63b280/href">https://medium.com/media/1fb58944f1b4d221ec3936a3dd63b280/href</a></iframe><p>Now, start up your server and send the following mutation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dea97c006d31cd9079394c2c9babccf/href">https://medium.com/media/5dea97c006d31cd9079394c2c9babccf/href</a></iframe><p>You will probably get an error because you are not authenticated/authorised to perform this action, as we specified that adding books is only for admins. If now you provide the above token in your header as described in the previous section you will see that a new book is successfully created and your result should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/099aeb3af5f31e96ec8932674938dd7c/href">https://medium.com/media/099aeb3af5f31e96ec8932674938dd7c/href</a></iframe><p>Again this example is fully worked out in my Github repo <a href="https://github.com/nmeibergen/rbac-demo">here</a>.</p><h3>That’s all there is to it</h3><p>At the start of this article I specified a few of my desires and I can now show you how these are all satisfied.</p><p>First of all separation between RBAC management and backend development is guaranteed. If RBAC manager wants to provide a visitor with additional permissions, the backend developer will not have to remove scopes from the GraphQL schema, instead one can simply adapt the rule based permissions JSON instead. For example, if you’d like visitors to be able to add books in the example, simply add it to the JSON and you’re done!</p><p>And indeed, guests, or visitors, however you’d like to call them, have clearly defined permissions as specified in the permissions JSON. Instead of having to refer to the GraphQL scheme to see these permissions everything is collected in a single place.</p><p>Whenever such changes are performed these can ‘instantly be turned on’ for end users of your tool by changing the environmental variable PERMISSIONS on your server or virtual machine or however you do your hosting. In my case I use a Kubernetes cluster and therefore will have to perform a restart on my pod that hosts the GraphQL server.</p><p>Whenever authorization is successful the user information is attached to the context and can thus be used immediately in your resolver. This is also shown in the example above.</p><p><strong>Thank you for reading through, and if you have any feedback, please let me know. Writing good code is a never ending learning journey!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf81bfa60790" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/rule-based-authorisation-for-your-graphql-server-cf81bfa60790">Rule-based authorisation for your GraphQL server</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>