<?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 Meghna on Medium]]></title>
        <description><![CDATA[Stories by Meghna on Medium]]></description>
        <link>https://medium.com/@meghnav274?source=rss-49f513f9e556------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IKBLj51lSSv-vj1TKP1oMA.png</url>
            <title>Stories by Meghna on Medium</title>
            <link>https://medium.com/@meghnav274?source=rss-49f513f9e556------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:43:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meghnav274/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[A Guide to WhatsApp Bot]]></title>
            <link>https://medium.com/@meghnav274/a-guide-to-whatsapp-bot-94439ecec32e?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/94439ecec32e</guid>
            <category><![CDATA[whatsapp-bot]]></category>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[whatsapp-bot-integration]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[whatsapp-bot-service]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 06:44:08 GMT</pubDate>
            <atom:updated>2024-09-24T06:44:08.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wXEdohR8CA6btP_7CkI1Q.png" /></figure><p><strong>Table of Contents</strong></p><ul><li><a href="#ae1c">What is a WhatsApp Bot?</a></li><li><a href="#c433">How is a WhatsApp Bot Configured?</a></li><li><a href="#6f02">Role of Meta in WhatsApp Bot</a></li><li><a href="#2213">What are Meta Business Partners?</a></li></ul><p>Now-a-days, almost every business has developed a WhatsApp Bot of their own. Be it for advertisement of their product, for sending the updates about customer’s orders, sending promotional offers, getting the customer information to provide a service, and what not. Basically, everyone is communicating using WhatsApp.</p><p>But have you ever wondered, how it all works? What technologies drive them, what rules are applied, and how is everything configured? We are going to find all that in this article!</p><ol><li><strong>What is a WhatsApp Bot?</strong></li></ol><blockquote>So, let’s start with the basics, what exactly is a WhatsApp bot?</blockquote><p>It is a program that interacts with the user through the WhatsApp Messaging App. It helps the business to generate leads, promote their products, provide fast customer support, find out what their customers need and possibly implement that, and provide tailored, personalized content to the users that may not be possible using any other means.</p><p><strong>2. How is a WhatsApp Bot Configured?</strong></p><p>Any business who wants to send messages to their customers on a medium to large scale on WhatsApp has to go through the following processes —</p><p>i. Create a WhatsApp Business Account.</p><p>ii. Buy a business phone number.</p><p>iii. Initiate Business Verification.</p><p>If you are using a Meta Business Partner, these steps can be taken care of by them.</p><p>iv. Setting up the Webhook URL —</p><p>Webhooks can be used to get real-time HTTP notifications whenever we receive a message from the user.</p><blockquote>Sending a Message through WhatsApp Bot</blockquote><p>There are two types of messages that you can send using your Bot. Freeform and Template Messages. Template messages have to be registered and approved by Meta, only after that we can send the message to the user and Freeform messages are any text message that we have to send.</p><p>There is a session of 24 hours, which counts as a single conversation. We will be charged for a conversation and not for single messages. Also, we can send the Freeform messages inside this 24-hour window, when this window ends, you need to communicate with your customers by only sending a template message.</p><p><strong>3. Role of Meta in WhatsApp Bot</strong></p><p>Meta provides a platform specifically for allowing the business to communicate with their customers which is known as <strong><em>WhatsApp Business Platform. </em></strong>It consists of three primary APIs —</p><p>i. Cloud API</p><p>ii. On-Premises API</p><p>iii. Business Management API</p><p>To send and receive messages, we can use Cloud API (which is hosted by Meta) or On-Premises API (which has to be hosted by us). Apart from using any one of these two APIs, we also have to use the Business Management API which is used to register our business account and manage our templates and phone numbers.</p><p><strong>4. What are Meta Business Partners?</strong></p><p>Meta Business Partners are the companies or agencies that have been recognized by Meta for their expertise and ability to help businesses succeed on Meta’s platforms like WhatsApp. These partners provide services such as advertising, marketing, and development solutions to help businesses manage their digital presence, run effective ad campaigns, and optimize their performance on Meta’s platforms.</p><p>Some of the Meta Business Partners for WhatsApp are —</p><ul><li><a href="https://www.infobip.com/"><strong>Infobip </strong></a>— Infobip provides a comprehensive platform for omnichannel communication, strong global reach, and great customer support. It is best suited for enterprises needing a reliable, large-scale solution that integrates multiple communication channels with strong customer service support.</li><li><a href="https://www.twilio.com/en-us"><strong>Twilio </strong></a>— Twilio offers highly customizable APIs, excellent for scaling, and supports multi-channel communication. It is ideal for larger businesses that need multi-channel integration and have the resources to manage complex systems.</li><li><a href="https://bird.com/"><strong>MessageBird </strong></a>— MessageBird provides an easy-to-use, single API for multi-channel communication, plus features like chatbots and automation. It is best suited for small to medium-sized businesses that want simplicity with multi-channel messaging capabilities.</li><li><a href="https://www.360dialog.com/"><strong>360Dialog </strong></a>— 360Dialog specializes in WhatsApp Business API with affordable pricing and direct API access. It is great for small businesses or startups that only need WhatsApp without the complexity of multi-channel communication.</li><li><a href="https://www.sinch.com/en-in/"><strong>Sinch </strong></a>— Sinch is strong for global outreach, supports rich media in messages (like images, and videos), and automates workflows with chatbots. It is ideal for businesses needing global messaging and automation but doesn’t require extensive custom development.</li></ul><p>So, here we have seen all the basic configurations of a WhatsApp Bot. Moving forward, we will be seeing in detail how to configure any one of the Meta Business Partners to create our own ChatBot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94439ecec32e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blazor Server vs Blazor WebAssembly vs Blazor Web App!]]></title>
            <link>https://medium.com/@meghnav274/blazor-server-vs-blazor-webassembly-vs-blazor-web-app-8fe8fc1cefeb?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fe8fc1cefeb</guid>
            <category><![CDATA[blazorhybrid]]></category>
            <category><![CDATA[blazor-webassembly]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[blazor-server]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 09:23:45 GMT</pubDate>
            <atom:updated>2024-07-11T09:23:45.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://medium.com/@meghnav274/understanding-net-blazor-7ad22c9c99d6"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*LlPeZPytpdqeMmclyTAhZQ.png" /></a></figure><h4>Table of Contents</h4><ul><li><a href="#41aa">What are Hosting Models</a></li><li><a href="#5ba3">Blazor Server</a></li><li><a href="#4235">Blazor WebAssembly</a></li><li><a href="#b37f">Blazor Web App</a></li><li><a href="#21c1">Which hosting model should you choose?</a></li></ul><p>So, you have heard about the modern frontend web development framework — <a href="https://medium.com/@meghnav274/understanding-net-blazor-7ad22c9c99d6">Blazor</a> and are excited to start building applications using the same. The first step you’ll do is open up Visual Studio, Create a new project, and search for templates that match Blazor. When you search Blazor, you will see almost five to six templates popup with different names and you will get all confused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*z6N2ruPE2fDwtyot2xH6vA.jpeg" /><figcaption>This screenshot is taken from Visual Studio 2022</figcaption></figure><p>The different Blazor templates above can be divided into three categories:</p><ol><li>Blazor Server</li><li>Blazor WebAssembly</li><li>Blazor Web App</li></ol><p>All these are the hosting models for Blazor which will allow us to control how our application functions. Let’s see in detail about each of the hosting models.</p><h3>1. Blazor Server:</h3><p>In Blazor Server, as the name suggests, the app logic runs on the server. The Blazor Server uses a SignalR Connection to serve the UI Updates to the user on their browser from the server. Here, when the user tries to access your web application, the user will get the UI of your application whereas the backend logic stays on the server and is fetched as and when requested. Here, by use of <strong>SignalR</strong>, real-time updates could be seen between the client and the user, which helps to keep the UI in sync with the server state. Here, as the code runs on the server, we have full access to the .NET APIs, as well as server-side resources like Database, File System, etc.</p><blockquote>How does Blazor Server Work?</blockquote><p>Suppose you access a web application that is developed in Blazor Web Server. Let’s see what process will take place when you first visit this website.</p><ul><li>When you initially navigate to a Blazor Web Server application, the server will send an initial HTML page that will include a small Javascript code to establish the SignalR connection. Typically, the name of the javascript will be blazor.server.js</li><li>This SignalR helps to establish a real-time communication channel between client and server.</li><li>User interaction such as button clicks or form submissions are sent to the server over SignalR connection.</li><li>The server then processes these events using application logic and sends the UI updates back to the client over SignalR connection, and the browser updates the DOM accordingly.</li></ul><blockquote>Benefits of Blazor Server</blockquote><ul><li>As only a small amount of data is required, load time is fast.</li><li>This is more secure as application logic is not exposed to the client.</li><li>All the .NET ecosystems can be leveraged, including server-side APIs and libraries.</li></ul><blockquote>Drawbacks of Blazor Server</blockquote><ul><li>Network Latency can happen if the server is slow.</li><li>As the server needs to handle multiple SignalR connections, high-traffic applications can face issues.</li><li>The application cannot function if not connected to the server.</li></ul><h3>2. Blazor WebAssembly:</h3><p>The Blazor WebAssembly runs entirely in the browser and uses <strong>WebAssembly</strong> (aka Wasm) to execute .NET Code. Wasm enables us to deploy on the web for client and server applications. Blazor WebAssembly uses Ahead of Time (AOT) Compilation, where we can compile our .NET Code directly into WebAssembly. Without using AOT, Blazor WebAssembly can run on the browser using .NET Intermediate Language interpreter implemented in WebAssembly with partial just-in-time (JIT) compilation support.</p><blockquote>How does Blazor WebAssembly Work?</blockquote><ul><li>When you navigate to a WebAssembly app, the server sends the static files, including WebAssembly runtime, .NET assemblies and any other assets required for the application.</li><li>WebAssembly runtime in the browser loads and executes the .NET assemblies.</li><li>Blazor framework handles rendering the UI and managing the user interactions.</li><li>The Client side Blazor app can communicate with server side APIs using standard HTTP calls.</li></ul><blockquote>Benefits of Blazor WebAssembly</blockquote><ul><li>Provides offline support after initial load as the application runs on the client side.</li><li>Leverages the powerful .NET ecosystem, enabling code reuse and unified development experience.</li><li>Works on any browser that supports WebAssembly without requiring a plugin.</li></ul><blockquote>Drawbacks of Blazor WebAssembly</blockquote><ul><li>The initial Download time is quite large as all the .NET assemblies and runtime needs to be downloaded into the browser.</li><li>Server-side APIs are not directly accessible, so restricted to the APIs available in WebAssembly and browser.</li></ul><h3>3. Blazor Web App:</h3><p>The Blazor Web App offers a hybrid approach by supporting both server-side and client interactivity. It combines the benefits of both Blazor WebAssembly as well as Blazor Server. This allows us to build applications that can render both on the client side using WebAssembly and on the server side, depending on the scenario. It can offer better performance, scalability, and flexibility by leveraging the strengths of both approaches.</p><blockquote>How does Blazor Web App Work?</blockquote><ul><li>Suppose you navigate to the application URL that uses the Blazor Web App Hosting Model.</li><li>The initial pre-rendered page is served by the server and is visible to the user while the browser downloads the Blazor WebAssembly runtime in the background.</li><li>WebAssembly rendering initializes and takes over the rendering, transitioning the application to client-side execution.</li><li>Client handles the subsequent API calls, and UI updates, so that the need for server communication could be reduced.</li></ul><blockquote>Benefits of Blazor Web App</blockquote><ul><li>Fast initial load as the initial load is pre-rendered by the server.</li><li>Server-side pre-rendering ensures search engines can index application content, which helps with SEO.</li><li>Once the WebAssembly is initialized, the application can run handle interaction in the browser which reduces server interaction and increases responsiveness.</li><li>The server is not required to process every interaction which frees up the server resources for other tasks.</li></ul><blockquote>Drawbacks of Blazor Web App</blockquote><ul><li>The complexity increases as we have to manage both server-side and client-side effectively.</li><li>The download size is large as the .NET runtime and assemblies are downloaded in the browser.</li><li>Security needs to be handled for both client-side and server-side applications.</li></ul><h3>Which Hosting Model should you choose?</h3><p>Choosing between Blazor Server, Blazor WebAssembly and Blazor Web App depends on various factors like your application requirements, end-user needs, and your development resources. Some of the criteria that can help you in making this decision are:</p><ol><li>Blazor Server —</li></ol><ul><li>Blazor Server is best for Applications which has heavy server-side logic.</li><li>It can be used in scenarios where SEO and initial load time are critical.</li><li>It can used in scenarios where we are going to have consistent network connectivity (like internal enterprise applications).</li></ul><p>2. Blazor WebAssembly —</p><ul><li>Blazor WebAssembly projects are best for customer-facing applications where we focus on user experience and responsiveness.</li><li>It can be used in applications requiring offline connectivity.</li></ul><p>3. Blazor Web App —</p><ul><li>Can be used in applications that require a balance of performance, scalability, and user experience.</li><li>It can be used in scenarios where SEO and initial load time are critical, but responsiveness and offline support are also needed.</li></ul><p>With keeping these matrix in mind, you can make a decision related to which hosting model would be best suited for your requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fe8fc1cefeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding .NET  Blazor!]]></title>
            <link>https://medium.com/@meghnav274/understanding-net-blazor-7ad22c9c99d6?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad22c9c99d6</guid>
            <category><![CDATA[blazor-components]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[blazor-server]]></category>
            <category><![CDATA[blazor-webassembly]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 09:46:40 GMT</pubDate>
            <atom:updated>2024-07-11T09:31:37.896Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding .NET Blazor</h3><figure><img alt="Blazor" src="https://cdn-images-1.medium.com/max/300/1*LlPeZPytpdqeMmclyTAhZQ.png" /></figure><p>If you are working with ASP.NET Core and want to become a full-stack developer without learning a line of Javascript or Javascript frameworks, then you need to learn Blazor as soon as possible.</p><p>Blazor is a .NET framework that is used for frontend development and it supports both client-side and server-side rendering in a single solution. You can leverage your knowledge of HTML, CSS, and C# and create a beautiful full-stack web application that will handle both frontend and backend in a single application. The best part about developing a Blazor application is that you do not need to write a line of Javascript in your code, all the events can be handled by leveraging C#.</p><p>Blazor apps are based on Components. A component is a simple fundamental building block that is used to create the User Interface of an application. They are reusable, self-contained pieces of UI that can range from implementing simple elements like buttons to complex structures like forms or entire pages. Components can be reused across multiple applications, reducing code duplication. Each component has its own rendering logic, state, and event handling which makes code modular and easier to manage. They are typically written in razor syntax using HTML and C#.</p><p>The Blazor Application can be hosted using different models like WebAssembly, Server, and Hybrid Model.</p><p><strong>Why should you use Blazor?</strong></p><p>Okay, so we have seen a small introduction to Blazor, now we will see why should we use or learn Blazor.</p><ol><li>Using Blazor, we can create interactive and responsive UIs by using C# code.</li><li>We can leverage the existing .NET ecosystem of .NET Libraries.</li><li>The performance, security, and reliability that .NET provides are highly beneficial.</li><li>In Blazor, the UI is quickly delivered to the browser by only rendering HTML, as it does not need to download the huge javascript bundles.</li><li>Blazor supports interactive server-side rendering which is done through a live connection between browser and server, which helps in processing user actions and updates the UI in real-time.</li><li>Here, the server can directly handle the user interaction like button clicks or form submissions which eliminates the need to create a separate API endpoint enabling a dynamic and interactive user experience.</li><li>Initially, the server sends the HTML content without activating the event handlers. Once the initial content is loaded, the real-time connection kicks in, enabling the interactive features. This makes the page load faster and feels more responsive.</li></ol><p><strong>What are Blazor hosting models?</strong></p><p>Razor components can run in server-side using ASP.NET Core versus client-side in the browser on a WebAssembly-based .NET Runtime. Blazor applications can also be hosted in hybrid mode. The same razor components can be used with any of the hosting models unchanged.</p><ol><li><strong>Blazor Server</strong>: Here, the components are executed on the server, from within an ASP.NET Core app. All the event handling and UI updates are handled using SignalR connection using WebSockets protocol. In Blazor Server Hosting model, each browser screen represents separate instances of server-managed component states. If a browser tab is closed or any external URL is navigated to, a graceful termination occurs where all the resources are immediately released. The Blazor app takes full capabilities of server resources including .NET Core, and .NET/C# code base including the app’s component code is not served to the clients. Here, we have to deploy our code on a server so that the end user can access it and there is no offline support. If the client connection fails, interactivity fails.</li><li><strong>Blazor WebAssembly</strong>: It runs the component&#39;s client-side code in the browser on a WebAssembly-based .NET runtime. Here, the razor components their runtime, and the .NET assemblies are downloaded in the browser. Components are executed directly on a browser UI thread. Here, assets are deployed as static files to a web server or a service capable of serving static content to clients. In Blazor web assembly, a large app takes a relatively longer time to download to a browser, which diminishes the user experience. In standalone Blazor WebAssembly apps, there’s no .NET server-side dependency after the app is downloaded from the server, so the app remains functional if the server goes offline also, in standalone Blazor WebAssembly applications, serverless deployment is possible. Here, razor components are restricted to the capabilities of the browser also, capable client hardware and software are required.</li><li><strong>Blazor Hybrid</strong>: Blazor Hybrid apps can be built using different .NET native app frameworks, including .NET MAUI, WPF, and Windows Forms. Using Blazor with .NET MAUI offers a convenient way to build cross-platform Blazor Hybrid apps for mobile and desktop, while Blazor integration with WPF and Windows Forms can be a great way to modernize existing apps.</li></ol><p>You can learn more about Blazor Hosting Models <a href="https://medium.com/@meghnav274/blazor-server-vs-blazor-webassembly-vs-blazor-web-app-8fe8fc1cefeb">here</a>.</p><p>So, this is some basic useful information about Blazor, which you can keep in mind while building your next Blazor Application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad22c9c99d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading files to Google Drive using .NET Console App]]></title>
            <link>https://medium.com/@meghnav274/uploading-files-to-google-drive-using-net-console-app-f0aae69a3f0f?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0aae69a3f0f</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[upload-on-google]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 06:06:41 GMT</pubDate>
            <atom:updated>2024-03-19T08:59:38.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uploading files to Google Drive using .NET Console App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*09QFoPY2GijGd_rn" /></figure><p>There may be many scenarios where you have to upload a file to Google Drive from your console application. It may be because you do not want to store the files on your server and need to store them on a cloud storage or you need to share the document with your user, here we will see how we can upload the file from our .NET Application.</p><p>Firstly, you have to navigate to <a href="https://console.cloud.google.com/">Google Cloud Platform</a> (GCP), if you haven’t already signed in with your Google account, you’ll see a page where you will be asked to sign in. After signing in, if you are using GCP for the first time, you’ll see a Terms of Service page where you have to Agree and then Continue to the website.</p><p>You will be navigated to the dashboard, where on the top-left corner, you can see a project dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSg_ctn21f5gH9XZhXOPzQ.jpeg" /></figure><p>Select the dropdown and click on New Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*AZbqeAsfG9BfmW2aa-MFHA.jpeg" /></figure><p>Give a project name — anything you want and then click on create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Wa20G-sG00D8eAf3eZYo3g.png" /></figure><p>Next, click the project dropdown once again and select the project you have created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*sxw7MpBTkMkkiSAPipRREw.jpeg" /></figure><p>Your, new project is created, now to upload files to Google Drive, we have to enable the Google Drive API, for that navigate to APIs and Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xV2BoGEZagp6292PPHj2Vw.png" /></figure><p>Click on Enable APIs and Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0ABdg3I5WGhH5852a76_A.png" /></figure><p>Search for Google Drive API and select the First one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMmnCY9xIOO9LAktzvn6zw.png" /></figure><p>Click on Enable and you will be redirected back to APIs and Services Dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*RFc0qVWogN6Lz5q9geuB8A.png" /></figure><p>Now, we have to create Credentials to use this API in our project. For that, click on Credentials, the Credentials Dashboard will be opened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqhRKshO4gfG3TdKJD4-KA.png" /></figure><p>Next, click on Create Credentials and remember to create Service Credential as we will be working with a console Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfK_W6DFpWRmfN8gRoTKlQ.png" /></figure><p>For Service Account Name, enter any name of your choice, then click on Create and Continue. From Grant this Service Account Access, click on Select a role and select Owner, and click Continue. At the end, click on Done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*wLPWJvJRHA9qtSTjAQ5QSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*ad1Q1eH_DaAK6JEZ9g4Niw.png" /></figure><p>Once the Service account has been created, you will be navigated back to the Credentials page. Scroll down to Service accounts, and click on the edit icon for the account you have just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZx_8ZtkhMHaikXqIQr9Iw.png" /></figure><p>Then, click on Keys Tab → Add Key → Create New Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*SZTI-eg488I6ATI7sJZkXA.png" /></figure><p>Select JSON and click on Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jlJLOdYa4nUWaNRXUTUG6A.png" /></figure><p>Your Key will be downloaded as a json file into your system. You have to use this file in the console application that we will develop to upload the file on Google Drive.</p><p>Let’s start by creating a new Console Application. I am using Visual Studio 2022.</p><ol><li>Open Visual Studio 2022 → Create New Project → Select Template (Console App) → Write Project Name → Click on Next → Click on Create → Your new Project will be created.</li><li>Next, we need to add some NuGet Packages to work with Google Drive API, for that Right Click on Project Name → Manage NuGet Package → Package Manager Console will be opened → Click on Browse and search for <strong>Google.Apis</strong> and click on Install. Similarly, install <strong>Google.Apis.Auth</strong> and <strong>Google.Apis.Drive.v3</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*uHQzvqVUzIpUwOjP7DW4rA.png" /></figure><p>3. Right Click on Project Name → Click on Add → Click on Class → Give a name for class → Click on Add. Our new class will be created which we will use to upload files to the drive.</p><p>4. Right-click on Project Name → Click on Open Folder in File Explorer → Go to bin → Debug → net6.0, Copy and paste your credentials file here. You can rename the file for easy access, I’ve named it <em>Credentials</em>. For easy access, you can also paste the file that you are planning to upload to Google Drive here.</p><p>5. In our new Class file, update the <em>internal</em> access specifier to <em>public</em>, so that we can access this class from our Program File.</p><p>6. In order to upload our files to a specific folder in Google Drive, we need to create a new folder in Drive. Navigate to Google Drive using the same account from which you have created the service account. Click on New → New Folder → Create New Folder. I have created a folder named ‘Test’. Open the folder you have just created, in the address bar, you will find an Id, copy and store this Id, we will be using this in the further steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86hqBb6N9rKxO-7luRdaCQ.jpeg" /></figure><p>7. Next, go to your <em>Credential.json</em> file that you have downloaded, in that file, you will find an email address named <em>client_email</em>, copy the email Id, we will need it for the further steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*FWcJ9eav1z7UEJRAQ82nhA.jpeg" /></figure><p>8. Go to the Folder you created on Google Drive, Click on the Folder Name → Share. In Add People text box, paste the client_email that you just copied and click on send, which will allow us to upload files in the folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Rcgm9qRw7_237tsCGcasLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*90sJbr77xznpbD5w-mzatA.jpeg" /></figure><p>9. Open up the class that you created and begin Coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*NWVjNAQgVey6vFksrgfh9w.jpeg" /></figure><ol><li>Create a method <em>UploadFilesToDrive </em>inside the class.</li><li>Give the path and name of your service account credential file.</li><li>Write the folder Id of the Google Drive Folder. Give the file name and path which you wish to upload.</li><li>Creating a variable of type GoogleCredential.</li><li>Next, we open the file in Read mode and create a scope for Google Drive File.</li><li>Create a new Drive service, to manipulate files in the drive. The Application name can be anything of your choice.</li><li>Assign the metadata to the file like the name of the file and where it would be uploaded.</li><li>Create a request to upload the file.</li><li>From the response, extract meaningful information like file Id and name.</li><li>Print this information to the console.</li></ol><pre>using Google.Apis.Auth.OAuth2;<br>using Google.Apis.Drive.v3;<br>using Google.Apis.Services;<br>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;<br><br>namespace UploadFile<br>{<br>    public class UploadToDrive<br>    {<br>        public void UploadFilesToDrive()<br>        {<br>            string credentialsPath = &quot;Credentials.json&quot;;<br>            string folderId = &quot;enter_your_folderId&quot;;<br>            string fileToUpload = &quot;D\\Demo.docx&quot;;<br><br>            GoogleCredential credential;<br>            using (var stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))<br>            {<br>                credential = GoogleCredential.FromStream(stream).CreateScoped(new[]<br>                {<br>                    DriveService.ScopeConstants.DriveFile<br>                });<br>                var service = new DriveService(new BaseClientService.Initializer()<br>                {<br>                    HttpClientInitializer = credential,<br>                    ApplicationName = &quot;Excel Export Upload Console App&quot;<br>                });<br><br>                var fileMetaData = new Google.Apis.Drive.v3.Data.File()<br>                {<br>                    Name = Path.GetFileName(fileToUpload),<br>                    Parents = new List&lt;string&gt; { folderId }<br>                };<br><br>                FilesResource.CreateMediaUpload request;<br>                using (var streamFile = new FileStream(fileToUpload, FileMode.Open))<br>                {<br>                    request = service.Files.Create(fileMetaData, streamFile, &quot;&quot;);<br>                    request.Fields = &quot;id&quot;;<br>                    request.Upload();<br>                }<br>                var uploadedFile = request.ResponseBody;<br>                Console.WriteLine($&quot;File &#39;{fileMetaData.Name}&#39; uploaded with ID: {uploadedFile.Id}&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>10. Next, open up your program.cs file and replace it with the below code to call our new class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*vUnak-MvktTcOufQ5XOnmQ.png" /></figure><pre>namespace UploadFile<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            UploadToDrive uploadToDrive = new UploadToDrive();<br>            uploadToDrive.UploadFilesToDrive();<br>        }<br>    }<br>}</pre><p>11. Run the code, you will get the file id printed on the console. You can use this file id to further manipulate the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*ttvZ05vlFgXVjYgdXrDjCA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*676UyaGD2VYu4HXKac4a6g.png" /></figure><p>You can follow the link to access the code on GitHub:</p><p><a href="https://github.com/Meghna2704/Upload_File">GitHub - Meghna2704/Upload_File: This project demonstrates how to upload a file on Google Drive.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0aae69a3f0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding .NET]]></title>
            <link>https://medium.com/@meghnav274/understanding-net-d38405b58701?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38405b58701</guid>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 10:27:35 GMT</pubDate>
            <atom:updated>2024-03-13T10:41:35.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ceg2iQZohS6VzZckjxrpg.png" /></figure><p>Sometimes, the terms .NET, ASP.NET, and ASP.NET Core all sound too similar or too confusing for a beginner. It becomes very difficult to distinguish one from another and often we tend to use these terms interchangeably which is not correct. So, let’s understand the .NET in the simplest way possible.</p><p><strong>.NET:</strong></p><p>Microsoft .NET (aka .NET Framework) is a free and open-source platform that is used for building a variety of applications. It is a software development framework that primarily runs on Windows. Using, Microsoft .NET Framework we can build various types of applications including web, desktop, mobile, cloud, gaming, and Internet of things (IoT) applications. It can run programs written in multiple languages, but the most popular one is C#. This .NET Framework includes a Common Language Runtime (CLR) which is used to manage memory, handle exceptions, and provide various other system services to execute .NET programs. There are many features that the .NET Framework offers. Some of them are:</p><ol><li>It supports more than 60 languages, out of which 11 are designed and developed by Microsoft. So, it gives users a kind of language independence which allows user to choose the language that best suits their needs or preferences.</li><li>It encourages the use of object-oriented programming principles which allows code organization, reuse, and maintenance.</li><li>.NET provides a unified development environment with a consistent set of libraries and tools for building various types of applications, making it easier for users to work on different projects.</li><li>The features like just-in-time compilation and native optimization allow users to get good performance.</li></ol><p><strong>ASP.NET:</strong></p><p>Microsoft ASP.NET is built on top of the .NET Framework. The ASP.NET is used for web application development. It allows developers to build dynamic websites, web applications, and web services using a variety of languages such as C#, VB.NET, and F#. ASP.NET extends the .NET platform with tools and libraries specifically used for building web apps. The ASP.NET provides a base framework for processing web requests. It also provides a web page templating syntax, known as razor for building dynamic web pages. It provides the identity functionality for handling logins, multi-factor authentication, and even external authentication from Google or Facebook. The ASP.NET provides the libraries for common web patterns such as MVC (model-view-controller).</p><p><strong>ASP.NET Core:</strong></p><p>ASP.NET Core is a significant evolution and divergence from the traditional ASP.NET Framework. ASP.NET Core is the open-source version of ASP.NET Framework. It runs on Windows, Linux, and macOS. The ASP.NET Core was first released in 2016 and is the re-design of the earlier Windows-only ASP.NET. The main area of focus while developing ASP.NET Core was performance. It is faster than other popular web development frameworks. Multiple versions of ASP.NET Core can exist side-by-side on the same server. It means that one app can adopt the latest version while other apps can run on the version they were tested on. ASP.NET Core is modular, so developers can add only components they need in their applications, reducing overall size and improving performance.</p><p><strong>Difference between ASP.NET and ASP.NET Core:</strong></p><p>Let’s look at some code/project level differences between ASP.NET and ASP.NET Core that can help us recognize whether the project belongs to ASP.NET Framework or ASP.NET Core.</p><ol><li>In ASP.NET Core, project files typically have a ‘.csproj’ extension, while ASP.NET Framework projects can have a ‘.csproj’ or ‘.vbproj’ extension.</li><li>In ASP.NET Core, all the startup logic and application configuration are defined in the ‘Startup.cs’ file. In the ASP.NET Framework, similar configurations might be present in ‘Global.asax’ or ‘.config’ files.</li><li>The project file (‘.csproj’ or ‘.vbproj’) usually contains the target framework for the respective ASP.NET Framework or ASP.NET Core projects. For example, ‘&lt;TargetFamework&gt;net5.0&lt;/TargetFramework&gt;’ indicates an ASP.NET Core project targeting .NET 5.0, whereas ‘&lt;TargetFramework&gt;net472&lt;/TargetFramework&gt;’ indicates an ASP.NET Framework project targeting .NET Framework 4.7.2</li><li>Some new APIs and Features like middleware pipeline, dependency injection, and hosting models are introduced in ASP.NET Core that are not available in ASP.NET Framework</li><li>To manage dependencies, ASP.NET Core uses NuGet Package Manager, while ASP.NET Framework relies more on traditional references to assemblies.</li></ol><p>These are some of the important points to be kept in mind regarding .NET, ASP.NET, and ASP.NET Core while working on your next task.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38405b58701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export millions of records in Excel from SQL Server using ASP.NET Core]]></title>
            <link>https://medium.com/@meghnav274/export-millions-of-records-in-excel-from-sql-server-using-asp-net-core-07cb2de979a0?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/07cb2de979a0</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mini]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 06:40:27 GMT</pubDate>
            <atom:updated>2024-03-19T09:23:14.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Export millions of records in Excel from SQL Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*lyFYDMrqcn7vAHJN.jpg" /></figure><p>We all have encountered a situation where we need to access the data from the database and export it as Excel or CSV files for further processing. Considering the data manipulation ability of Microsoft Excel, it is our go-to choice for handling data. However, if we are required to export huge amounts of records, say millions of records, the memory and time taken to export the data as an Excel file is considerably very large, where we can consider exporting the data as CSV file rather than an Excel file. But, here’s the catch, the maximum limit of rows per sheet in Excel is 1,048,576 rows. So, if you want to export, say 5 million records and you export it as CSV file, the file will get exported easily and even at a reasonable speed for the number of records, but when you’ll open the CSV file, you’ll get the error that some of the data will be lost as. This error occurs because as mentioned excel can only store approx 1 million records per sheet.</p><p>The solution here is that we have to split the data from the table into multiple sheets in Excel file. Here, we will be dealing with a table that consists of 5 million rows and around 36 columns. The idea here is that we will export 1 million records in the first sheet, the next 1 million records in the second sheet, and so on (we will need 5 sheets for 5 million records).</p><p>We will be developing a console application in .NET Core and we’ll be using <a href="https://github.com/mini-software/MiniExcel">MiniExcel</a> Library to export the data to Excel File. MiniExcel is a fast, simple, and low-memory .NET processing Excel tool. We will also be using SSMS to write stored procedures and manipulate the tables.</p><ol><li>I have used a table with 5 million records and around 35 columns for this particular task. We will be creating a temporary table with the id from the main table and a part column. The part column will act as a divider for the records. Each one-million record will have a different part value. For this, we will be writing a stored procedure.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*IMGQyiHX5Ek47Dl4giUGxw.png" /></figure><p>Here, GenerateTempTable is the name of our stored procedure. You can change the value of partition_size variable depending on your use case. We will be selecting id column from dummy_table and creating a new column as part of our new temp_dummy_table. Next, we will be creating indexes on these two columns, as it will ensure faster retrieval of records.</p><p>Upon executing the above stored procedure, we will get the output as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*UErcObndhGDDNT8j97Swdw.png" /></figure><p>The value of Part will be utilized in our console application.</p><pre>CREATE PROCEDURE GenerateTempTable<br>AS<br>BEGIN<br>    SET NOCOUNT ON;<br><br>    -- Drop the temp table if it already exists<br>    IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = &#39;dbo&#39; AND TABLE_NAME = &#39;temp_dummy_table&#39;)<br>    BEGIN<br>        DROP TABLE dbo.temp_dummy_table;<br>    END<br><br>    -- Calculate the total number of rows in the table<br>    DECLARE @total_rows INT;<br>    SELECT @total_rows = COUNT(*) FROM dbo.dummy_table;<br><br>    -- Calculate the number of partitions needed based on the desired partition size (1 million records)<br>    DECLARE @partition_size INT = 1000000; -- 1 million records per partition<br>    DECLARE @ntile_value INT = CEILING(CAST(@total_rows AS DECIMAL) / @partition_size);<br><br>    -- Create the temp table with NTILE partitioning using the calculated ntile_value<br>    SELECT id, NTILE(@ntile_value) OVER (ORDER BY id) AS Part INTO dbo.temp_dummy_table FROM dbo.dummy_table;<br><br>    -- Create clustered index on id<br>    CREATE CLUSTERED INDEX ix_id ON dbo.temp_dummy_table(id);<br><br>    -- Create non-clustered index on part<br>    CREATE NONCLUSTERED INDEX ix_part ON dbo.temp_dummy_table(Part);<br><br> SELECT @ntile_value as Part<br>END<br>GO</pre><p>1. Create a console application in Visual Studio 2022.</p><p>Open Visual Studio 2022 → Create New Project → From Templates select Console App → Click on next → Enter the name of your project and change the location if needed → Click Next → Click on Create. Your project should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmLxjvOk7xYQG-mamWlFcA.png" /></figure><p>2. In order to extract the records from the table, we will need to connect our project to our Database, for that we will be adding an App.config file. To do that, right-click on project name → Add → New Item → Search config → Select Application Configuration File → Click on Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*CDCcvYZK4HjF7uSW2f88IA.png" /></figure><p>3. Next, we need to add the connection string in the App.config file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*9BTlH_4BN6P4P23XzeRVuw.jpeg" /></figure><p>3.1. Add the Data Source — the server name for your Database connection.</p><p>3.2. Add the Initial Catalog (Database) name where your table is present.</p><p>3.3. Add the credentials — UserId and Password used to access your Server.</p><p>4. Now, we need to add the dependencies to our project. We will need the MiniExcel, SqlClient, and Configuration Manager Nuget Packages. To add that, right-click on the project name → Manage Nuget Packages → Nuget Package Manager Console will be opened → Click on Browse → Search MiniExcel → Click on MiniExcel → Install → Click on OK → MiniExcel will be installed. Similarly, search and install System.Data.SqlClient as well as System.Configuration.ConfigurationManager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*6MhLGsb9qRyEENYmVHJhTw.png" /></figure><p>5. To start implementing the functionality, we will be adding a new class to the project. Right-click on project name → Add → Class → Select Class → Give a name to your class → Click on Add. A new class will be added to your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWGjNabcjK7_dsTWodtjYQ.png" /></figure><p>Now, to access this class, we will need to change the access specifier from internal to public. Once that is done, we will write a new method inside which we can extract the data from the table and export it in an Excel file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRPYCG7bkOBJMR1VI42R8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga8iEIsNaNsscGIhqehgYA.png" /></figure><pre>using MiniExcelLibs;<br>using System.Configuration;<br>using System.Data.SqlClient;<br><br>namespace ExcelExportApp<br>{<br>    public class ExportData<br>    {<br>        public void GetData()<br>        {<br>            string currentDate = DateTime.Now.ToString(&quot;yyyyMMddHHmmss&quot;);<br>            string LogFolder = @&quot;D:\ExcelExport\Logs&quot;;<br>            SqlConnection sqlCon; <br>            try<br>            {                <br>                int maxLoopCounter = 0;<br>                string TableName = &quot;dummy_table&quot;;<br>                //Initialize sheets variable to store the data sheet wise<br>                var sheets = new Dictionary&lt;string, object&gt;();<br><br>                string excelFilePath = @&quot;D:\ExcelExport\DataFile.xlsx&quot;;<br><br>                //Get connection string from App.config<br>                string connectionString = ConfigurationManager.ConnectionStrings[&quot;Local&quot;].ConnectionString;<br>                SqlCommand sqlcmd;<br><br>                //Create sqlConnection<br>                sqlCon = new SqlConnection(connectionString);<br>                sqlCon.Open();<br>                sqlcmd = new SqlCommand(&quot;GenerateTempTable&quot;, sqlCon);<br>                sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;<br>                //Setting CommandTimeout = 0 so that the connection won&#39;t close while executing the stored procedure<br>                sqlcmd.CommandTimeout = 0;<br>                //Store value from stored procedure into maxLoopCounter<br>                maxLoopCounter = Convert.ToInt32(sqlcmd.ExecuteScalar());<br><br>                //Fetch the record depending on the number of part value     <br>                for (int i = 1; i &lt;= maxLoopCounter; i++)<br>                {<br>                    string sheetName = &quot;Sheet&quot; + i.ToString();<br>                    //Establish Connection<br>                    sqlCon = new SqlConnection(connectionString);<br>                    sqlCon.Open();<br>                    //Sql Command to extract the data based on part variable. First 1 million records will be fetched and stored in the first sheet and so on.<br>                    sqlcmd = new SqlCommand(@&quot;select a.* from &quot; + TableName + &quot; a inner join temp_&quot; + TableName + &quot; b on a.id = b.id where b.part = &quot; + i + &quot;&quot;, sqlCon);<br>                    sheets.Add(sheetName, sqlcmd.ExecuteReader());<br>                }<br>                //Finally, Saving the excel file with all the sheets.<br>                MiniExcel.SaveAs(excelFilePath, sheets);<br>            }<br>            catch (Exception exception)<br>            {<br>                //Any exception while executing the code, will be logged to the ErrorLog file<br>                using (StreamWriter sw = File.CreateText(LogFolder + &quot;\\&quot; + &quot;ErrorLog &quot; + currentDate + &quot;.log&quot;))<br>                {<br>                    sw.WriteLine(exception.ToString());<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>6. The last step here would be to call our class from the program.cs to execute it. For this, we will make the necessary changes in program.cs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*3s4Pkz-YFiJM8BBc1hlZrA.png" /></figure><pre>namespace ExcelExportApp<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            ExportData exportData = new ExportData();<br>            //Call method in the class<br>            exportData.GetData();<br>        }<br>    }<br>}</pre><p>7. Lastly, we have to execute this console application. This application takes around <strong>6–7 minutes</strong> to extract <strong>5 million</strong> records from the table and export it in an Excel File.</p><p>OUTPUT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4il91gCVqeZRfQLTvbUjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUZ9HdIkj8va9Xc-ZBOwfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmTestCwDfLNMwGmXPxAOA.png" /></figure><p>Source code for reference:</p><p><a href="https://github.com/Meghna2704/ExcelExportApp">GitHub - Meghna2704/ExcelExportApp: This project creates an excel file with 5 million records using asp.net core console application</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07cb2de979a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Google reCAPTCHA using ASP.NET Core Web]]></title>
            <link>https://medium.com/@meghnav274/implementing-google-recaptcha-using-asp-net-core-web-24f539ba4987?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f539ba4987</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[recaptcha]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 07:02:15 GMT</pubDate>
            <atom:updated>2024-03-19T09:34:44.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Google reCAPTCHA using ASP.NET Core Web API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*xjQlC37LGnxBHYKspZfCRQ.png" /></figure><p>Designed a form but worried that the website may face bot attacks or other automated attacks and submit irrelevant data to your backened? Well, Google reCaptcha provides a solution to this very problem.</p><p>Google reCaptcha is a system that helps detect fraud and only allows legitimate users to enter your system and use your login page, submit any form, make some kind of payment, view some pages, and many more blocking fake users.</p><p>Now, let’s talk about implementing reCaptcha in your project. We will be implementing frontend using HTML, CSS, and Javascript and for backend we will be using ASP.NET Core Web API.</p><p>The implementation part is quite easy. Google provides an API for reCaptcha generation in a javascript file whose link has to be included in your HTML code.</p><p>We will start by creating a simple Login Form using HTML and CSS.</p><p>I have created this Login Form in which we will add the Google reCaptcha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*jfeI2CqiDgqXELe2VVgFKQ.png" /></figure><p>To add Google reCaptcha, you would first need to create the key that we will be using later on in the code.</p><p>To create a new key, visit the following URL:</p><p><a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></p><p>If you are already signed in with your Google account, a register dashboard will be visible, else you will need to log in first with your Google account.</p><p>This is the register key dashboard, here you have to enter basic information like Label, reCaptcha type, and domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC04uPSUcF31SORjZ3gI5g.png" /></figure><ol><li>The label can be any name that you want to assign to your key.</li><li>There are two types of reCaptcha provided by Google, v3 and v2. We would be using v2 “I am not a Robot” checkbox.</li><li>In the Domains field, you need to specify for which domain you need to use the Google reCapthca. E.g. your website name is : <br><em>https://your-website.com/index.html</em> — here you only need to enter <br>your-website.com as domain.<br>Here as I am implementing reCaptcha for demonstration purposes, I’ll be running my application in the local environment for which I have used 127.0.0.1 as domain.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*9NE5ULaV4pAKye9-EeZLwg.png" /></figure><p>After filling in all the details, click on submit. You will have two keys, the Site key which is used on the client side, and the Secret key which is used on the server side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*MwL2LLR0BWOZ_OLQDisMZA.png" /></figure><p>Coming back to the coding side, you will need to add this line of code where you want to place your reCaptcha, I am adding it before the Login button.</p><pre>&lt;div class=&quot;g-recaptcha&quot; data-sitekey=add_your_sitekey&gt;&lt;/div&gt;</pre><p>After adding this div class at the desired location, add a javascript file to call the Google reCaptcha API.</p><pre>&lt;script type=&quot;text/javascript&quot; src=&quot;https://www.google.com/recaptcha/api.js&quot;&gt;&lt;/script&gt;</pre><p>This is how the login page looks after adding reCaptcha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*DfS8Kj1_QJWr_gktt5gW-Q.png" /></figure><p>You can find the code for HTML(index.html) and CSS(style.css) files below:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Login Page&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;    <br>    &lt;script type=&quot;text/javascript&quot; src=&quot;https://www.google.com/recaptcha/api.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;login-page&quot;&gt;<br>        &lt;div class=&quot;form&quot;&gt;      <br>          &lt;div class=&quot;login-form&quot;&gt;<br>            &lt;input type=&quot;text&quot; placeholder=&quot;Username&quot;/&gt;<br>            &lt;input type=&quot;password&quot; placeholder=&quot;Password&quot;/&gt;<br>            &lt;div class=&quot;g-recaptcha&quot; data-sitekey=&quot;6LfU_xMpAAAAADmXvZq0VqCVLIyJz3x6V8dUQeZ8&quot;&gt;&lt;/div&gt;&lt;br&gt;<br>            &lt;button onclick=&quot;LoginButton()&quot;&gt;Login&lt;/button&gt;            <br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br><br></pre><pre>@import url(https://fonts.googleapis.com/css?family=Roboto:300);<br><br>.login-page {<br>  width: 360px;<br>  padding: 8% 0 0;<br>  margin: auto;<br>}<br>.form {<br>  position: relative;<br>  z-index: 1;<br>  background: rgb(116, 223, 187);<br>  max-width: 360px;<br>  margin: 0 auto 100px;<br>  padding: 30px;<br>  text-align: center;<br>  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);<br>}<br>.form input {<br>  font-family: &quot;Roboto&quot;, sans-serif;<br>  outline: 0;<br>  background: #f2f2f2;<br>  width: 100%;<br>  border: 0;<br>  margin: 0 0 15px;<br>  padding: 15px;<br>  box-sizing: border-box;<br>  font-size: 14px;<br>}<br>.form button {<br>  font-family: &quot;Roboto&quot;, sans-serif;<br>  text-transform: uppercase;<br>  outline: 0;<br>  background: rgb(8, 103, 116);<br>  width: 100%;<br>  border: 0;<br>  padding: 15px;<br>  color: #FFFFFF;<br>  font-size: 14px;<br>  -webkit-transition: all 0.3 ease;<br>  transition: all 0.3 ease;<br>  cursor: pointer;<br>}<br>.form button:hover,.form button:active,.form button:focus {<br>  background: #073b44;<br>}<br><br>.container {<br>  position: relative;<br>  z-index: 1;<br>  max-width: 300px;<br>  margin: 0 auto;<br>}</pre><p>The frontend part is now completed, after this, we will be using javascript to get the response from reCaptcha and then validate the response on the backend using the secret key.</p><p>I have added an onclick function on the Login button which will fetch the response from reCaptcha and make an ajax call to our API. You can also add other features here, like disabling the login button until all three fields are filled depending on your requirements. Here, we are keeping things simple and displaying an alert on successful or unsuccessful validation of reCaptcha.</p><p>For API side, we are using ASP.NET Core and Visual Studio 2022, you can refer the first part (Step 1) of my <a href="https://medium.com/@meghnav274/simple-jwt-authentication-using-asp-net-core-api-5d04b496d27b">article</a> which will guide you on how you can create an API project using Visual Studio 2022.</p><ol><li>Go to appsettings.json and add your secret key.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ZB3RJQ2PGcunFHq36XYPKQ.png" /></figure><pre>&quot;reCaptcha&quot;: {<br>    &quot;SecretKey&quot;: Your_Secret_Key, <br>  },</pre><p>2. Create a new Controller. You can follow these steps:<br>​​​​Right Click on Controllers folder -&gt; Add -&gt; Controller -&gt; Select Empty API Controller -&gt; Give a name to the Controller (I have named it UserController).</p><p>Once your controller is created, it will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*6lj-gal04tYi0c5URxwYJQ.png" /></figure><p>3. Add the logic to validate reCaptcha in controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*AVx7qlXqQditMYEs5jvfQg.png" /></figure><ol><li>Here, we have injected Configuration to fetch Secret Key from appsettings.json and HttpClient to post our result to the google API endpoint.</li><li>We have created a method named ‘GetreCaptchaResponse’ which accepts the reCaptcha response which will be sent from the front end. Next, we are creating a content variable in which we will store our response and the secret key.</li><li>Google has provided an API endpoint (<a href="https://www.google.com/recaptcha/api/siteverify">https://www.google.com/recaptcha/api/siteverify</a>) where the response and secret key should be passed and it will give you the result in json format. You can visit <a href="https://developers.google.com/recaptcha/docs/verify">this </a>page to learn more about it. <br>We are passing our content to this api and storing the result in response variable.</li><li>If this response is successful, then we are reading the Success and Error codes and storing it in result variable.</li></ol><p>You can find the entire code below.</p><pre>using Microsoft.AspNetCore.Authorization;<br>using Microsoft.AspNetCore.Http;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace reCaptchaAPI.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class UserController : ControllerBase<br>    {<br>        private readonly IConfiguration _configuration;<br>        private readonly HttpClient _httpClient;<br>        public UserController(IConfiguration configuration, HttpClient httpClient)<br>        {<br>            _configuration = configuration;<br>            _httpClient = httpClient;<br>        }<br>        [HttpGet(&quot;Captcha&quot;)]<br>        public async Task&lt;bool&gt; GetreCaptchaResponse(string userResponse)<br>        {<br>            var reCaptchaSecretKey = _configuration[&quot;reCaptcha:SecretKey&quot;];<br><br>            if(reCaptchaSecretKey != null &amp;&amp; userResponse != null)<br>            {<br>                var content = new FormUrlEncodedContent(new Dictionary&lt;string, string&gt;<br>                {<br>                    {&quot;secret&quot;, reCaptchaSecretKey },<br>                    {&quot;response&quot;, userResponse }<br>                });<br>                var response = await _httpClient.PostAsync(&quot;https://www.google.com/recaptcha/api/siteverify&quot;, content);<br>                if(response.IsSuccessStatusCode)<br>                {<br>                    var result = await response.Content.ReadFromJsonAsync&lt;reCaptchaResponse&gt;();<br>                    return result.Success;<br>                }<br>            }<br>            return false;<br>        }<br><br>        public class reCaptchaResponse<br>        {<br>            public bool Success { get; set; }<br>            public string[] ErrorCodes { get; set; }<br>        }<br>    }<br>}</pre><p>​ 5. Next step is to register HttpClient middleware in our program.cs and also as we would be hitting this API from our front end, we have to specify CORS (Cross Origin Resource Sharing) which will help you to access API from your frontend code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*yIU8Q6KNpNe3pA8GUeNklQ.png" /></figure><p>​To specify CORS:</p><pre>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddDefaultPolicy(<br>        policy =&gt;<br>        {<br>            policy.AllowAnyOrigin()<br>                .AllowAnyHeader()<br>                .AllowAnyMethod();<br>        });<br>});<br><br>app.UseCors();</pre><p>​​ ​ ​To register HttpClient Middleware:</p><pre>builder.Services.AddHttpClient();</pre><p>Your API Project is now completed. You can run and test it once using swagger.</p><p>The only thing remaining now is writing an ajax call to implement the API. We are going to add an onclick function for Login Button and define the ajax call in the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*pUpys--H5aRd1NbS5sBgGA.png" /></figure><p>Here, we are getting the reCaptcha response and sending this as parameter to the API. You can run your API project and a Swagger page will be opened, from where you can copy the localhost url and use here. Please make sure that you name the endpoint correctly!</p><p>After making these changes and running the application, we will get an alert as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*uL87io0bDsWNA3l6xpXcCw.png" /></figure><p>Javascript (script.js) code is as follows:</p><pre>function LoginButton(){<br>    const reCaptchaResponse = grecaptcha.getResponse();<br>    if(reCaptchaResponse){<br>        $.ajax({<br>            type: &quot;GET&quot;,<br>            url: &quot;https://localhost:44317/api/User/Captcha&quot;,<br>            data: {userResponse : reCaptchaResponse},            <br>            success: function(data){<br>                if(data){<br>                    //API returned true<br>                    alert(&quot;Captcha Verified&quot;);<br>                }else{<br>                    //API returned false<br>                    alert(&quot;Please verify captcha again&quot;);<br>                }               <br>            },<br>            error: function(error){<br>                alert(&quot;Please try again&quot;);<br>            }<br>        });<br>    }<br>    else{<br>        alert(&quot;Something went wrong with reCaptcha. Please try again!&quot;);<br>    }<br>}</pre><p>Please refer the source code for this application:</p><p><a href="https://github.com/Meghna2704/reCaptcha">GitHub - Meghna2704/reCaptcha: This project shows how to implement the google reCaptch functionality</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f539ba4987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Authorization Option in Swagger]]></title>
            <link>https://medium.com/@meghnav274/adding-authorization-option-in-swagger-638abfb0041f?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/638abfb0041f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 07:19:49 GMT</pubDate>
            <atom:updated>2023-10-31T07:19:49.573Z</atom:updated>
            <content:encoded><![CDATA[<p>Implemented the authentication mechanism to secure your API endpoints, but confused about how can we use the token provided by your authentication scheme in order to access other APIs that are actually authorized ?</p><p>This confusion can be common for the newbies in ASP.NET programming. Especially, while implementing the Authentication and Authorization mechanism. It is actually quite simple to add the Authorize option in your swagger in order to provide the token and authorize the endpoints in your application.</p><p>In my previous medium story, I talked about how can we implement the JWT Authentication using ASP.NET Core and access the token provided after the successful authentication of the user. You can go through the story below in case of any confusion on implementing the JWT Authentication mechanism.</p><p><a href="https://medium.com/@meghnav274/simple-jwt-authentication-using-asp-net-core-api-5d04b496d27b">https://medium.com/@meghnav274/simple-jwt-authentication-using-asp-net-core-api-5d04b496d27b</a></p><p>In this article, we will see how can we make use of this token to access the restricted endpoints that have the [Authorize] attribute applied to it.</p><p>To add the authorize option in Swagger, you have to add the below line of code in Program.cs</p><ol><li>The AddSwaggerGen Method is used to configure Swagger. This part configures the swagger generation for your application and specifies the title to be provided for the API documentation.</li><li>This part adds a security definition to the Swagger documentation. In this case, it defines how to use a Bearer token for authorization. It specifies that the token should be provided in the “Authorization” header with a format of “JWT.” It specifies a description that will be visible in the swagger documentation.</li><li>This part specifies the security requirements for your API endpoints. It states that the “Bearer” security scheme is required for all API endpoints. This informs the user that you have to use “Bearer” keyword before providing the token in order to authenticate the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*8IwHjigQ-NLcZk1TTKr-sw.png" /></figure><pre>builder.Services.AddSwaggerGen(c =&gt; {<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo<br>    {<br>        Title = &quot;JWTToken_Auth_API&quot;,<br>        Version = &quot;v1&quot;<br>    });<br>    c.AddSecurityDefinition(&quot;Bearer&quot;, new OpenApiSecurityScheme()<br>    {<br>        Name = &quot;Authorization&quot;,<br>        Type = SecuritySchemeType.ApiKey,<br>        Scheme = &quot;Bearer&quot;,<br>        BearerFormat = &quot;JWT&quot;,<br>        In = ParameterLocation.Header,<br>        Description = &quot;JWT Authorization header using the Bearer scheme. \r\n\r\n Enter &#39;Bearer&#39; [space] and then your token in the text input below.\r\n\r\nExample: \&quot;Bearer 1safsfsdfdfd\&quot;&quot;,<br>    });<br>    c.AddSecurityRequirement(new OpenApiSecurityRequirement {<br>        {<br>            new OpenApiSecurityScheme {<br>                Reference = new OpenApiReference {<br>                    Type = ReferenceType.SecurityScheme,<br>                        Id = &quot;Bearer&quot;<br>                }<br>            },<br>            new string[] {}<br>        }<br>    });<br>});</pre><p>After adding this code, run the solution and you’ll see an Authorize button available in the top right of your Swagger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzE61zI9Otmz9MSbJtvu4A.png" /></figure><p>Click on the button and a dialog box will open in which you have to enter your token after the “Bearer” keyword. You can also read the description of how you have to enter the token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*vvg_wUUUfImkmJHWiF7PAA.png" /></figure><p>After the Authorize option is added to your swagger, you need to specify the authentication and authorization techniques that you would be using in the Program.cs file.</p><p>Here, the AddAuthentication configures the authentication services for your application. It specifies the default authentication, challenge and scheme to be used is JWT Bearer.</p><p>The further part of the code specifies the settings for how to manipulate the JWT Token. It accesses the key that is stored in appsettings.json as:</p><pre> &quot;Jwt&quot;: {<br>    &quot;Key&quot;: &quot;3713ab7f791c1991d3a210c5fa68c3aa&quot;<br>  },</pre><p>Next, it Adds the Authorization in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*wriei_yLDMvF2DuDeJfrFw.png" /></figure><pre><br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;<br>    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;<br>    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;<br>}).AddJwtBearer(o =&gt;<br>{<br>    o.RequireHttpsMetadata = true;<br>    o.SaveToken = true;<br>    o.TokenValidationParameters = new TokenValidationParameters<br>    {<br>        ValidateIssuerSigningKey = true,<br>        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration[&quot;Jwt:Key&quot;])),<br>        ValidateIssuer = false,<br>        ValidateAudience = false<br>    };<br>});<br><br><br>builder.Services.AddAuthorization();</pre><p>Next, you can add a simple method in the controller with [Authorize] Attribute and try to access this using both, without passing the token and then by passing the token.</p><pre>        [Authorize]<br>        [HttpGet(&quot;Demo&quot;)]<br>        public IActionResult Demo()<br>        {<br>            return Ok(&quot;User Authenticated Successfully!&quot;);<br>        }</pre><p>After adding this, run the solution and go to Swagger, expand the Demo API request, and click on Execute. You will get a 401 response which means Unauthorized. You are facing this error response as the user is not authenticated providing the token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXu9HjCGzkVrZLEeqO4wBg.png" /></figure><p>Next, you can authenticate the user by providing the token with “Bearer” Keyword and try to execute the API again. Once the user is authenticated, you will get a 200 Success Response, which means that the API is successfully authenticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbyT_BuQ6uKOam_YvSoESw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=638abfb0041f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple JWT Authentication using ASP.NET Core Web API]]></title>
            <link>https://medium.com/@meghnav274/simple-jwt-authentication-using-asp-net-core-api-5d04b496d27b?source=rss-49f513f9e556------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d04b496d27b</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[visual-studio]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Meghna]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 06:04:08 GMT</pubDate>
            <atom:updated>2024-03-19T10:42:41.248Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a step-by-step tutorial on implementing JWT Authentication using ASP.NET Core Web API. We won’t be using any additional Data Base Connection and will define the user credentials in the code for simplicity.</p><p>JWT Authentication is a popular method to provide authentication while exchanging data between two parties. It is a token-based stateless authentication mechanism. JWT is mostly used for API authentication and server-to-server authentication.</p><p><strong>Step 1: Create a new Project</strong></p><p>Start Visual Studio 2022</p><p>Create a new Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORmL3mQD88i5gaHx2VovWw.jpeg" /></figure><p>Select ASP.NET Core Web API and click on Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5KJ6UoY8D-UkBtVqai3jQ.png" /></figure><p>Enter the project name and Location as per your preference and click on Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7N8tdR45p4cE-HyPOtPDmg.png" /></figure><p>Select the framework (I’ve used .NET 7.0) and click on Create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDLPKsA6UszmM2y94e8sAA.png" /></figure><p>You’ll get a default Web API Project. You can delete the default WeatherForecastController.cs and WeatherForecast.cs to avoid any sort of confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAP8B43xHuWBH9P7ucbclA.png" /></figure><p><strong>Step 2: Manage NuGet Packages</strong></p><p>From Solution Explorer, right-click on the Dependencies and select “Manage Nuget Packages”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*MK9rE2TYPk7v88mylBgVnw.png" /></figure><p>A NuGet Package Manager Window will be opened. Click on Browse and Search JWTBearer, and you’ll get the results. From results select Microsoft.AspNetCore.Authentication.JwtBearer and click on install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjIwgWeIt040EE-2P9xP1w.png" /></figure><p>From the License Acceptance Dialog Box, click on “I Accept” and the installation will be started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*5nJGkD7DZJEoQMksICR19g.png" /></figure><p><strong>Step 3: Start Coding :-)</strong></p><p>In order to apply JWT Authentication, we have to provide a key for JWT to work. This key will be used every time to provide a token upon successful login from the user.</p><p>The key can be anything — It can be your name, any other significant text or number in your project or you can also provide any randomly generated hash value.</p><p>I’ve used a random <a href="https://onlinehashtools.com/generate-random-md5-hash">MD5 Hash generator online tool</a> that provides 10 random hash values by default, you can select any one value from this, or you can also change the number of hash values generated from the settings provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*n5XFOvWorJCEwH_JTfBCHw.png" /></figure><p>Now, open the appsettings.json file and add a section for JWT key</p><figure><img alt="Please change the key value as per your preference" src="https://cdn-images-1.medium.com/max/645/1*634U4doy2hObu6gNgb3dBw.png" /></figure><pre>&quot;Jwt&quot;: {<br>    &quot;Key&quot;: &quot;3713ab7f791c1991d3a210c5fa68c3aa&quot;<br>  },</pre><p>When the user tries to access the API, we have to take the user credential as input and use it further to authenticate the user. To achieve this, we will create a user model class consisting of a Username and Password and store the input from the user in this model class.</p><p>To create a user model class, right-click on the project name -&gt; Add -&gt; Class, and a new window will appear, select “class” and give an appropriate name (e.g. User.cs) and click on “Add”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*rpbouz_DbrxsYpl_kNQeyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*t-kTCbwiMJ_HEoqUjKM3cg.png" /></figure><p>We have to create two properties for user authentication — UserName and Password, which can be done as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*uJPySWOSYPID9I34Ly2HwA.png" /></figure><pre>namespace JWT_Authentication<br>{<br>    public class User<br>    {<br>        public string UserName { get; set; }<br>        public string Password { get; set; }<br>    }<br>}</pre><p>Now, we have to write the actual code for Implementing JWT Authentication and returning the token after validating the user.</p><p>For this, you can create a Folder by right-clicking on the project name and selecting “Add new folder”. We will be naming this folder “Services”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*ZbIWke42IPVa2zsAMO1wSw.png" /></figure><p>After the Services Folder is created, we have to add a service and an interface to implement this service. In order to do that, we have to right-click on the Services folder -&gt; Add -&gt; New Item -&gt; Select Interface -&gt; Give a name for this interface -&gt; Add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*Ui3J6fb-Wo03KlReUE3wUw.png" /></figure><p>This interface will be implementing the Login Service and we need to pass the User model to this interface. We are returning the token from the service so we will be keeping the return type as string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*GxvMagY3gZAdB-iXVycQkQ.png" /></figure><pre>namespace JWT_Authentication.Services<br>{<br>    public interface IUserService<br>    {<br>        string Login(User user);<br>    }<br>}</pre><p>For the next step, we have to add a UserService File in the Services Folder. To do this, we have to right-click on Services -&gt; Add -&gt; Class, a new class dialog box will appear, here we have to name the service “UserService. cs” and click on “Add”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*jOwHIYfnp6UJwtW_e8om6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*vNz_s0XnX_BXUPrEDwhQkA.png" /></figure><p>In this UserService.cs, we have to implement the JWT functionality.</p><ol><li>You will get the following code generated by default in UserService.cs. Here, we have to implement the IUserService.cs interface.</li></ol><pre>namespace JWT_Authentication.Services<br>{<br>    public class UserService<br>    {<br>    }<br>}</pre><p>2. Hover over the IUserService and click on “Implement interface”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*W08eMPFccwZl414Z0ap7Jw.png" /></figure><p>3. Create a new List of User Class Model to assign a UserName and Password against which the incoming user request will be validated. You can change the UserName and Password according to your preference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*m_BGdlg0bWick9q47gVR2A.png" /></figure><p>4. In order to access the JWT Key from the appsettings.json, we have to inject the Configuration as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*zcK2ZiiYSElpaWUodS52oA.png" /></figure><p>5.</p><ol><li>The login user will check whether the incoming data matches the predefined credentials i.e. “Admin” and “Password” in this case.</li><li>If the loginUser is null, it means the credentials are different and it will return an empty string.</li><li>If loginUser contains some value, we will generate a new JwtTokenHandler and assign it to tokenHandler.</li><li>We will access the JWT key from appsettings and store it in a variable named key.</li><li>We will create a new token descriptor where we will assign the UserName as a claim.</li><li>We have to assign the Expiry time, which can be set as per your preference.</li><li>Using the appropriate Security Algorithm, new signing credentials will be created</li><li>Using the token descriptor parameter, we will create a new token.</li><li>Store this token in a variable and return it upon successfully validating the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*t369pU4WL47bdJzi9Qu83g.png" /></figure><pre>using Microsoft.IdentityModel.Tokens;<br>using System.IdentityModel.Tokens.Jwt;<br>using System.Security.Claims;<br>using System.Text;<br><br>namespace JWT_Authentication.Services<br>{<br>    public class UserService : IUserService<br>    {<br>        private List &lt;User&gt; _users = new List&lt;User&gt;<br>        { <br>            new User{ UserName = &quot;Admin&quot;, Password = &quot;Password&quot;}<br>        };<br><br>        private readonly IConfiguration _configuration;<br><br>        public UserService(IConfiguration configuration)<br>        {<br>            _configuration = configuration;<br>        }<br><br>        public string Login(User user)<br>        {<br>            var LoginUser = _users.SingleOrDefault(x =&gt; x.UserName == user.UserName &amp;&amp; x.Password == user.Password);<br><br>            if(LoginUser == null)<br>            {<br>                return string.Empty;<br>            }<br><br>            var tokenHandler = new JwtSecurityTokenHandler();<br>            var key = Encoding.ASCII.GetBytes(_configuration[&quot;Jwt:Key&quot;]);<br>            var tokenDescriptor = new SecurityTokenDescriptor<br>            {<br>                Subject = new ClaimsIdentity(new Claim[]<br>                {<br>                    new Claim(ClaimTypes.Name, user.UserName)<br>                }),<br>                Expires = DateTime.UtcNow.AddMinutes(30),<br>                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)<br>            };<br>            var token = tokenHandler.CreateToken(tokenDescriptor);<br>            string userToken = tokenHandler.WriteToken(token);<br>            return userToken;<br>        }<br>    }<br>}</pre><p>To register the service, we have to add the following line of code in Program.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*sD1dfm7yfW-67eoGZIFZgw.png" /></figure><pre>builder.Services.AddScoped&lt;IUserService, UserService&gt;();</pre><p>6. In order to implement the service we have just created, we will create a controller, which will take the user credentials as input and provide the token.</p><p>To create a new controller, right-click on the controllers folder -&gt; Add -&gt; Controller. From the controller dialog box, select API Controller — Empty Controller -&gt; Add. Let’s name this controller “UserController.cs” and then click on Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*JbL_gyt8MHmSTyhmBn16-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*mZ1khEOQuVh-OlImG8X3FA.png" /></figure><p>7. In the newly created User Controller, we must inject the service as we have to use the UserService. Then, we will create a new Login Method which has to use the [AllowAnonymous] attribute, as this method will be passing the token and should be accessible to anyone to access the token.</p><ol><li>Injecting the UserService.</li><li>Specifies the “Post” request and uses “Login” as the route.</li><li>Passing the User model as a parameter to the Login Method.</li><li>Calling the Login method of User Service and passing the user model as a parameter.</li><li>If the Service returns null or empty, it did not find the matching credentials to validate.</li><li>Returning token upon successfully authenticating the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*B-rEJY_1LMQhfWCdX8Qjzg.png" /></figure><pre>using JWT_Authentication.Services;<br>using Microsoft.AspNetCore.Authorization;<br>using Microsoft.AspNetCore.Http;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace JWT_Authentication.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class UserController : ControllerBase<br>    {<br>        private readonly IUserService _userService;<br>        public UserController(IUserService userService)<br>        {<br>            _userService = userService;<br>        }<br><br>        [HttpPost(&quot;Login&quot;)]<br>        [AllowAnonymous]<br>        public IActionResult Login(User user)<br>        {<br>            var token = _userService.Login(user);<br>            if(token == null || token == string.Empty)<br>            {<br>                return BadRequest(new { message = &quot;UserName or Password is incorrect&quot; });<br>            }<br>            return Ok(token);<br>        }<br>    }<br>}</pre><p>8. After completing this, run the solution. A swagger page will be opened in your default browser. We can use this swagger to test our API endpoints.</p><p>Expand the “/api/User/Login” Post request that would be visible in Swagger and click on “Try it out”. Enter your credentials, the ones that we have mentioned while creating the UserService (in this case UserName = “Admin” and Password = “Password”) and click on “Execute”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JlaEc7PGKQN2Xm1uqm3wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4jxnZwAAtlgssS9R2uXdQ.png" /></figure><p>In the response body, we will get the Token that can be used to access any other endpoints that contain some sensitive data and that needs to be Authorized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLLUyowZh8sxdo7Iba2HsA.png" /></figure><p>In this way, we have implemented the JWT Authentication using ASP.NET Core and have received the token upon successful authentication of user. Here is the source code link for reference:</p><p><a href="https://github.com/Meghna2704/JWT_Authentication_v1">GitHub - Meghna2704/JWT_Authentication_v1: This proect showcases the implementation of JWT Authentication using asp.net</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d04b496d27b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>