Authentication In Vue.js — Smashing Magazine

NavBar.vue And App.vue Components

In your src/components folder, delete the HelloWorld.vue and a new file called NavBar.vue.

This is the component for our navigation bar, it links to different pages of our component been routed here. Each router link points to a route/page on our app.

Vuex Configuration with Axios

Axios is a JavaScript library that is used to send requests from the browser to APIs. According to the Vuex documentation;

“Vuex is a state management pattern library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.”

What does that mean? Vuex is a store used in a Vue application that allows us to save data that will be available to every component and provide ways to change such data. We’ll use Axios in Vuex to send our requests and make changes to our state (data).

To deal with Vuex resetting after refreshing we will be working with vuex-persistedstate, a library that saves our Vuex data between page reloads.

npm install --save vuex-persistedstate

Now let’s create a new folder store in src, for configuring the Vuex store. In the store folder, create a new folder; modules and a file index.js. It’s important to note that you only need to do this if the folder does not get created for you automatically.

import Vuex from 'vuex';
import Vue from 'vue';
import createPersistedState from "vuex-persistedstate";
import auth from './modules/auth';

// Load Vuex
Vue.use(Vuex);
// Create store
export default new Vuex.Store({
  modules: {
    auth
  },
  plugins: [createPersistedState()]
});

Here we are making use of Vuex and importing an auth module from the modules folder into our store.

Похожее:  Продвинутое использование

Defining Routes

In our router/index.js file, import our views and define routes for each of them

Actions

Actions are functions that are used to commit a mutation to change the state or can be used to dispatch i.e calls another action. It can be called in different components or views and then commits mutations of our state;

Register Action

Add the auth0 configuration variables to express

🛠 Create a .env file for the API Server under the auth0-express-js-sample directory:

touch .env

🛠 Populate this auth0-express-js-sample/.env file as follows:

Add the auth0 configuration variables to vue.js

From the Auth0 Application Settings page, you need the Auth0 Domain and Client ID values to allow your Vue.js application to use the communication bridge you created.

Author

Auth0

Calling an api

This section focuses on showing you how to get an access token in your Vue.js application and how to use it to make API calls to protected API endpoints.

Configure vue.js to connect with the express api

🛠 Head back to the auth0-vue-sample project directory that stores your Vue.js application.

🛠 Open the auth_config.json file and update it as follows, providing a value to audience and serverUrl:

Connect vue.js with auth0

The best part of the Auth0 platform is how streamlined it is to get started by following these steps:

Create a communication bridge between vue.js and auth0

When you use Auth0, you don’t have to build login forms. Auth0 offers a Universal Login page to reduce the overhead of adding and managing authentication.

How does Universal Login work?

Create a free auth0 account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Create a login button

🛠 Create a LoginButton.vue file under the src/components/ directory:

touch src/components/LoginButton.vue

🛠 Populate src/components/LoginButton.vue like so:

Create a logout button

🛠 Create a LogoutButton.vue file under the src/components/ directory:

touch src/components/LogoutButton.vue

Populate src/components/LogoutButton.vue like so:

Custom request and response interceptors

You can easily setup custom request and response interceptors if you use different request handling library.

Get the express api demo

🛠 Open a new terminal window and clone the auth0-express-js-sample repo somewhere in your system. Ensure that you clone it outside your Vue.js project directory.

Home.vue

Rewrite the Home.vue to look like this:

Installing strapi

The documentation works you through installing Strapi from the CLI, the minimum requirements for running Strapi, and how to create a quickstart project.

The Quickstart project uses SQLite as the default database, but feel free to use whatever database you like.

    yarn create strapi-app my-project //using yarn
    npx create-strapi-app my-project //using npx

Replace my-project with the name you wish to call your application directory. Your package manager will create a directory with the name and will install Strapi.

If you have followed the instructions correctly, you should have Strapi installed on your machine.

    yarn develop //using yarn
    npm run develop //using npm

Installing vue-axios

