<?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 Bono on Medium]]></title>
        <description><![CDATA[Stories by Bono on Medium]]></description>
        <link>https://medium.com/@bono1567?source=rss-c2bc4770d0ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vQo-ky5XD7-TnrxDwPrA5A.png</url>
            <title>Stories by Bono on Medium</title>
            <link>https://medium.com/@bono1567?source=rss-c2bc4770d0ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:35:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bono1567/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[Authentication with Dagster Web-server (without Dagster Cloud)]]></title>
            <link>https://medium.com/@bono1567/authentication-to-dagster-web-server-without-dagster-cloud-f85f55e7b7af?source=rss-c2bc4770d0ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85f55e7b7af</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dagster]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[starlette]]></category>
            <dc:creator><![CDATA[Bono]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 22:44:57 GMT</pubDate>
            <atom:updated>2024-03-15T12:00:17.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPS5sdIQY6LMLaVh-bhlvA.png" /><figcaption>Source: <a href="https://dagster.io/brand">Dagster Brand: How to use the Dagster brand assets</a></figcaption></figure><p>Many Dagster open-source enthusiasts may desire to incorporate a login functionality into their Dagster UI. This guide demonstrates the steps to achieve this. <a href="https://dagster.io/lp/dagster-cloud-trial?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=20994091624&amp;utm_content=159889033153&amp;utm_term=dagster%20cloud&amp;gad_source=1&amp;gclid=Cj0KCQjwwMqvBhCtARIsAIXsZpZgxQSQ6i-V7BqyeL6Ow8HkACiEZv7HzXzEhDpoASuqpCQsPlI40aQaAqOREALw_wcB">Dagster cloud</a> offers a Single Sign-On (SSO) feature, albeit at a cost. The tutorial also covers creating a login page and implementing user access restrictions to prevent unauthorized execution of runs from inaccessible codebases.</p><p>Dagster webserver is a Starlette solution and a lot of what has been mentioned in this article has been reused: Starlette-Login</p><blockquote>This article does not cover uploading your version of dagster-webserver to any Python package index.</blockquote><p>Prerequisites:</p><p>- Now what is dagster: <a href="https://docs.dagster.io/getting-started?_gl=1*1dwnn9q*_ga*MTE0NDM5ODgxOC4xNzA3MTY0OTM0*_ga_84VRQZG7TV*MTcxMDQ1NTEzMS4yLjEuMTcxMDQ1NTE5OC42MC4wLjA.*_gcl_aw*R0NMLjE3MTA0NTUxNDEuQ2owS0NRand3TXF2QmhDdEFSSXNBSVhzWnBaZ3hRU1E2aS1WN0JxeWVMNk93OEhrQUNpRVp2N0h6WHpFaERwb0FTdXFwQ1FzUGxJNDBhUWFBcU9SRUFMd193Y0I.*_gcl_au*MjAzNDExOTY4MC4xNzEwNDQzOTgw">Welcome to Dagster! | Dagster Docs</a><br>- Download/clone the Dagster open-source codebase: <a href="https://github.com/dagster-io/dagster">Dagster (github.com)</a><br>- Python 3.8 -3.12 (I’m using 3.11)</p><p><strong>STEPS:</strong></p><ol><li>In the Dagster code base go to <br><em>dagster-master\python_modules\</em></li><li>Open <em>dagster-webserver</em> in your IDE.</li><li>I would highly suggest you create a <a href="https://docs.python.org/3/library/venv.html">virtual environment</a> in the project folder for this: <br><em>python -m venv venv</em></li><li>Activate the <em>venv.</em></li><li><em>pip install Starlette-Login</em></li><li><em>pip install dagster-webserver <br></em>We do this to get the UI section of the code.</li><li>If you wish to use the <a href="https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable">yarn</a> to install the UI use the <em>build_js.sh</em> script. If you do so skip to step 10.</li><li>Once thats complete go to /venv/Lib/dagster-webserver</li><li>Copy the <em>webapp </em>directory to the dagster-webserver folder.</li><li>Add a python file <em>user.py. </em>Your folder structure should resemble this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*LGOestFjAOKqTmMKKG0QaQ.png" /></figure><p>11. Add this to the <em>user.py</em> file (same as: <a href="https://starlette-login.readthedocs.io/en/stable/">Starlette-Login</a>):</p><pre>import typing<br>from dataclasses import dataclass<br><br>from starlette.requests import Request<br>from starlette_login.mixins import UserMixin<br><br>@dataclass<br>class User(UserMixin):<br>    identifier: int<br>    username: str<br>    password: str = &#39;password&#39; <br>    &quot;&quot;&quot; High suggest never to store password in server cahce/memory<br>    instead store in a DB or have an auth API. <br>    In the server you just want to link the session with the user<br>    &quot;&quot;&quot;<br><br>    def check_password(self, password: str):<br>        return self.password == password<br><br>    def operation_check(self, operation: str):<br>    &quot;&quot;&quot;<br>     This is the section to put checks around each GraphQl op <br>      that the user can perform.<br>    &quot;&quot;&quot;<br>        if self.username != &quot;admin&quot;:<br>            if &quot;run&quot; in operation:<br>                return False<br>        return True<br><br>    @property<br>    def is_authenticated(self) -&gt; bool:<br>        return True<br><br>    @property<br>    def display_name(self) -&gt; str:<br>        return self.username<br><br>    @property<br>    def identity(self) -&gt; int:<br>        return self.identifier<br><br><br>class UserList:<br>    def __init__(self):<br>        self.user_list = []<br><br>    def dict_username(self) -&gt; dict:<br>        d = {}<br>        for user in self.user_list:<br>            d[user.username] = user<br>        return d<br><br>    def dict_id(self) -&gt; dict:<br>        d = {}<br>        for user in self.user_list:<br>            d[user.identity] = user<br>        return d<br><br>    def add(self, user: User) -&gt; bool:<br>        if user.identity in self.dict_id():<br>            return False<br>        self.user_list.append(user)<br>        return True<br><br>    def get_by_username(self, username: str) -&gt; typing.Optional[User]:<br>        return self.dict_username().get(username)<br><br>    def get_by_id(self, identifier: int) -&gt; typing.Optional[User]:<br>        return self.dict_id().get(identifier)<br><br>    def user_loader(self, request: Request, user_id: int):<br>        return self.get_by_id(user_id)</pre><p>12. Open the <em>graphql.py</em> file. This is the file where the parent Starlette server is defined and the <strong>GraphQLWS </strong>class is inherited by the <strong>DagsterWebserver</strong>.</p><p>13. Make the following adjustments:</p><pre>from .user import UserList<br>from starlette.middleware.sessions import SessionMiddleware<br>from starlette_login.login_manager import LoginManager<br>from starlette_login.backends import SessionAuthBackend<br>from starlette_login.login_manager import LoginManager<br>from starlette_login.middleware import AuthenticationMiddleware</pre><p>Add a few lines to make the constructor look like this:</p><pre>def __init__(self, app_path_prefix: str = &quot;&quot;):<br>        self._app_path_prefix = app_path_prefix<br><br>        self._graphql_schema = self.build_graphql_schema()<br>        self._graphql_middleware = self.build_graphql_middleware()<br>        self._user_list = UserList()<br>        # Adding dummy users, not gonna happen in real-life :)<br>        user_list.add(User(identifier=1, username=&#39;user1&#39;, password=&#39;password&#39;))<br>        user_list.add(User(identifier=2, username=&#39;user2&#39;, password=&#39;password&#39;))<br>        self._login_manager = LoginManager(redirect_to=&#39;login&#39;, secret_key=&#39;secret&#39;)<br>        # Suggestion: randomly generate the secret key everytime the server starts.<br>        self._login_manager.set_user_loader(self._user_list.user_loader)</pre><p>Add the middleware for creating sessions and managing log in.</p><pre>def create_asgi_app(<br>        self,<br>        **kwargs,<br>    ) -&gt; Starlette:<br>        app = Starlette(<br>            routes=self.build_routes(),<br>            middleware=self.build_middleware() + [<br>                    Middleware(SessionMiddleware, secret_key=&#39;secret&#39;),<br>                    Middleware(<br>                        AuthenticationMiddleware,<br>                        backend=SessionAuthBackend(self._login_manager),<br>                        login_manager=self._login_manager,<br>                        allow_websocket=False,<br>                    )<br>                    ],<br>            **kwargs,<br>        )<br>        app.state.login_manager = self._login_manager<br>        return app</pre><p>14. Now we move to the <em>webserver.py </em>file. Here we will define the login page and add routes to login and logout.</p><pre>from urllib.parse import parse_qsl<br><br>from starlette.requests import Request<br>from starlette.responses import (<br>    RedirectResponse, HTMLResponse, PlainTextResponse<br>)<br><br>from starlette_login.decorator import login_required<br>from starlette_login.utils import login_user, logout_user<br><br><br>HOME_PAGE = &quot;You are logged in as {{ user.username }}&quot;<br>LOGIN_PAGE = &quot;&quot;&quot;<br>&lt;h4&gt;{error}&lt;h4&gt;<br>&lt;form method=&quot;POST&quot;&gt;<br>&lt;label&gt;username &lt;input name=&quot;username&quot;&gt;&lt;/label&gt;<br>&lt;label&gt;Password &lt;input name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/label&gt;<br>&lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>&lt;/form&gt;<br>&quot;&quot;&quot;<br># Feel free to change and imporve the styling of the LOGIN PAGE</pre><p>Now define the login and the logout page behaviour within the <strong>DagsterServer </strong>class.</p><pre>async def login_page(self, request: Request):<br>        error = &#39;&#39;<br>        if request.user.is_authenticated:<br>            return self.index_html_endpoint(request)<br>        if request.method == &#39;POST&#39;:<br>            body = (await request.body()).decode()<br>            data = dict(parse_qsl(body))<br>            user = self._user_list.get_by_username(data[&#39;username&#39;])<br>            if not user:<br>                error = &#39;Invalid username&#39;<br>            elif user.check_password(data[&#39;password&#39;]) is False:<br>                error = &#39;Invalid password&#39;<br>            else:<br>                await login_user(request, user)<br>                return self.index_html_endpoint(request)<br>        return HTMLResponse(LOGIN_PAGE.format(error=error))<br><br>async def logout_page(self, request: Request):<br>        if request.user.is_authenticated:<br>            content = &#39;Logged out&#39;<br>            await logout_user(request)<br>            return self.index_html_endpoint(request=request)<br>        else:<br>            content = &#39;You not logged in&#39;<br>        return PlainTextResponse(content)</pre><p>Include the login required decorator. While I’m specifically applying it to the index function, I highly recommend extending its use to other functions such as those handling web sockets and additional functionalities within your application.<br>For web-socket you can use — @<strong>ws_login_required</strong>:</p><pre>@login_required<br>    def index_html_endpoint(self, request: Request):</pre><p>Add the log-in and the log-out page to the router in <em>def</em> build_routes(<em>self</em>)</p><pre>[<br>Route(&#39;/login&#39;, self.login_page, methods=[&#39;GET&#39;, &#39;POST&#39;], name=&#39;login&#39;),<br>Route(&#39;/logout&#39;, self.logout_page, name=&#39;logout&#39;),<br>]</pre><p>15. Testing your changes:</p><p>Move back to the project folder where the setup.py is located and execute:</p><pre>pip install .</pre><p>Once that&#39;s complete:</p><pre>cd dagster_webserver_tests<br>dagster dev</pre><p>You should see that the server has started:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlojlCg3ndIRyr730nmowA.png" /></figure><p>Clicking on the link will give you a login page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*n4kOWTBpCiUihRZP-8-xjA.png" /></figure><p>The next section is how to restrict operations based on users.</p><h3><strong>OPERATION RESTRICTION</strong></h3><p>Before we move any further, I will briefly explain how the UI interacts with dagster-webserver.</p><p>Dagster-webserver operates as a GraphQL server. Requests are formatted in the <a href="https://graphql.org/">GraphQL</a> query language (further details can be found in the provided link).</p><p>One key benefit is the ability to access all data from a <em>single endpoint </em>(making life easier for us). The schemas are outlined in the <em>dagster-graphql</em> library, serving as a foundation for user filtering mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdRSUkId4xPbH9li2ypmng.png" /><figcaption>Dagster GraphQL query/ payload</figcaption></figure><p>I won’t delve into the specifics now, but I’ll indicate where adjustments should be made.<br>- In the <em>webserver.py</em> file, in the GraphQL endpoint (remember single endpoint):</p><pre>async def graphql_http_endpoint(self, request: Request):<br>        &quot;&quot;&quot;Fork of starlette GraphQLApp.<br><br>        Allows for:<br>        * our context type (crucial)<br>        * our GraphiQL playground (could change).<br>        &quot;&quot;&quot;<br>        .... Skip to this section ......<br>        ...  <br>            except json.JSONDecodeError:<br>                return PlainTextResponse(<br>                    &quot;Malformed GraphQL variables. Passed as string but not valid&quot;<br>                    f&quot; JSON:\n{variables}&quot;,<br>                    status_code=status.HTTP_400_BAD_REQUEST,<br>                )<br>        <br>        # Check access to the dag job here.<br>        if request.session[&#39;id&#39;]:<br>            user = self._user_list.get_by_id(request.session[&quot;id&quot;])<br>            if not user.operation_check(operation_name) #This was defined earlier:<br>                return HTMLResponse(&quot;Not Authorized&quot;, status_code=401)<br><br>        .......</pre><p>Now you can tailor your solution around this.</p><h3>NEXT STEP</h3><p>Maybe add it to the open-source code?<br>If any “dagster dev”s (unintentional pun) reading this please to share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85f55e7b7af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>