<?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 Fareed Idris on Medium]]></title>
        <description><![CDATA[Stories by Fareed Idris on Medium]]></description>
        <link>https://medium.com/@fareedidris?source=rss-82ee07d2ab3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f0ipwP1RyJbjwkgnIGDkHg.jpeg</url>
            <title>Stories by Fareed Idris on Medium</title>
            <link>https://medium.com/@fareedidris?source=rss-82ee07d2ab3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:07:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fareedidris/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[Cookie Based Authentication Using Flask and Vue.js: Part 2]]></title>
            <link>https://fareedidris.medium.com/cookie-based-authentication-using-flask-and-vue-js-part-2-bd2b47545466?source=rss-82ee07d2ab3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd2b47545466</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Fareed Idris]]></dc:creator>
            <pubDate>Fri, 14 May 2021 00:34:59 GMT</pubDate>
            <atom:updated>2021-05-14T12:34:36.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*UW7JTAbDtEt9aLY3BqZjJg.png" /></figure><p>This is part 2 of how to integrate cookie based authentication into your Flask/Vue application.</p><ul><li><a href="https://fareedidris.medium.com/cookie-based-authentication-using-flask-and-vue-js-part-1-c625a530c157">Part 1: Flask</a></li><li>Part 2: Vue.js <strong>(you are here)</strong></li><li>Part 3: Connecting your applications in a development environment</li></ul><p>This series is from the perspective of running 2 applications, one for your Vue frontend and the other your Flask backend.</p><p><strong>Disclaimer:</strong> This is not the definitive way to do this nor is it the best way. But it is 1 way of doing it so enjoy.</p><h3>Assumptions and setup</h3><p>I’ve created my Vue application using the <a href="https://cli.vuejs.org/">vue-cli</a> tool. I find it easier to work with when getting a project up and running quickly. The structure will be written from this angle.</p><p>To simplify the structure of this article, I will assume you have a basic understanding of how Vue works.</p><h3>Getting Started</h3><p>If you are using vue-cli to create your project, it should have a project structure similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs5qMgyvCg3Q3AJLutJdIg.png" /><figcaption>vue-cli default project structure</figcaption></figure><p>Vue-cli also installs <a href="https://router.vuejs.org/">vue-router</a> and <a href="https://vuex.vuejs.org/">vuex</a>, two great libraries I’ll be using in this article.</p><p>The last library you will want to install is <a href="https://github.com/axios/axios">axios</a>, a great library for working with HTTP requests. This is optional as you can simply use the JavaScript native HTTP API, <a href="https://javascript.info/fetch">Fetch</a>, but my personal preference is to use axios.</p><pre>$ npm install axios</pre><h3>Setting up axios instance</h3><p>If you’re coming from part 1, you will know I’ve created a flask API that I’m using to authenticate users. The first thing I will want to do is create an axios instance that has parameters configured to my authentication API. This essentially allows me to create a single object that can only communicate with my authentication endpoints, is decoupled from my Vue instance and I can import into any file. I can even call it something like “authService”. Neat.</p><p>I create a .env file in the root of my project, where I can store the route to my authentication endpoint.</p><pre># .env</pre><pre>VUE_APP_AUTH_URL=https://api.myapplication.com/auth // Your URL here</pre><p>The VUE_APP_* prefix is necessary, as is explained <a href="https://cli.vuejs.org/guide/mode-and-env.html#environment-variables">here</a>.</p><p>Now for the fun part. In my src/ folder I create a file for my axios instance.</p><pre># src/api.js</pre><pre>import axios from &#39;axios&#39;;<br><br>const authService = axios.create({<br>  baseURL: process.env.VUE_APP_AUTH_URL,<br>  withCredentials: true,<br>  xsrfCookieName: &#39;csrf_access_token&#39;<br>});</pre><pre>export { authService };</pre><p>I’ve created the instance with a couple parameters configured for working with cookies as well as interacting with my authentication API. For an explanation of the parameters:</p><ul><li>baseURL: This is prepended to any URLs provided to the instance</li><li>withCredentials: This determines whether cross site requests are made with credentials (see: cookies) or not. <strong>This is only necessary with cross site or cross origin requests, but since I am working with 2 separate applications (Flask + Vue) running on separate ports on my development machine, its necessary.</strong></li><li>xsrfCookieName: The name of the cookie used for storing our csrf token. This is configured in our flask application. The default is shown above but if you change it in your flask application config file, change it here too.</li></ul><p>We will look at sending requests and managing responses but as it is now the axios instance should be able to communicate with our flask application as well as handle any cookies it receives.</p><h3>Vuex Module</h3><p>I decided to use vuex to manage the state of a user and actions to handle our authentication requests. By namespacing this state and actions as a vuex module, this allows for a single file where all our main authentication interactions with our backend take place. I create a directory for my vuex store and a sub-directory for the vuex modules, removing the store.js file that came with our default vue-cli installation.</p><h4>Project Structure</h4><pre>src<br>|---assets<br>|---components<br>|---store<br>|   |---modules<br>|   |   |---auth.js<br>|   |---index.js<br>|---views<br>|---App.vue<br>|---api.js<br>|---main.js<br>|---router.js</pre><pre><strong>### src/store/index.js</strong></pre><pre>import Vue from &#39;vue&#39;;<br>import Vuex from &#39;vuex&#39;;<br>import auth from &#39;./modules/auth&#39;;<br><br>Vue.use(Vuex);<br><br>export default new Vuex.Store({<br>  modules: {<br>    auth<br>  }<br>});<br></pre><pre><br><strong>### src/store/modules/auth.js</strong></pre><pre>import { authService } from &#39;@/api&#39;<br><br>const namespaced = true;<br><br>const state = {<br>  user: {},<br>  isLoggedIn: false<br>};<br><br>const getters = {<br>  isLoggedIn: state =&gt; state.isLoggedIn,<br>  user: state =&gt; state.user<br>};<br><br>const actions = {<br>  async registerUser({ dispatch }, user) {<br>    await authService.post(&#39;/register&#39;, user)<br>    await dispatch(&#39;fetchUser&#39;)<br>  },<br>  async loginUser({ dispatch }, user) {<br>    await authService.post(&#39;/login&#39;, user)<br>    await dispatch(&#39;fetchUser&#39;)<br>  },<br>  async fetchUser({ commit }) {<br>    await authService.get(&#39;/user&#39;)<br>      .then(({ data }) =&gt; commit(&#39;setUser&#39;, data))<br>  },<br>  async logoutUser({ commit }) {<br>    await authService.post(&#39;/logout&#39;);<br>    commit(&#39;logoutUserState&#39;);<br>  }<br>};<br><br>const mutations = {<br>  setUser(state, user) {<br>    state.isLoggedIn = true;<br>    state.user = user;<br>  },<br>  logoutUserState(state) {<br>    state.isLoggedIn = false;<br>    state.user = {};<br>  }<br>};<br><br>export default {<br>  namespaced,<br>  state,<br>  getters,<br>  actions,<br>  mutations<br>};</pre><p>Whew. The usefulness of the axios instance becomes really apparent here. Instead of manually typing our authentication URL over and over again or specifying cookie specific parameters for our axios instance, we set it once and its done. We now simply specify the route we are hitting and enjoy our clean code.</p><h3>Error Handling</h3><p>You might be thinking: “But what about errors? What if the cookies have expired?”. This is where another cool feature of the axios instance come into play.</p><h4>Response Interceptors</h4><p>Due to axios being a JavaScript promise based library, for the asynchronous use case, we can intercept requests or responses before they are handled by a then or catch . This is very useful for our use case where we want to intercept a 401 Unauthorized and utilize the refresh token flow we setup in the last article or return the error.</p><p>To do this we add the following interceptor to our src/api.js file:</p><pre>const COOKIE_EXPIRED_MSG = &#39;Token has expired&#39;</pre><pre>authService.interceptors.response.use((response) =&gt; {<br>  return response<br>}, async (error) =&gt; {<br>  const error_message = error.response.data.msg<br>  switch (error.response.status) {<br>    case 401:<br>      if (!error.config.retry &amp;&amp; error_message === COOKIE_EXPIRED_MSG) {<br>        error.config.retry = true<br>        authService.defaults.xsrfCookieName = &#39;csrf_refresh_token&#39;;<br>        await authService.post(&#39;/refresh_token&#39;)<br>        authService.defaults.xsrfCookieName = &#39;csrf_access_token&#39;;<br>        return authService(error.config)<br>      }<br>      break;<br>    case 404:<br>      router.push(&#39;/404&#39;);<br>      break;<br>    default:<br>      break;<br>  }<br>  return error.response;<br>});</pre><p>Here is a breakdown of what is going on in this snippet:</p><ul><li>I intercept an error response and store the contents of the error message as a constant. Here I am looking at ‘error.response.data.msg’ for my error message. <strong>This is custom and specific to how I return errors from my flask application. You may use ‘error.response.data.message’ or ‘error.response.data.error’ depending on what you have used. Don’t blindly copy and paste!</strong></li><li>I use a switch statement to make the conditional logic for the different status codes more obvious.</li><li>I check if this error request is a retry from a previous interception and if our error message is the same as our cookie expiration message. <strong>This is hard-coded and I’ve used the default flask-jwt-extended error message as seen in the last article of this series. if you’ve changed this value in your flask configuration file, change it here too.</strong></li><li>If the conditional is true meaning this is not a retry request and the error message refers to an expired cookie, I change the retry parameter of our request config to true. I then change the xsrfCookieName parameter we set when the instance is created to refer to our refresh token instead.</li><li>I send a POST request to my refresh_token endpoint with the updated authService instance.</li><li>I then revert the xsrfCookieName change and return the error requests config, updated with our retry parameter.</li></ul><p>By doing it like this, we have our refresh tokens working and intercept requests so that they are automatically refreshed once our backend notices it has expired. There are more efficient ways of doing this, such as intercepting the cookie expiration in our flask application and returning a new cookie along with our response, all in one request. I’ll leave it to you to figure out how to integrate this. <a href="https://flask-jwt-extended.readthedocs.io/en/stable/refreshing_tokens/#implicit-refreshing-with-cookies">Here’s</a> a hint.</p><h3>Finishing Up</h3><p>We have all our pieces in place in the forms of the authService instance and our vuex store. Now we need to tie it all together in a view.</p><pre><strong>### src/views/login.vue</strong></pre><pre>&lt;template&gt;<br>  &lt;form @submit=&quot;login&quot;&gt;<br>    &lt;input v-model=&quot;username&quot; placeholder=&quot;Username&quot;&gt;<br>    &lt;input v-model=&quot;password&quot; type=&quot;password&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>  &lt;/form&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { mapActions, mapGetters } from &#39;vuex&#39;<br>export default {<br>  data: () =&gt; ({<br>    user: {<br>      username: null,<br>      password: null<br>    }<br>  }),<br>  computed: {<br>    ...mapGetters({<br>      authUser: &#39;auth/user&#39;<br>    })<br>  },<br>  methods: {<br>    ...mapActions({<br>      loginUser: &#39;auth/loginUser&#39;<br>    }),<br>    async login() {<br>      await this.loginUser(this.user)<br>        .then(() =&gt; {<br>          if (this.authUser.authenticated) {<br>            this.$router.push(&#39;/secure&#39;)<br>          } else {<br>            // Handle error<br>            this.user = {<br>              username: null,<br>              password: null<br>            }<br>          }<br>        })<br>      <br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><h3>Conclusion</h3><p>So now we have a backend that can handle authentication via cookies and a frontend that integrates with it. With this functionality in place, the series is pretty much done. The last part will be on integrating the two applications together on a development machine. Working with 2 applications in 2 languages is enough fun as it is but throw in CORS errors and browsers considering ports different origins for a whole new meaning of fun. Next time on drag…</p><h4>Resources</h4><ul><li>Axios — <a href="https://github.com/axios/axios">https://github.com/axios/axios</a></li><li>Vuex — <a href="https://vuex.vuejs.org/">https://vuex.vuejs.org/</a></li><li>Vue-router — <a href="https://router.vuejs.org/">https://router.vuejs.org/</a></li><li><a href="https://flask-jwt-extended.readthedocs.io/en/stable/refreshing_tokens/#implicit-refreshing-with-cookies">Flask-JWT-Extended’s other way of handling refresh</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd2b47545466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookie Based Authentication using Flask and Vue.js: Part 1]]></title>
            <link>https://fareedidris.medium.com/cookie-based-authentication-using-flask-and-vue-js-part-1-c625a530c157?source=rss-82ee07d2ab3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c625a530c157</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Fareed Idris]]></dc:creator>
            <pubDate>Mon, 29 Mar 2021 11:53:23 GMT</pubDate>
            <atom:updated>2022-12-09T10:21:41.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cookie Based Authentication with Flask and Vue.js: Part 1</h3><figure><img alt="A side-by-side image of the flask logo, followed by a picture of a stack of cookies" src="https://cdn-images-1.medium.com/max/1014/1*3NlPIIirjpqWTlFwf5kNWQ.png" /></figure><p>This is part 1 of how to integrate cookie based authentication into your Flask/Vue application.</p><ul><li>Part 1: Flask <strong>(you are here)</strong></li><li><a href="https://fareedidris.medium.com/cookie-based-authentication-using-flask-and-vue-js-part-2-bd2b47545466">Part 2: Vue.js</a></li></ul><p>This series is from the perspective of running 2 applications, one for your Vue frontend and the other your Flask backend.</p><p><strong>Disclaimer:</strong> This is not the definitive way to do this nor is it the best way. But it is 1 way of doing it so enjoy.</p><h3><strong>Assumptions</strong></h3><p>To simplify the structure of this article, I will make a couple assumptions about the state of your project:</p><ul><li>You are familiar with Flask and how it works</li><li>You have a database for storing user credentials such as a username and password</li></ul><h3>Getting Started</h3><p>First up is to install the libraries we will be using:</p><pre>$ pip install flask-jwt-extended</pre><p>Next, we create a blueprint for accessing authentication endpoints. This can be in a file called auth.py</p><pre># endpoints/auth.py</pre><pre>from flask import Blueprint</pre><pre>bp = Blueprint(&#39;auth&#39;, __name__, url_prefix=&quot;/auth&quot;)</pre><pre># __init__.py</pre><pre>from authApp.endpoints import auth</pre><pre>...<br>app.register_blueprint(auth.bp)</pre><h3>Authentication Flows</h3><p>Luckily, the authentication flows for both registering an account and logging in are fairly similar. The only difference would be adding a user to the database if one with the provided details does not exists during the registration flow.</p><p>When the registration endpoint is reached, we extract the new user details from the request and check if a user with those credentials already exists. If not, we create a new user model instance and add that to the database. Once the user is created the remainder of the flow is the same as logging in.</p><p>We use the Flask-JWT-Extended functions create_access_token and create_refresh_token to create those corresponding tokens. We can then create a response map using the flask jsonify function and use 2 more Flask-JWT-Extended functions, set_access_cookies and set_refresh_cookies, to store the newly created tokens in cookies and add them to the response map.</p><p>The response map is then returned to the client, completing the authentication process.</p><p>We use the werkzeug.security function generate_password_hash to hash a password because storing plaintext passwords is some pretty weak stuff.</p><pre># endpoints/auth.py</pre><pre>from flask import request, jsonify<br>from flask_jwt_extended import create_access_token, create_refresh_token, set_access_cookies, set_refresh_cookies<br>from authApp.models import User</pre><pre>...</pre><pre>@bp.route(&#39;/register&#39;, methods=(&#39;POST&#39;,))<br>def register():<br>  data = request.get_json()<br>  password = data[&#39;password&#39;]<br>  username = data[&#39;username&#39;]<br><br>  user = User.query.filter_by(username=username).first()<br>  if user is None:<br>    user = User(<br>      username=username,<br>      password=generate_password_hash(password)<br>    )<br><br>    user.add()</pre><pre>    access_token = create_access_token(identity=user.user_id)<br>    refresh_token = create_refresh_token(identity=user.user_id)<br><br>    response = jsonify()<br>    set_access_cookies(response, access_token)<br>    set_refresh_cookies(response, refresh_token)<br><br>    return response, 201<br>  else:<br>    return jsonify(message=&quot;Unable to create user.&quot;), 400</pre><pre>@bp.route(&#39;/login&#39;, methods=(&#39;POST&#39;,))<br>def login():<br>  data = request.get_json()<br>  username = data[&#39;username&#39;]<br>  password = data[&#39;password&#39;]<br>  user = User.authenticate(username, password)<br>  if user:<br>    access_token = create_access_token(identity=user.user_id)<br>    refresh_token = create_refresh_token(identity=user.user_id)<br><br>    response = jsonify()<br>    set_access_cookies(response, access_token)<br>    set_refresh_cookies(response, refresh_token)<br>    return response, 201<br>  else:<br>    return jsonify(message=&quot;Unauthorized&quot;), 401</pre><p>Logout is also fairly intuitive. Flask_JWT_Extended provides a unset_jwt_cookies function to unset jwt cookies from a response, so that’s what we do. The response to our frontend no longer contains valid authentication cookies.</p><pre>from flask_jwt_extended import unset_jwt_cookies, jwt_required</pre><pre>@bp.route(&#39;/logout&#39;, methods=(&#39;POST&#39;,))<br>@jwt_required<br>def logout():<br>  response = jsonify()<br>  unset_jwt_cookies(response)<br>  return response, 200</pre><h3>Securing Endpoints</h3><p>Once again Flask-JWT-Extended comes to the rescue. We are provided a function, jwt_required, that we use as a decorator for our endpoint functions. With this in place, requests must have a jwt token present to be able to access it, otherwise a default 401 response is returned.</p><pre>from flask_jwt_extended import jwt_required</pre><pre>@bp.route(&#39;/secure&#39;, methods=(&#39;GET&#39;,))<br>@jwt_required<br>def secured_endpoint():<br>  ...</pre><h3>Refreshing Tokens</h3><p>Refresh tokens are much longer lived tokens that are sent along with access tokens to our flask application. If a request is returned to the frontend as a 401 due to an expired token, a new request is made to a refresh endpoint where we return a new access token and use it to retry the initial request. Flask-JWT-Extended provides a more in depth explanation into how this works <a href="https://flask-jwt-extended.readthedocs.io/en/stable/refreshing_tokens/#explicit-refreshing-with-refresh-tokens">here</a>.</p><pre>from flask_jwt_extended import jwt_refresh_token_required</pre><pre>@bp.route(&#39;/refresh&#39;, methods=(&#39;POST&#39;,))<br>@jwt_refresh_token_required<br>def refresh():<br>  user_id = get_jwt_identity()<br>  user = User.query.filter_by(user_id=user_id).first()<br>  access_token = create_access_token(identity=user.user_id)<br><br>  response = jsonify()<br>  set_access_cookies(response, access_token)<br><br>  return response, 201</pre><p>We use the jwt_refresh_token_required decorator here since the access token is expired and we’re relying on the refresh token for this request. Plus we only want users to access this endpoint with a valid refresh token.</p><h3>Configuration Options</h3><p>There are a couple config options used to make everything work:</p><p>JWT_SECRET_KEY={secret_key}— Used to encode and decode jwt token. “Keep it secret. Keep it safe.”</p><p>JWT_TOKEN_LOCATION=[‘cookies’] — Well, this is a series on cookie based authentication. Flask-JWT-Extended allows storing jwt’s in other parts of a request but that’s outside the scope of this series.</p><p>JWT_COOKIE_SECURE=True— True means cookies will only be sent over an HTTPS connection. You usually want this true in production. It defaults to False, making development easier.</p><p><strong>There are a lot of useful configuration options made available by Flask-JWT-Extended, I’d highly recommend </strong><a href="https://flask-jwt-extended.readthedocs.io/en/stable/options/"><strong>checking them out here</strong></a><strong>.</strong></p><h3>Conclusion</h3><p>So far what we have is an API that accepts user credentials, validates them and creates authentication tokens that are stored in cookies. So far so good. Next is to handle our login and token refresh flows on the frontend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c625a530c157" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>