# Frontend Authentication Flow

In this guide you will learn what frontend expects from API response for authentication and authentication related notes.

WARNING

Provided JWT Service is for demo and inspiration purpose you might need to update it if your API response or Authentication flow is different than ours.

# Login

For login you must send email and password as POST data to your API request (It is required in our demo). In response you will get:

{
  "userData": {
    "id": 1,
    "fullName": "John Doe",
    "username": "johndoe",
    "avatar": "/img/13-small.d796bffd.png",
    "email": "admin@demo.com",
    "role": "admin",
    "ability": [
      {
        "action": "manage",
        "subject": "all"
      }
    ],
    "extras": {
      "eCommerceCartItemsCount": 5
    }
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjE3NjkyNjk2LCJleHAiOjE2MTc2OTMyOTZ9.ktkWaawSrKOmHbrke-1kCe7Ao3EkapSoh6ip12T9Slc",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjE3NjkyNjk2LCJleHAiOjE2MTc2OTMyOTZ9.V4WQWNJWStNV0NSIsyy0I_cTjQULNx0NUmsJjO3x_xU"
}

Above is what frontend expects in response of login API request. You might not need same response for your project.

Let's say you are not using eCommerceCartItemsCount than you don't need extras in that case.

Now, situation is your API response if different from what frontend expects because you removed extras. So, you have to modify frontend code (Mainly Login.vue file).

There might be another case where your login API request just send access token and refresh token on login and not user data. In this case you manually have to make another API call for getting user data in frontend. This also results in modification in frontend code (Mainly Login.vue file).

So, it is clear that there is more chances that you have to update the frontend code because your API response is different from what frontend expects.

To understand what we are doing after login, please consider understanding the code we wrote.

Talk is cheap, show me the code.

- Linus Torvalds

login() {

  // Form Validation
  this.$refs.loginForm.validate().then(success => {

    // If form validation is successful
    if (success) {

      // Make Login request using JWT request
      // NOTE: You can use axios.post() instead of JWT service
      useJwt.login({
        email: this.userEmail,
        password: this.password,
      })
        .then(response => {
          // `response.data` is response from API which is above mentioned
          const { userData } = response.data

          // Setting access token in localStorage
          // NOTE: Please check the source code to better understand JWT service
          useJwt.setToken(response.data.accessToken)

          // Setting refresh token in localStorage
          useJwt.setRefreshToken(response.data.refreshToken)

          // Setting user data in localStorage
          localStorage.setItem('userData', JSON.stringify(userData))

          // Updating user ability in CASL plugin instance
          this.$ability.update(userData.ability)

          // ? This is just for demo purpose as well.
          // ? Because we are showing eCommerce app's cart items count in navbar
          this.$store.commit('app-ecommerce/UPDATE_CART_ITEMS_COUNT', userData.extras.eCommerceCartItemsCount)

          // Redirection after login
          // ? This is just for demo purpose. Don't think CASL is role based in this case, we used role in if condition just for ease
          this.$router.replace(getHomeRouteForLoggedInUser(userData.role))
            .then(() => {
              this.$toast({
                component: ToastificationContent,
                position: 'top-right',
                props: {
                  title: `Welcome ${userData.fullName || userData.username}`,
                  icon: 'CoffeeIcon',
                  variant: 'success',
                  text: `You have successfully logged in as ${userData.role}. Now you can start to explore!`,
                },
              })
            })
        })
        .catch(error => {
          this.$refs.loginForm.setErrors(error.response.data.error)
        })
    }
  })
},

You might need to update above login method according to your API response.

# Registration

For registration you must send username, email and password because these are required by our fake db. In response you will get below:

{
  "userData": {
    "email": "peter@starkindustries.com",
    "username": "underoos",
    "fullName": "",
    "avatar": null,
    "role": "admin",
    "ability": [
      {
        "action": "manage",
        "subject": "all"
      }
    ],
    "id": 3
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNjE3Njk0MTQ0LCJleHAiOjE2MTc2OTQ3NDR9.ZjxLVrmgxKdRhiYgpSV_RuQNUn8Pbv4d7dSG37mm5Xg",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjE3NjkyNjk2LCJleHAiOjE2MTc2OTMyOTZ9.V4WQWNJWStNV0NSIsyy0I_cTjQULNx0NUmsJjO3x_xU"
}

This response is similar to login. Again, if you have any changes you need to update the code same as described in login.

As we are getting more questions and demand of Auth + ACL for our template we will make our Authentication more simpler and easy to understand in upcoming major VueJS release.

# Conclusion

For everything to work correctly, make sure you store data in localStorage properly so later it can be read correctly by other code. Otherwise make sure to update the code of writing data to localStorage and read from localStorage.

Last Updated: 11/16/2022, 12:36:59 PM