We need a package for making API calls to our Strapi backend, and we’ll be using the Vue-Axios package for that purpose.

Run the following command to install Vue-Axios in your machine

    npm install --save axios vue-axios vue-router vuex
    or
    yarn add axios vue-axios vue-router vuex

Installing vue-fontawesome with vue.js

Font-awesome is a package that we’ll use for getting and rendering icons in our application. Execute the following commands to install vue-fontawesome on your machine

    npm i --save @fortawesome/fontawesome-svg-core
    npm i --save @fortawesome/free-solid-svg-icons 
    npm i --save @fortawesome/vue-fontawesome
    or
    yarn add @fortawesome/fontawesome-svg-core
    yarn add @fortawesome/vue-fontawesome
    yarn add @fortawesome/vue-fontawesome

Integrate the login and logout buttons

Let’s wrap the LoginButton and LogoutButton into a component called AuthenticationButton.

🛠 Create an AuthenticationButton.vue file under the src/components/ directory:

touch src/components/AuthenticationButton.vue

🛠 Populate src/components/AuthenticationButton.vue with the following code:

There are some advantages to using this AuthenticationButton component wrapper:

Integrating all the installed packages into our vue.js application

What’ve we’ve done above is to install the packages. Vue.js has no idea what to do with the installed packages, so we’re going to tell Vue.js what to do with the packages.

Open up the main.js file that is located in the src folder and replace the contents of the file with the following code

Integrating tailwindcss with vue.js

We are going to use TailwindCSS as our CSS framework. Let’s see how we can integrate TailwindCSS into our Vue.js Application.

    npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
    or
    yarn add tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
  • Then in the root of your Vue.js folder, create a postcss.config.js and fill it up with the following lines.
    module.exports = {
      plugins: {
        tailwindcss: {},
        autoprefixer: {},
      }
    }

Also, in the root of the Vue.js folder create a tailwindcss.config.js and fill it up with the following lines.

Issue reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

License

The MIT License (MIT)

Copyright (c) 2022 Davor Grubelić

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Modules

Modules are different segments of our store that handles similar tasks together, including:

Before we proceed, let’s edit our main.js file.

Password recovery set-up

On the side menu bar under settings,

Prerequisites

What’ll you need for this tutorial:

Resources

Explore more on

State

In our state dict, we are going to define our data, and their default values:

Using yarn

    yarn add strapi-provider-email-nodemailer

What is auth0?

Auth0 helps you to:

What is strapi?

The Strapi documentation says that “Strapi is a flexible, open-source Headless CMS that gives developers the freedom to choose their favorite tools and frameworks while also allowing editors to manage and distribute their content easily.”

What you will learn

Here’s what the final version of our Application will look like

You can find the GitHub repository for the frontend application here and the repository for the backend application.

Links to the assets used in this project:

Background image &
Other assets

I hope you’re very excited, so let’s get started with our Strapi Backend setup:

Общие настройки проекта settings.py

config = Config(".env")
DEBUG = config("DEBUG", cast=bool, default=False)
DATABASE_URL = config("DATABASE_URL", cast=str)
SECRET_KEY = config("SECRET_KEY", cast=Secret)
ALLOWED_HOSTS = config("ALLOWED_HOSTS", cast=CommaSeparatedStrings)
JWT_PREFIX = config("JWT_PREFIX", cast=str)
JWT_ALGORITHM = config("JWT_ALGORITHM", cast=str)


Для удобства использования вынесем переменные из файла .env в отдельный файл настроек.

Промежуточный слой для работы с jwt middleware.py

Поскольку Starlette еще достаточно молодой фреймворк, удобной «батарейки» JWT к нему еще не написано. Исправим этот недочет.

Ссылки

Полный код на Github:

Бекенд на Starlette

Фронтенд на Vue.js

Пример работы

Спасибо за внимание Удачных интеграций.

Файл с переменными .env


Объявим здесь переменные, которые нам в дальнейшем понадобятся для работы:

Building the front-end

Let’s begin building the front-end of our application.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *