Skip to main content

Part-1 VueJS JWT(JSON Web Token) Authentication(Access Token Implementation)

In this article, we are going to understand the steps for JWT(JSON Web Token) authentication. Here our main focus to fetch the JWT access token to make users log into our VueJS 3.0 application. For maintaining user info we will use Vuex state management.

JWT Token:

JSON Web Token is a digitally signed and secured token for user validation. The jwt is constructed with 3 informative parts:
  • Header
  • Payload
  • Signature

Create A VueJS 3.0 Sample Application:

Let's begin by creating a VueJS 3.0 sample application.
Command To Install Vue CLI Globally On Your System
npm install -g @vue/cli
Command To Create A Vue App:
vue create your_app_name

Required NPM Packages:

Need to install the Vue routing library to configure routing into our application.
Command To Install Vue Router Library(For Vue3.0)
npm install vue-router@4
Need to install the Vuex Store library to configure state management to our application
Command To Install Vuex Store Library(For Vue3.0)
npm install vuex@next
Install Axios library to invoke API call's in our application
Command To Install Axios Library
npm install axios

Basic Page Component And Route Configuration:

In this section, we will be going to implement vue js pages and their routes.

Let's use bootstrap design in our sample so add the below CSS reference link in the index.html page of our VueJS application
public/index.html:(Just above closing head tag)
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
Now add the Home component.
src/components/Home.vue:
<template>
    <div>
        <h4>Home Page</h4>
    </div>
</template>
<script>
export default {
    
}
</script>
Now add the Login Form component.
src/components/Login.vue:(Html Part)
<template>
  <div>
    <h4>Login Form</h4>
    <form>
      <div class="mb-3">
        <label for="txtuserName" class="form-label">User Name</label>
        <input
          type="text"
          class="form-control"
          id="txtuserName"
          aria-describedby="emailHelp"
          v-model="username"/>
      </div>
      <div class="mb-3">
        <label for="txtPassword" class="form-label">Password</label>
        <input
          type="password"
          class="form-control"
          id="txtPassword"
          v-model="password"
/> </div> <button type="button" class="btn btn-primary" @click="login()">Submit</button> </form> </div> </template>
  • Here we created a sample login form with model binding properties like 'username' and 'password'.
src/components/login.vue:(Script Part)
<script>
export default {
  data(){
   return{
	username:'',
	password:''
   }
  },
  methods:{
   login(){
	console.log(this.username, this.password);
   }
  }
};
</script>
  • Here we have model binding properties and the 'login' method.
Now update App.vue file with the navigation menu as below.
<template>
  <div>
   <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
	<div class="collapse navbar-collapse" id="navbarSupportedContent">
	  <ul class="navbar-nav me-auto mb-2 mb-lg-0">
		<li class="nav-item">
		  <router-link to="/" class="nav-link">Home</router-link>
		</li>
		 <li class="nav-item">
		  <router-link to="/login" class="nav-link">Login</router-link>
		</li>
	  </ul>
	</div>
    </div>
   </nav>
   <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
};
</script>
  • Here we added a bootstrap menu and also used the 'router-link' vue component for navigation and also used the 'router-view' vue component to render the content.
Now create a route configuration file.
src/appRouter.js:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import Login from './components/Login.vue';

const routes =[
  {path:'/', component:Home},
  {path:'/login', component:Login}
];

export const routeConfig = createRouter({
  history: createWebHistory(),
  routes: routes
});
Now register our route config file into our main.js file
src/main.js:
import { createApp } from 'vue'
import App from './App.vue'
import * as appRouter from './appRouter';

const app = createApp(App)
app.use(appRouter.routeConfig);
app.mount('#app')

A Basic Skeleton Structure Of Vuex State Management:

For accessing token or user data we will maintain it in Vuex State Management along with the browser local storage. So now here we will implement a basic structure of vuex state management in our sample application.
src/store/modules/auth.js:
const state = () => ({
  authData: {
    token: "",
    refreshToken: "",
    tokenExp: "",
    userId: "",
    userName: "",
  },
});

const getters = {};

const actions = {};

const mutations = {};

export default{
    namespaced:true,
    state,
    getters,
    actions,
    mutations
}
  • Here we are separating our states by using modules which means we can maintain the different states of an application as a module. Here we creating authentication as a separate state module into the auth.js file.
  • In general state mainly contains objects like 'state', 'getters', 'actions', and 'mutations'.
  • Inside of state object, we have created an object called 'authData' which maintains all information about the application authentication.
  • Defined to use namespace in the state to avoid the conflict between the method names
Now register our auth state module into the vuex store module.
src/store/index.js:
import { createStore } from "vuex";
import authModule from './modules/auth';

const store = createStore({
  modules:{
   auth:authModule
  }
});

export default store;
  • Here we registered our auth module, the property name we used to register our module is 'auth'. The 'auth' property name will be used as the namespace while using our store.
Now register vuex store into the vue instance of our application in the main.js file.
src/main.js:
import { createApp } from 'vue'
import App from './App.vue'
import * as appRouter from './appRouter';
import store from './store/index';

const app = createApp(App)
app.use(appRouter.routeConfig);
app.use(store);
app.mount('#app')

Mock JWT Access Token:

As a front-end developer no need to spend more time onto work on JWT authentication API (using nodejs, .net, java server programs). So let's use a sample JWT token by mocking it in a constant variable in our application, latter we will make a dynamic API call for fetching the Jwt token at the end section of this article.
A sample jwt token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJzdWIiOjEsImlhdCI6MTYwODIwNjE3OSwiZXhwIjozNjAxNjA4MjA2MTc5fQ.BcHKT6ffgvkt0EztkJT35a0Yc7iWF9wkeNxKB4wSJEQ

JWT Decoder:

As we know JWT token encrypted string which contains some information like 'username', 'expiration', and some other claims. So to decode the jwt access token use the below code snippet
src/shared/jwtHelper.js:
export function jwtDecrypt(token) {
  var base64Url = token.split(".")[1];
  var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  var jsonPayload = decodeURIComponent(
    atob(base64)
      .split("")
      .map(function(c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );

  return JSON.parse(jsonPayload);
}

Implement Logic To Authenticate User Using Access Token:

Using mock jwt access token we will authenticate our user by storing the access token in browser local storage and in vuex state management as well.

Now update auth.js module state object with an additional property like 'loginStatus' this contains a message like authentication success or failure.
src/store/modules/auth.js:(Update 'state' object)
const state = () => ({
  authData: {
    token: "",
    refreshToken: "",
    tokenExp: "",
    userId: "",
    userName: "",
  },
  loginStatus:"",
});
Now update the mutations object to update our state in the auth.js module.
src/store/modules/auth.js:(Update 'mutations' object)
import { jwtDecrypt } from "../../shared/jwtHelper";

const mutations = {
  saveTokenData(state, data) {

    localStorage.setItem("access_token", data.access_token);
    localStorage.setItem("refresh_token", data.refresh_token);

    const jwtDecodedValue = jwtDecrypt(data.access_token);
    const newTokenData = {
      token: data.access_token,
      refreshToken: data.refresh_token,
      tokenExp: jwtDecodedValue.exp,
      userId: jwtDecodedValue.sub,
      userName: jwtDecodedValue.userName,
    };
    state.authData = newTokenData; 
  },
  setLoginStatu(state, value){
     state.loginStatus = value;
  }
};
  • Here in our mutation, we have defined 2 state change methods like 'SaveTokenData' and 'setLoginStatus'.
  • (Line: 2) The 'SaveTokenData' method accepts two parameters. The 'state' parameter nothing but our vuex state which will automatically be passed by the framework and the other is the 'data' parameter which is a user-defined input parameter where we passed our data into the method.
  • (Line: 4&5) Saving the token and refresh token data in local browser storage, so that they will be available to our application if we close and reopen our application as well.
  • (Line: 7) Decrypting the access token using our helper method defined above
  • Next updating the state of the 'authData' object.
  • (Line: 17-19) Setting the state of the 'loginStatus'.
Now we need to update the action method to get the access token from the API, for now, we will mock the access token in later steps we will update to use authentication API.
src/store/modules/auth.js:(Update 'actions' object)
const actions = {
  async login({commit},payload) {
    console.log(payload);
     const data = {
      access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlRlc3QiLCJzdWIiOjIsImlhdCI6MTYwNDMwOTc0OSwiZXhwIjoxNjA0MzA5ODA5fQ.jHez9kegJ7GT1AO5A2fQp6Dg9A6PBmeiDW1YPaCQoYs",
      refresh_token: ""
     }
     commit('saveTokenData', data);
     commit('setLoginStatu','success');
  },
};
  • (Line: 2) Defined action method 'login'. The reason we made this method async because in upcoming steps we will call authentication API which is an async call. This method has input parameter like '{commit}' this command to trigger the mutation which will be automatically passed by vuex and the second parameter is 'payload' user passing data(ex: user credential object).
  • (Line: 4) The constant object mocked with the access token.
  • (Line: 8)  Invoking the mutation method 'saveTokenData'
  • (Line: 9)  Invoking the mutation method 'setLoginStatus'
Now update the getter to fetch the status of 'loginStatus' property as below.
src/store/modules/auth.js:(Update getters object)
const getters = {
  getLoginStatus(state){
    return state.loginStatus;
  }
};
Now update the logic in Login.vue component to use the auth.js store to authenticate the user.
src/component/Login.vue:
<script>
import {mapActions, mapGetters} from 'vuex';
export default {
    data(){
        return{
            username:'',
            password:''
        }
    },
    computed:{
      ...mapGetters('auth',{
        getterLoginStatus:'getLoginStatus'
      })
    },
    methods:{
        ...mapActions('auth',{
          actionLogin:'login'
        }),
        async login(){
           await this.actionLogin({username:this.username, password:this.password});
           if(this.getterLoginStatus === 'success'){
             alert('login sucess');
           }else{
             alert('failed to login')
           }
        }
    }
};
</script>
  • (Line: 11-13) The 'getters' in the vuex state are used to fetch data. So to consume the getters in our vue component we need to use 'mapGetters' where we have to register our getters methods. The reason behind 'mapGetters' is used in 'computed' properties is that makes our data available with the latest updates.
  • (Line: 16-18) The 'actions' in the vuex state are to do async jobs like invoking API calls and then save the results to state by invoking mutations. So to trigger actions from the vue component we need to use 'mapActions' where we register vuex action methods.
  • (Line: 19-26) The 'login' method invoked when the user clicks on the login button. Here we first invoking 'actionLogin' which implicitly calls the 'login' action method states. After that checking the authentication state by using 'getterLoginStatus' which implicitly fetches data from the store.

Create A Dashboard Page:

Now let's create a sample user dashboard page where will display some user's data on it.

Now let's create a getter that fetches the 'authData' object in the auth.js module.
src/store/modules/auth.js:(Update getters object)
// code hidden for display purpose
const getters = {
  getAuthData(state){
    return state.authData;
  }
};
Create a new 'Dashboard' component where we display the user information.
src/components/Dashboard.vue:
<template>
    <div>
        <h1>Dashboard Page</h1>
        <div>
            UserName -- {{gettersAuthData.userName}}
        </div>
        <div>
            Id  -- {{gettersAuthData.userId}}
        </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
    computed:{
        ...mapGetters('auth',{
            gettersAuthData:'getAuthData'
        })
    }
}
</script>
  • Here fetching the user data using 'getAuthData' getter.
Update logic to navigate the user to the dashboard page in the Login component.
src/components/Login.vue:
async login(){
   await this.actionLogin({userName:this.username, password:this.password});
   if(this.getterLoginStatus === 'success'){
	 this.$router.push("/dashboard");
   }else{
	 alert('failed to login')
   }
}
Add the new route in the appRoutes.js file.
src/appRoute.js:
import Dashboard from './components/Dashboard.vue'

{path:'/dashboard',component: Dashboard}

Navigation Guards:

Navigation guards are used to executing navigation conditionally means if the non-authenticated user tries to access the page that requires authentication then the navigation guards will restrict the user from accessing the page.

In our sample example, the 'Dashboard' component needs user authentication, but if we try to access it without authentication also user able to see this component. So now we need to apply guards to protect our 'Dashboard' component.

In the jwtHelper.js file add a helper method to check the token expiration.
src/shared/jwtHelper.js:
export function tokenAlive(exp) {
  if (Date.now() >= exp * 1000) {
    return false;
  }
  return true;
}
  • The method returns 'true' if the token is still active.
Now create getter in our auth.js module to return a boolean value to identify user authenticated or not authenticated.
src/store/modules/auth.js:
import { tokenAlive } from "../../shared/jwtHelper";

const getters = {
  // code hidden for display purpose
  isTokenActive(state) {
    if (!state.authData.tokenExp) {
      return false;
    }
    return tokenAlive(state.authData.tokenExp);
  },
};
Now add the navigation guard in the appRouter.js file.
src/appRouter.js:
import { createRouter, createWebHistory } from "vue-router";
import Home from "./components/Home.vue";
import Login from "./components/Login.vue";
import Dashboard from "./components/Dashboard.vue";
import store from "./store/index";

const routes = [
  { path: "/", component: Home, meta: { requiredAuth: false } },
  { path: "/login", component: Login, meta: { requiredAuth: false } },
  { path: "/dashboard", component: Dashboard, meta: { requiredAuth: true } },
];

export const routeConfig = createRouter({
  history: createWebHistory(),
  routes: routes,
});

routeConfig.beforeEach((to,from, next) => {
    if(to.meta.requiredAuth){
        const auth = store.getters["auth/isTokenActive"];
        if(!auth){
           return next({path: '/login'});
        }
    }
    return next();
});
  • Here we can observe the routes new object like 'meta' is added. In this meta-object, we can define any properties. For our scenario, I have added property like 'requiredAuth' of type boolean, to differentiate which routes need authentication.
  • (Line: 18) Here we configured a global navigation guard that will execute for all routes before navigating. Inside of it, we added logic like based on 'requiredAuth' property we are checking user authentication and redirection.

Load Token On Application Open:

Now one problem we face is if we reload our application or closes & reopen the application we can observe we are in a logout state because all the data we maintained in the vuex store will be lost. So in this case we need to restore the store state by loading the access token from the browser's local storage.

So let's update our navigation guard to load the access token from the local browser storage.
src/appRoute.js:
routeConfig.beforeEach((to,from, next) => {
    console.log(store.getters["auth/getAuthData"].token);
    if(!store.getters["auth/getAuthData"].token){
        const access_token = localStorage.getItem("access_token");
        const refresh_token = localStorage.getItem("refresh_token");
        if(access_token){
            const data = {
                access_token:access_token,
                refresh_token:refresh_token
            };
            store.commit('auth/saveTokenData',data);
        }
    }
    const auth = store.getters["auth/isTokenActive"];

    if(to.fullPath == "/"){
        return next();
    }
    else if(auth && !to.meta.requiredAuth){
        return next({path:"/dashboard"});
    }
    else if(!auth && to.meta.requiredAuth){
        return next({path: '/login'});
    }

    return next();
});
  • (Line: 3-13) Loads the access token from the browser store and then updating the store state by populating the user data.

NestJS(Nodejs) Server JWT API:

Command To Install NestJS CLI:
npm i -g @nestjs/cli
Next, go to the root folder of the repo and run the command to install all the package
Command To Install ALL Packages In our Repository application:
npm install
That's all we have set up a JWT API in our local system for testing, now run the following command to start the application.
Command To Start NestJS APP:
npm run start:dev
Our jwt token endpoint
Url:- http://localhost:3000/auth/login
Payload:-
{
	"username":"test",
	"password":"1234"
}

note:- payload should be same as above, variable name 'username' and 'password'
don't change them, they are even case sensitive. credentials also use as above

Integrate JWT Authentication Endpoint:

Till now we used mocked jwt token, now we are going to use real Jwt authentication endpoint.

Let's update the 'login' action method in store
src/store/modules/auth.js:(Update login action method)
async login({ commit }, payload) {
    const response = await axios
      .post("http://localhost:3000/auth/login", payload)
      .catch((err) => {
        console.log(err);
      });
    if (response && response.data) {
      commit("saveTokenData", response.data);
      commit("setLoginStatu", "success");
    } else {
      commit("setLoginStatu", "failed");
    }
}
  • Here we replace our mock jwt token with real authentication API.
That's all about the steps to implement the access token in VueJS 3.0 application. In the next article, we will learn about the refresh token implementation.

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on access token implementation in VueJS 3.0 application. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. Command To Install Vue CLI Globally On Your System

    npm install -g @vue/cli :)

    ReplyDelete
  2. Replies
    1. there might be issue with breaking changes, but logic you can implement as it is

      Delete
  3. Great article thank you very much!

    ReplyDelete
  4. Thank you very much, very useful !

    ReplyDelete

Post a Comment

Popular posts from this blog

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

NestJS File Upload

In this article, we are going to understand the steps to create a file uploading endpoint in the NestJS application. Key Features In NestJS File Upload: Let us know some key features of NestJS file upload before implementing a sample application. FileInterceptor: The 'FileInterceptor' will be decorated on top of the file upload endpoint. This interceptor will read single file data from the form posted to the endpoint. export declare function FilesInterceptor(fieldName: string, localOptions?: MulterOptions): Type<NestInterceptor>; Here we can observe the 'fieldName' first input parameter this value should be a match with our 'name' attribute value on the form file input field. So our interceptor read our files that are attached to the file input field. Another input parameter of 'MulterOptions' that provides configuration like file destination path, customizing file name, etc. FilesInterceptor: The 'FilesInterceptor' will be decorated on t

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http