Interpolation in middle of string

i want make interpolation in middle of string, i can't use string.Format because my string have {} brackets (javascript code)

i want make interpolation in middle of string, i can't use string.Format because my string have {} brackets (javascript code)

I tried this: string code = "(function(){var myvariable = $"{myvariable}"});"

Returns: ) expected ; expected

My code:

string code = "(function(){var myvariable = (variable in c#)});"


Create a desktop app with Electron, React and C#

Create a desktop app with Electron, React and C#

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

First years in my software craftsmanship started with Delphi 7. It was amazing, it was time when the internet was semi-empty. It was hard to find examples, ask help, basically, you were on your own. Ohh good old times, I wouldn’t change that experience, but I wouldn’t want to do that again.

Time goes on, everything evolves, new technologies come in play. Time to time, I stop and look at what has been changed. And that is so cool, always there is something new to look into. To change my own biases, yes painful, but the world isn’t stuck in time warp.

Ladies and gentlemen I bring to you my experience with Electron.

What is an Electron

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

This is amazing, you can be a web app developer and by reusing the same skillset you can build a desktop app.

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.### The project

Let us create an empty npm project

npm init --yes

Add Electron stuff and start command

npm i -D electron

Add start script inside package.json

"start":"electron ."
{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "electron": "^4.0.6"
  }
}

If we execute the npm start, we should get a popup error from Electron. That is ok, this only means that Electron is alive and we don’t know how to boot it.

The main and renderer process

Before we dive into coding, it is important to understand the basics of Electrons architecture.

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.
My oversimplified explanation would be. There is a main process which creates a window and that window is a Chromium. Where Chromium is a process by itself aka renderer.

Typescript

Starting from the 1 June of the year 2017, Electron supports Typescript. Good, let’s use it.

npm i -D typescript
npm i -D tslint
npm i -D prettier

Add tslint.jsonin the project root

{
  "extends": "tslint:recommended",
  "rules": {
    "max-line-length": {
      "options": [
        120
      ]
    },
    "new-parens": true,
    "no-arg": true,
    "no-bitwise": true,
    "no-conditional-assignment": true,
    "no-consecutive-blank-lines": false
  },
  "jsRules": {
    "max-line-length": {
      "options": [
        120
      ]
    }
  }
}

Add tsconfig.json in the root of the project

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

For typescript compilation, tsc could be used, but as the end game is to use React and manipulate with templates. Webpack is the way to go this time.

Web pack

Setup for the web pack

npm i -D webpack webpack-cli
npm i -D html-webpack-plugin
npm i -D @babel/cli @babel/core @babel/preset-env babel-loader @babel/plugin-proposal-class-properties @babel/plugin-transform-arrow-functions
npm i -D @babel/preset-typescript



Add .babel.rc in the root of the project

{
  "presets": [
    "@babel/env",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

So far so good, now let us create a main process of Electron and say hello to Mom!

Create a folder src

Add main.ts file in src folder

const url = require("url");
const path = require("path");

import { app, BrowserWindow } from "electron";

let window: BrowserWindow | null;

const createWindow = () => {
  window = new BrowserWindow({ width: 800, height: 600 });

  window.loadURL(
    url.format({
      pathname: path.join(__dirname, "index.html"),
      protocol: "file:",
      slashes: true
    })
  );

  window.on("closed", () => {
    window = null;
  });
};

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (window === null) {
    createWindow();
  }
});

line 8 creating a window and loading index.html into window aka Chromium.

Add index.html to the src folder

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hi mom</title>
  </head>
  <body>
    <h1>Hi mom!</h1>
  </body>
</html>

Add webpack.config.js in the root. Instruction for the web pack how to handle Electrons main process build. Important target:"electron-main"

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html",
  inject: false
});

const config = {
  target: "electron-main",
  devtool: "source-map",
  entry: "./src/main.ts",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  node: {
    __dirname: false,
    __filename: false
  },
  plugins: [htmlPlugin]
};

module.exports = (env, argv) => {
  return config;
};

Adjust a bit package.json

{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build": "webpack --mode development",
    "start": "electron ./dist/main.js"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-typescript": "^7.3.3",
    "babel-loader": "^8.0.5",
    "electron": "^4.0.6",
    "html-webpack-plugin": "^3.2.0",
    "prettier": "^1.16.4",
    "tslint": "^5.13.1",
    "typescript": "^3.3.3333",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  }
}

Execute commands

npm run build
npm run start

And here it is. A fully functional desktop application. Which is saying hi to mom.

And this is actually the place where your front end developer skills kick in. As it is a Chromium you can use any kind of frontend technology, React, Vue, Angular, plain javascript.

The React

React will live in Electrons renderer process for that reason we will have to create a separate web pack build configuration. And teach babel to use react loader

npm i -D @babel/preset-react
npm i -S react react-dom
npm i -D @types/react @types/react-dom

Adjust.babelrc

{
  "presets": [
    "@babel/env",
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Adjust webpack.config.js by removing the responsibility of index.html template generation. It is the responsibility of the renderer build process.

const path = require("path");

const config = {
  target: "electron-main",
  devtool: "source-map",
  entry: "./src/main.ts",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  node: {
    __dirname: false,
    __filename: false
  }
};

module.exports = (env, argv) => {
  return config;
};

Add new web pack config file webpack.react.config.js . This configuration is responsible for compiling react stuff and making sure that compiled result is injected insideindex.html

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

const config = {
  target: "electron-renderer",
  devtool: "source-map",
  entry: "./src/app/renderer.tsx",
  output: {
    filename: "renderer.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  plugins: [htmlPlugin]
};

module.exports = (env, argv) => {
  return config;
};

Adjust index.html so that it contains a container where React can place its component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hi mom</title>
  </head>
  <body>
    <div id="renderer"></div>
  </body>
</html>

Create a folder app inside src and create renderer.tsx

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import {Dashboard} from "./components/Dashboard";

ReactDOM.render(<Dashboard />, document.getElementById('renderer'));

Now let’s say Hello mom again, only now we will use a React to do so.

Create a folder components inside app and create Dashboard.tsx

import * as React from 'react';

export const Dashboard = () => {
    return <div>Hello Mom!</div>;
};

Adjust the package.json and add a new command so we can compile the renderer.

{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build:react": "webpack --mode development --config webpack.react.config.js",
    "build": "webpack --mode development",
    "start": "electron ./dist/main.js"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "@babel/preset-typescript": "^7.3.3",
    "@types/react": "^16.8.6",
    "@types/react-dom": "^16.8.2",
    "babel-loader": "^8.0.5",
    "electron": "^4.0.6",
    "html-webpack-plugin": "^3.2.0",
    "prettier": "^1.16.4",
    "tslint": "^5.13.1",
    "typescript": "^3.3.3333",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  },
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  }
}
npm run build:react
npm run build
npm run start

Now, this is something I don’t see every day. A native desktop app running React inside of it. Well maybe I do, I just don’t know it as Electron is a popular framework and is used all over the place. For example, Visual Studio code, try to guess what is powering it ;).

The C# what?

A blog post by Rui Figueiredo ignited my interest in Electron.

Electron using C#. That is an interesting synergy going on here. And as it is C# core, it is cross-platform as well.

Cross-platform desktop app powered by Electron using React for UI and extended functionality by C# goodness. And now not only you can use your frontend skills, but backend as well.

Install new package for npm project

npm i -D electron-cgi

Adjust main.ts for a test run, we will send Mom to C# console app and it will return Hello Mom back. And we will console log that.

const { ConnectionBuilder } = require("electron-cgi");

...

let connection = new ConnectionBuilder()
  .connectTo("dotnet", "run", "--project", "./core/Core")
  .build();

connection.onDisconnect = () => {
  console.log("lost");
};

connection.send("greeting", "Mom", (response: any) => {
  console.log(response);
  connection.close();
});

Create a simple dotnet C# core console app. Add ElectronCgi.DotNet nuget.

using ElectronCgi.DotNet;

namespace Core
{
    class Program
    {
        static void Main(string[] args)
        {
            var connection = new ConnectionBuilder()
                .WithLogging()
                .Build();
            
            connection.On<string, string>("greeting", name => "Hello " + name);
            
            connection.Listen();    
        }
    }
}
npm run build
npm run start

Amazing isn’t it? Rui did go an extra mile and added this to C# as well

connection.OnAsync();

Now we are talking serious stuff. Imagen what possibilities this opens? Async communication to a database, to Rest API, to Queues, all nice packages for clouds, Amazon, Azure etc. All the good stuff from C# at your fingertips.

And it is not limited only to sending strings, it can be strongly typed object in C#.

Here is how

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.
Heavy use of stdout. Which isn’t necessarily something bad, for example, php.exe and the frameworks which surround it ;).

I generally like the approach, clean, smart and innovating. I do endorse read a full blog post of Rui.

Extra mile with React and C#

Let’s make this even interesting, send the message to React from C#.

For that make changes in renderer by changing the Dashboard functional component to a component with the state.

import * as React from "react";
import { ipcRenderer } from "electron";

interface IState {
  message: string;
}

export class Dashboard extends React.Component<{}, IState> {
  public state: IState = {
    message: ""
  };

  public componentDidMount(): void {
    ipcRenderer.on("greeting", this.onMessage);
  }

  public componentWillUnmount(): void {
    ipcRenderer.removeAllListeners("greeting");
  }

  public render(): React.ReactNode {
    return <div>{this.state.message}</div>;
  }

  private onMessage = (event: any, message: string) => {
    this.setState({ message: message });
  };
}

What is going there? We subscribe to the channel greeging and upon receiving a message from the main process we put the message into the state. And from that point React takes ower, notices the state changes and renders the message.

Changes in the main process by sending received message from C# to React

const url = require("url");
const path = require("path");
const { ConnectionBuilder } = require("electron-cgi");

import { app, BrowserWindow } from "electron";

...

connection.send("greeting", "Mom from C#", (response: any) => {
  window.webContents.send("greeting", response);
  connection.close();
});

Create a legit EXE file

Add package

npm i -D electron-packager

Adjust the package.json file by adding package-win command and point main to dist folder file main.js.

Tutorial for all platform build commands here.

{
  "main": "dist/main.js",
  "scripts": {
    "package-win": "electron-packager . electron-demo --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron-demo\""
  }
}
npm run package-win

Copy C# folder “core” into “release-builds\electron-demo-win32-ia32” and run the electron-demo.exe

The end

This journey of mine from Delphi 7 to React, Electron, C# is awesome. As I said before, nothing is stuck in time, every day new technologies pop up which makes us better and breaks our personal biases.

To stay open minded is our biggest challenge.

Sourcecode of demo in GitHub

Deploy an Angular App from Visual Studio Code to Azure

Deploy an Angular App from Visual Studio Code to Azure

Deploy an Angular App from Visual Studio Code to Azure - What do you get when you mix Angular 6, Node 10, Visual Studio Code and Azure? A really quick and slick way to develop and deploy a web application using the latest and greatest technologies. Keep reading to find out how.

Deploy an Angular App from Visual Studio Code to Azure - What do you get when you mix Angular 6, Node 10, Visual Studio Code and Azure? A really quick and slick way to develop and deploy a web application using the latest and greatest technologies. Keep reading to find out how.

This article will discuss how to:
  • Setup a free Node server on the cloud using Azure App Service
  • Build a basic Angular 6 web app running on Node 10
  • Use Visual Studio Code to deploy the web app from a local development machine to Azure
Prerequisites

You will need a free Microsoft Azure account with any Azure subscription. If you don’t have a paid subscription, a Pay-As-You-Go subscription is fine. All Azure services used in this article are free for development and testing purposes.

You will also need the following tools installed on your development machine:

  • Setup a free Node server on the cloud using Azure App Service
  • Build a basic Angular 6 web app running on Node 10
  • Use Visual Studio Code to deploy the web app from a local development machine to Azure

The instructions in this article assume Visual Studio Code v1.28, Node 10.6.0 and Angular CLI v6.1.1 although other versions may work too.

Set Up a New Web App on Azure

The first thing to do is setup the Web App (server) on the Azure cloud. The Azure portal or the Azure CLI can be used to create a new Web App. This article will demonstrate how to setup a server using the Azure portal.

To setup a Node.js server on Azure, you will need to create an App Service plan and a Web A_pp_. The App Service plan will be created on the F1 Free tier which provides a basic free virtual server suitable for development (1 GB ram, 1 hour CPU time / day).

To create the App Service plan:

  1. Locate “App Service plan” using the resource search in the Azure Portal
  2. Fill in the App Service plan name, Resource Group and make sure you select the “F1 Free” pricing tier. The free pricing tier can be found under the “Dev / Test” tab.

To create your Web App:

  1. Locate “App Service plan” using the resource search in the Azure Portal
  2. Fill in the App Service plan name, Resource Group and make sure you select the “F1 Free” pricing tier. The free pricing tier can be found under the “Dev / Test” tab.

You should now see your App Service plan and Web App on your Azure dashboard.

The web server is now ready.

You might be wondering why you don’t have to specify the type of web server to use when creating an Azure Web App. This is because Azure Web Apps conveniently support .NET, .NET Core, Java, Node.js, PHP and static HTML websites out of the box.## Set up Local Development Environment

The next step is to set up a local development environment including a local Node.js server, an Angular 6 application, Visual Studio Code and the Azure App Service extension.

The Local Node.js Server

A Node.js server needs to be installed on your development machine to build and test locally. I recommend that you use the Node Version Manager (NVM) command-line utility to manage and switch between multiple Node.js versions installed on your development machine. If you have NVM installed, installing the right version of Node.js is as simple as running these commands:

nvm install 10.6.0 64
nvm use 10.6.0

You should always make sure that your local server and remote server versions are in sync. Azure Web Apps support many versions of Node.js including v10.6.0.

The Angular App

You can generate an Angular 6.x app shell using the Angular CLI:

npm install -g @angular/cli
npm new canadian-maple

Alternatively, if you want to work with something a little more flashier and Canadian then clone the official Canadian Maple app from GitHub. The rest of this article will assume you did!

Visual Studio Code

Visual Studio Code combined with the Azure App Service extension can be used to develop, package and deploy the web app to Azure cloud.

Open up Visual Studio Code in the directory of your Angular app. Use the ng serve command in the integrated terminal (CTRL-~ shortcut) to run and verify your app .

Azure App Service Extension

Install the Azure App Service extension from the Visual Studio Code marketplace. After installing the extension and reloading Visual Studio Code, you will notice a new Azure icon in the left navigation bar. Click on the Azure icon to open the extension and select the option to sign into Azure.

After signing into Azure, you will see the “canadianmaple” Web App that was created previously.

You might be wondering why you don’t have to specify the type of web server to use when creating an Azure Web App. This is because Azure Web Apps conveniently support .NET, .NET Core, Java, Node.js, PHP and static HTML websites out of the box.> You might be wondering why you don’t have to specify the type of web server to use when creating an Azure Web App. This is because Azure Web Apps conveniently support .NET, .NET Core, Java, Node.js, PHP and static HTML websites out of the box.## Update Node Version on Azure Web App

Chances are the default version of Node on the Azure Web App is not the version that you want to use. Luckily, the version of node can be changed with the WEBSITE_NODE_DEFAULT_VERSION environment variable. Navigate to the Application settings section of the Application settings page for your Azure Web App. Click on the environment variable value to change it to 10.6.0.

You might be wondering why you don’t have to specify the type of web server to use when creating an Azure Web App. This is because Azure Web Apps conveniently support .NET, .NET Core, Java, Node.js, PHP and static HTML websites out of the box.
After changing the Node version, you can verify that the setting took effect by using the Console development tool and issuing the node -v command:

Deploying the App

Build the web application before deploying with the ng build command. This command will create the dist/canadian-maple directory containing a transpiled, minified, ready-to-deploy version of your application.

Deploying to an Azure Web App is as simple as right-clicking on the web app in the Azure App Service extension and selecting the “Deploy to Web App” option. The extension will make a suggestion on what to deploy but use the Browse option to select the dist/canadian-maple folder instead.

You will see a few prompts and notifications:

  • Setup a free Node server on the cloud using Azure App Service
  • Build a basic Angular 6 web app running on Node 10
  • Use Visual Studio Code to deploy the web app from a local development machine to Azure

Once the deployment is complete, you will receive a notification with a convenient button to browse to the site.

You have just deployed an Angular 6 app running on Node 10.6.0 to the Azure cloud… relatively painlessly! Check out http://canadianmaple.azurewebsites.net to see a live example.

Recap

Let’s recap what has been accomplished:

  • Setup a free Node server on the cloud using Azure App Service
  • Build a basic Angular 6 web app running on Node 10
  • Use Visual Studio Code to deploy the web app from a local development machine to Azure

Now wasn’t that fast and painless?

*Originally published by Brian De Sousa at *https://briandesousa.net

==========================

Follow me on Facebook | Twitter

Learn More

☞ Angular 8 (formerly Angular 2) - The Complete Guide

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers

☞ Angular Essentials (Angular 2+ with TypeScript)

☞ Angular (Full App) with Angular Material, Angularfire & NgRx

☞ Angular & NodeJS - The MEAN Stack Guide

Selenium WebDriver with C# Tutorial for Beginners

Selenium WebDriver with C# Tutorial for Beginners

Selenium is the most popular tool to test websites! Join me and thousands of students to learn Selenium Webdriver!


Selenium is a free automation testing tool for web applications. It is able to work with different browsers like Chrome, Firefox, IE, Opera and simulate human like behavior. Selenium is able to interact with all the different elements in a webpage. It can click on them, input text, extract text and much more. By covering all the different functionalities on your website with Selenium tests, you will be able to quickly catch new and reappearing old bugs. This will save your team time and money.

Specially for you, I have prepared a website where you can play around and practice your skills.

The website has special elements designed specificly for the course and for you to be able to easily work with them and learn.

In this course we will focus on Graphic User Interface and Functionality Testing and we will learn how to work with the various selectors that Selenium offers us to use like:

  • Name selector
  • ID Selector
  • Class Name selector
  • CSS Path selector
  • X Path selector

After that we will learn how to work with some special elements like:

  • Input text boxes
  • Check boxes
  • Radio buttons
  • Drop down menus
  • JavaScript Alert boxes

We will also have a few theory lectures in which I will explain when you should use either of these selectors, how to inspect elements and what is an Automation Testing Framework and why do we need to learn how to create one.


Learn More

C# Basics for Beginners - Learn C# Fundamentals by Coding

C# Intermediate: Classes, Interfaces and OOP

Complete C# Unity Developer 2D: Learn to Code Making Games

Full Stack Developers: Everything You Need to Know

VS Code extensions you may not have heard of before

ASP.NET Core 3.0 - Basic Authentication Tutorial with Example API

ASP.NET Core 3.0 - Basic Authentication Tutorial with Example API

In this tutorial we'll go through a simple example of how to implement Basic HTTP authentication in an ASP.NET Core 3.0 API with C#.

Tutorial built with ASP.NET Core 3.0

In this tutorial we'll go through a simple example of how to implement Basic HTTP authentication in an ASP.NET Core 3.0 API with C#.

The example API has just two endpoints/routes to demonstrate authenticating with basic http authentication and accessing a restricted route:

  • /users/authenticate - public route that accepts HTTP POST requests containing the username and password in the body. If the username and password are correct then the user details are returned.
  • /users - secure route that accepts HTTP GET requests and returns a list of all the users in the application if the HTTP Authorization header contains valid basic authentication credentials. If there are no basic auth credentials or the credentials are invalid then a 401 Unauthorized response is returned.

Tutorial Contents

Tools required to run the ASP.NET Core 3.0 Tutorial Example Locally

To develop and run ASP.NET Core applications locally, download and install the following:

  • .NET Core SDK - includes the .NET Core runtime and command line tools
  • Visual Studio Code - code editor that runs on Windows, Mac and Linux
  • C# extension for Visual Studio Code - adds support to VS Code for developing .NET Core applications
Running the ASP.NET Core Basic Authentication API Locally
  1. Download or clone the tutorial project code from https://github.com/cornflourblue/aspnet-core-3-basic-authentication-api
  2. Start the api by running dotnet run from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message Now listening on: http://localhost:4000. Follow the instructions below to test with Postman or hook up with one of the example single page applications available (Angular, React or Vue).

NOTE: You can also start the application in debug mode in VS Code by opening the project root folder in VS Code and pressing F5 or by selecting Debug -> Start Debugging from the top menu. Running in debug mode allows you to attach breakpoints to pause execution and step through the application code.

Testing the ASP.NET Core Basic Authentication API with Postman

Postman is a great tool for testing APIs, you can download it at https://www.getpostman.com/.

Below are instructions on how to use Postman to authenticate a user with the api, and then make an authenticated request with basic authentication credentials to retrieve a list of users from the api.

How to authenticate a user with Postman

To authenticate a user with the basic authentication api and follow these steps:

  1. Open a new request tab by clicking the plus (+) button at the end of the tabs.

  2. Change the http request method to "POST" with the dropdown selector on the left of the URL input field.

  3. In the URL field enter the address to the authenticate route of your local API - http://localhost:4000/users/authenticate.

  4. Select the "Body" tab below the URL field, change the body type radio button to "raw", and change the format dropdown selector to "JSON (application/json)".

  5. Enter a JSON object containing the test username and password in the "Body" textarea:

    {
        "username": "test",
        "password": "test"
    }
    
  6. Click the "Send" button, you should receive a "200 OK" response containing the user details in the response body, this indicates that the username and password are correct.

Here's a screenshot of Postman after the request is sent and the user has been authenticated:
ASP.NET Core 3.0 - Basic Authentication Tutorial with Example API

How to make an authenticated request to retrieve all users

To make an authenticated request using basic authentication credentials, follow these steps:

  1. Open a new request tab by clicking the plus (+) button at the end of the tabs.
  2. Change the http request method to "GET" with the dropdown selector on the left of the URL input field.
  3. In the URL field enter the address to the users route of your local API - http://localhost:4000/users.
  4. Select the "Authorization" tab below the URL field, change the type to "Basic Auth" in the type dropdown selector, enter test into the "Username" field and test into the "Password" field.
  5. Click the "Send" button, you should receive a "200 OK" response containing a JSON array with all the user records in the system (just the one test user in the example).

Here's a screenshot of Postman after making an authenticated request to get all users:
ASP.NET Core 3.0 - Basic Authentication Tutorial with Example API

Running an Angular 8 client app with the ASP.NET Core Basic Auth API

For full details about the example Angular 8 application see the tutorial Angular 8 - Basic HTTP Authentication Tutorial & Example. But to get up and running quickly just follow the below steps.

  1. Download or clone the Angular 8 tutorial code from https://github.com/cornflourblue/angular-6-basic-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the line below the comment // provider used to create fake backend located in the /src/app/app.module.ts file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the Angular example application and it should be hooked up with the ASP.NET Core Basic Authentication API that you already have running.
Running a React client app with the ASP.NET Core Basic Auth API

For full details about the example React application see the post React - Basic HTTP Authentication Tutorial & Example. But to get up and running quickly just follow the below steps.

  1. Download or clone the React tutorial code from https://github.com/cornflourblue/react-basic-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.jsx file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the React example application and it should be hooked up with the ASP.NET Core Basic Authentication API that you already have running.
Running a Vue.js client app with the ASP.NET Core Basic Auth API

For full details about the example Vue.js application see the post Vue.js - Basic HTTP Authentication Tutorial & Example. But to get up and running quickly just follow the below steps.

  1. Download or clone the VueJS tutorial code from https://github.com/cornflourblue/vue-basic-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.js file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the VueJS example application and it should be hooked up with the ASP.NET Core Basic Authentication API that you already have running.
ASP.NET Core Basic Authentication Project Structure

The tutorial project is organised into the following folders:
Controllers - define the end points / routes for the web api, controllers are the entry point into the web api from client applications via http requests.
Models - represent request and response models for controller methods, request models define the parameters for incoming requests, and response models can be used to define what data is returned.
Services - contain business logic, validation and data access code.
Entities - represent the application data.
Helpers - anything that doesn't fit into the above folders.

Click any of the below links to jump down to a description of each file along with its code:

ASP.NET Core Users Controller

Path: /Controllers/UsersController.cs

The ASP.NET Core users controller defines and handles all routes / endpoints for the api that relate to users, this includes authentication and standard CRUD operations. Within each route the controller calls the user service to perform the action required, this enables the controller to stay 'lean' and completely separated from the business logic and data access code.

The controller actions are secured with basic authentication using the [Authorize] attribute, with the exception of the Authenticate method which allows public access by overriding the [Authorize] attribute on the controller with the [AllowAnonymous] attribute on the action method. I chose this approach so any new action methods added to the controller will be secure by default unless explicitly made public.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WebApi.Services;
using System.Threading.Tasks;
using WebApi.Models;

namespace WebApi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IUserService _userService;

        public UsersController(IUserService userService)
        {
            _userService = userService;
        }

        [AllowAnonymous]
        [HttpPost("authenticate")]
        public async Task<IActionResult> Authenticate([FromBody]AuthenticateModel model)
        {
            var user = await _userService.Authenticate(model.Username, model.Password);

            if (user == null)
                return BadRequest(new { message = "Username or password is incorrect" });

            return Ok(user);
        }

        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var users = await _userService.GetAll();
            return Ok(users);
        }
    }
}
ASP.NET Core User Entity

Path: /Entities/User.cs

The user entity class represents the data for a user in the application. Entity classes are used to pass data between different parts of the application (e.g. between services and controllers) and can be used to return http response data from controller action methods.

namespace WebApi.Entities
{
    public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}
ASP.NET Core Basic Authentication Handler

Path: /Helpers/BasicAuthenticationHandler.cs

The basic authentication handler is asp.net core middleware that handles request authentication by inheriting from the asp.net core AuthenticationHandler base class and overriding the HandleAuthenticateAsync() method.

Basic authentication logic is implemented in the HandleAuthenticateAsync() method by verifying the username and password received in the HTTP Authorization header, verification is done by calling _userService.Authenticate(username, password). On successful authentication the method returns AuthenticateResult.Success(ticket) which makes the request authenticated and sets the HttpContext.User to the currently logged in user.

The basic authentication middleware is configured in the application inside the ConfigureServices(IServiceCollection services) method in the application Startup file below.

using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebApi.Entities;
using WebApi.Services;

namespace WebApi.Helpers
{
    public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private readonly IUserService _userService;

        public BasicAuthenticationHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock,
            IUserService userService)
            : base(options, logger, encoder, clock)
        {
            _userService = userService;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return AuthenticateResult.Fail("Missing Authorization Header");

            User user = null;
            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                var username = credentials[0];
                var password = credentials[1];
                user = await _userService.Authenticate(username, password);
            }
            catch
            {
                return AuthenticateResult.Fail("Invalid Authorization Header");
            }

            if (user == null)
                return AuthenticateResult.Fail("Invalid Username or Password");

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username),
            };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }
    }
}
ASP.NET Core Extension Methods

Path: /Helpers/ExtensionMethods.cs

Extension methods are used to add convenience methods and extra functionality to existing types in C#.

The extension methods class adds a couple of simple convenience methods for removing passwords from User instances and IEnumerable<User> collections. These methods are called by the Authenticate and GetAll methods in the UserService to ensure the user objects returned don't include passwords.

using System.Collections.Generic;
using System.Linq;
using WebApi.Entities;

namespace WebApi.Helpers
{
    public static class ExtensionMethods
    {
        public static IEnumerable<User> WithoutPasswords(this IEnumerable<User> users) {
            return users.Select(x => x.WithoutPassword());
        }

        public static User WithoutPassword(this User user) {
            user.Password = null;
            return user;
        }
    }
}
ASP.NET Core Authenticate Model

Path: /Models/AuthenticateModel.cs

The authenticate model defines the parameters for incoming requests to the /users/authenticate route of the api, because it is set as the parameter to the Authenticate method of the UsersController. When an HTTP POST request is received to the route, the data from the body is bound to an instance of the AuthenticateModel, validated and passed to the method.

ASP.NET Core Data Annotations are used to automatically handle model validation, the [Required] attribute sets both the username and password as required fields so if either are missing a validation error message is returned from the api.

using System.ComponentModel.DataAnnotations;

namespace WebApi.Models
{
    public class AuthenticateModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        public string Password { get; set; }
    }
}
ASP.NET Core Basic Auth User Service

Path: /Services/UserService.cs

The user service contains a method for authenticating user credentials, and a method for getting all users in the application.

I hardcoded the array of users in the example to keep it focused on basic http authentication, in a production application it is recommended to store user records in a database with hashed passwords. For an extended example that includes support for user registration and stores data with Entity Framework Core check out ASP.NET Core 3.0 - Simple API for Authentication, Registration and User Management.

The top of the file contains an interface that defines the user service, below that is the concrete user service class that implements the interface.

On successful authentication the Authenticate method returns the user details, the client application should then include the base64 encoded user credentials in the HTTP Authorization header of subsequent api requests to access secure endpoints.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi.Entities;
using WebApi.Helpers;

namespace WebApi.Services
{
    public interface IUserService
    {
        Task<User> Authenticate(string username, string password);
        Task<IEnumerable<User>> GetAll();
    }

    public class UserService : IUserService
    {
        // users hardcoded for simplicity, store in a db with hashed passwords in production applications
        private List<User> _users = new List<User>
        {
            new User { Id = 1, FirstName = "Test", LastName = "User", Username = "test", Password = "test" }
        };

        public async Task<User> Authenticate(string username, string password)
        {
            var user = await Task.Run(() => _users.SingleOrDefault(x => x.Username == username && x.Password == password));

            // return null if user not found
            if (user == null)
                return null;

            // authentication successful so return user details without password
            return user.WithoutPassword();
        }

        public async Task<IEnumerable<User>> GetAll()
        {
            return await Task.Run(() => _users.WithoutPasswords());
        }
    }
}
ASP.NET Core App Settings (Development)

Path: /appsettings.Development.json

Configuration file with application settings that are specific to the development environment.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}
ASP.NET Core App Settings

Path: /appsettings.json

Root configuration file containing application settings for all environments.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
ASP.NET Core Program

Path: /Program.cs

The program class is a console app that is the main entry point to start the application, it configures and launches the web api host and web server using an instance of IHostBuilder. ASP.NET Core applications require a host in which to execute.

Kestrel is the web server used in the example, it's a new cross-platform web server for ASP.NET Core that's included in new project templates by default. Kestrel is fine to use on it's own for internal applications and development, but for public facing websites and applications it should sit behind a more mature reverse proxy server (IIS, Apache, Nginx etc) that will receive HTTP requests from the internet and forward them to Kestrel after initial handling and security checks.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                        .UseUrls("http://localhost:4000");
                });
    }
}
ASP.NET Core Startup

Path: /Startup.cs

The startup class configures the request pipeline of the application and how all requests are handled.

The basic authentication handler is configured for the application in the ConfigureServices(IServiceCollection services) method.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApi.Helpers;
using WebApi.Services;
using Microsoft.AspNetCore.Authentication;

namespace WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();

            // configure basic authentication 
            services.AddAuthentication("BasicAuthentication")
                .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);

            // configure DI for application services
            services.AddScoped<IUserService, UserService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => endpoints.MapControllers());
        }
    }
}
ASP.NET Core Basic Authentication Web Api csproj

Path: /WebApi.csproj

The csproj (C# project) is an MSBuild based file that contains target framework and NuGet package dependency information for the application.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
</Project>

The tutorial project is available on GitHub at https://github.com/cornflourblue/aspnet-core-3-basic-authentication-api.

ASP.NET Core 3.0 - JWT Authentication Tutorial with Example API

ASP.NET Core 3.0 - JWT Authentication Tutorial with Example API

In this tutorial we'll go through a simple example of how to implement JWT (JSON Web Token) authentication in an ASP.NET Core 3.0 API with C#.

In this tutorial we'll go through a simple example of how to implement JWT (JSON Web Token) authentication in an ASP.NET Core 3.0 API with C#.

The example API has just two endpoints/routes to demonstrate authenticating with JWT and accessing a restricted route with JWT:

  • /users/authenticate - public route that accepts HTTP POST requests containing the username and password in the body. If the username and password are correct then a JWT authentication token and the user details are returned.
  • /users - secure route that accepts HTTP GET requests and returns a list of all the users in the application if the HTTP Authorization header contains a valid JWT token. If there is no auth token or the token is invalid then a 401 Unauthorized response is returned.

The tutorial project is available on GitHub at https://github.com/cornflourblue/aspnet-core-3-jwt-authentication-api.

Tutorial Contents

  • Tools required to develop ASP.NET Core 3.0 applications
  • Running the example API locally
  • Testing the ASP.NET Core API with Postman
  • Running an Angular 8 app with the ASP.NET Core API
  • Running a React app with the ASP.NET Core API
  • Running a Vue.js app with the ASP.NET Core API
  • ASP.NET Core JWT API project structure
Tools required to run the ASP.NET Core 3.0 JWT Example Locally

To develop and run ASP.NET Core applications locally, download and install the following:

  • .NET Core SDK - includes the .NET Core runtime and command line tools
  • Visual Studio Code - code editor that runs on Windows, Mac and Linux
  • C# extension for Visual Studio Code - adds support to VS Code for developing .NET Core applications
Running the ASP.NET Core JWT Authentication API Locally
  1. Download or clone the tutorial project code from https://github.com/cornflourblue/aspnet-core-3-jwt-authentication-api
  2. Start the api by running dotnet run from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message Now listening on: http://localhost:4000. Follow the instructions below to test with Postman or hook up with one of the example single page applications available (Angular, React or Vue).

NOTE: You can also start the application in debug mode in VS Code by opening the project root folder in VS Code and pressing F5 or by selecting Debug -> Start Debugging from the top menu. Running in debug mode allows you to attach breakpoints to pause execution and step through the application code.

Testing the ASP.NET Core JWT Auth API with Postman

Postman is a great tool for testing APIs, you can download it at https://www.getpostman.com/.

Below are instructions on how to use Postman to authenticate a user to get a JWT token from the api, and then make an authenticated request with the JWT token to retrieve a list of users from the api.

How to authenticate a user with Postman

To authenticate a user with the api and get a JWT token follow these steps:

  1. Open a new request tab by clicking the plus (+) button at the end of the tabs.

  2. Change the http request method to "POST" with the dropdown selector on the left of the URL input field.

  3. In the URL field enter the address to the authenticate route of your local API - http://localhost:4000/users/authenticate.

  4. Select the "Body" tab below the URL field, change the body type radio button to "raw", and change the format dropdown selector to "JSON (application/json)".

  5. Enter a JSON object containing the test username and password in the "Body" textarea:

    {
        "username": "test",
        "password": "test"
    }
    
  6. Click the "Send" button, you should receive a "200 OK" response with the user details including a JWT token in the response body, make a copy of the token value because we'll be using it in the next step to make an authenticated request.

Here's a screenshot of Postman after the request is sent and the user has been authenticated:

This is image title

This is image title

How to make an authenticated request to retrieve all users

To make an authenticated request using the JWT token from the previous step, follow these steps:

  1. Open a new request tab by clicking the plus (+) button at the end of the tabs.
  2. Change the http request method to "GET" with the dropdown selector on the left of the URL input field.
  3. In the URL field enter the address to the users route of your local API - http://localhost:4000/users.
  4. Select the "Authorization" tab below the URL field, change the type to "Bearer Token" in the type dropdown selector, and paste the JWT token from the previous authenticate step into the "Token" field.
  5. Click the "Send" button, you should receive a "200 OK" response containing a JSON array with all the user records in the system (just the one test user in the example).

Here's a screenshot of Postman after making an authenticated request to get all users:

This is image title

This is image title

Running an Angular 8 client app with the ASP.NET Core JWT Auth API

For full details about the example Angular 8 application see the post Angular 8 - JWT Authentication Example & Tutorial. But to get up and running quickly just follow the below steps.

  1. Download or clone the Angular 8 tutorial code from https://github.com/cornflourblue/angular-8-jwt-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the line below the comment // provider used to create fake backend located in the /src/app/app.module.ts file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the Angular example application and it should be hooked up with the ASP.NET Core JWT Auth API that you already have running.
Running a React client app with the ASP.NET Core JWT Auth API

For full details about the example React application see the post React - JWT Authentication Tutorial & Example. But to get up and running quickly just follow the below steps.

  1. Download or clone the React tutorial code from https://github.com/cornflourblue/react-jwt-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.jsx file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the React example application and it should be hooked up with the ASP.NET Core JWT Auth API that you already have running.
Running a Vue.js client app with the ASP.NET Core JWT Auth API

For full details about the example VueJS JWT application see the post Vue.js + Vuex - JWT Authentication Tutorial & Example. But to get up and running quickly just follow the below steps.

  1. Download or clone the VueJS tutorial code from https://github.com/cornflourblue/vue-vuex-jwt-authentication-example
  2. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  3. Remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.js file.
  4. Start the application by running npm start from the command line in the project root folder, this will launch a browser displaying the VueJS example application and it should be hooked up with the ASP.NET Core JWT Auth API that you already have running.
ASP.NET Core JWT Authentication Project Structure

The tutorial project is organised into the following folders:
Controllers - define the end points / routes for the web api, controllers are the entry point into the web api from client applications via http requests.
Models - represent request and response models for controller methods, request models define the parameters for incoming requests, and response models can be used to define what data is returned.
Services - contain business logic, validation and data access code.
Entities - represent the application data.
Helpers - anything that doesn't fit into the above folders.

ASP.NET Core JWT Users Controller
**Path: /Controllers/UsersController.cs**

The ASP.NET Core users controller defines and handles all routes / endpoints for the api that relate to users, this includes authentication and standard CRUD operations. Within each route the controller calls the user service to perform the action required, this enables the controller to stay 'lean' and completely separated from the business logic and data access code.

The controller actions are secured with JWT using the [Authorize] attribute, with the exception of the Authenticate method which allows public access by overriding the [Authorize] attribute on the controller with [AllowAnonymous] attribute on the action method. I chose this approach so any new action methods added to the controller will be secure by default unless explicitly made public.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WebApi.Services;
using WebApi.Models;
using System.Linq;

namespace WebApi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IUserService _userService;

        public UsersController(IUserService userService)
        {
            _userService = userService;
        }

        [AllowAnonymous]
        [HttpPost("authenticate")]
        public IActionResult Authenticate([FromBody]AuthenticateModel model)
        {
            var user = _userService.Authenticate(model.Username, model.Password);

            if (user == null)
                return BadRequest(new { message = "Username or password is incorrect" });

            return Ok(user);
        }

        [HttpGet]
        public IActionResult GetAll()
        {
            var users = _userService.GetAll();
            return Ok(users);
        }
    }
}
ASP.NET Core JWT User Entity
**Path: /Entities/User.cs**

The user entity class represents the data for a user in the application. Entity classes are used to pass data between different parts of the application (e.g. between services and controllers) and can be used to return http response data from controller action methods. If multiple types of entities or other custom data is required to be returned from a controller method then a custom model class should be created in the Models folder for the response.

namespace WebApi.Entities
{
    public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Token { get; set; }
    }
}
ASP.NET Core JWT App Settings
**Path: /Helpers/AppSettings.cs**

The app settings class contains properties defined in the appsettings.json file and is used for accessing application settings via objects that are injected into classes using the ASP.NET Core built in dependency injection (DI) system. For example the User Service accesses app settings via an IOptions<AppSettings> appSettings object that is injected into the constructor.

Mapping of configuration sections to classes is done in the ConfigureServices method of the Startup.cs file.

namespace WebApi.Helpers
{
    public class AppSettings
    {
        public string Secret { get; set; }
    }
}
ASP.NET Core JWT Extension Methods
**Path: /Helpers/ExtensionMethods.cs**

Extension methods are used to add convenience methods and extra functionality to existing types in C#.

The extension methods class adds a couple of simple convenience methods for removing passwords from User instances and IEnumerable<User> collections. These methods are called by the Authenticate and GetAll methods in the UserService to ensure the user objects returned don't include passwords.

using System.Collections.Generic;
using System.Linq;
using WebApi.Entities;

namespace WebApi.Helpers
{
    public static class ExtensionMethods
    {
        public static IEnumerable<User> WithoutPasswords(this IEnumerable<User> users) {
            return users.Select(x => x.WithoutPassword());
        }

        public static User WithoutPassword(this User user) {
            user.Password = null;
            return user;
        }
    }
}
ASP.NET Core JWT Authenticate Model
**Path: /Models/AuthenticateModel.cs**

The authenticate model defines the parameters for incoming requests to the /users/authenticate route of the api, because it is set as the parameter to the Authenticate method of the UsersController. When an HTTP POST request is received to the route, the data from the body is bound to an instance of the AuthenticateModel, validated and passed to the method.

ASP.NET Core Data Annotations are used to automatically handle model validation, the [Required] attribute sets both the username and password as required fields so if either are missing a validation error message is returned from the api.

using System.ComponentModel.DataAnnotations;

namespace WebApi.Models
{
    public class AuthenticateModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        public string Password { get; set; }
    }
}
[Back to top](#projectstructure)
 
ASP.NET Core JWT User Service
**Path: /Services/UserService.cs**

The user service contains a method for authenticating user credentials and returning a JWT token, and a method for getting all users in the application.

I hardcoded the array of users in the example to keep it focused on JWT authentication, in a production application it is recommended to store user records in a database with hashed passwords. For an extended example that includes support for user registration and stores data with Entity Framework Core check out ASP.NET Core 2.2 - Simple API for Authentication, Registration and User Management.

The top of the file contains an interface that defines the user service, below that is the concrete user service class that implements the interface.

On successful authentication the Authenticate method generates a JWT (JSON Web Token) using the JwtSecurityTokenHandler class which generates a token that is digitally signed using a secret key stored in appsettings.json. The JWT token is returned to the client application which must include it in the HTTP Authorization header of subsequent requests to secure routes.

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using WebApi.Entities;
using WebApi.Helpers;

namespace WebApi.Services
{
    public interface IUserService
    {
        User Authenticate(string username, string password);
        IEnumerable<User> GetAll();
    }

    public class UserService : IUserService
    {
        // users hardcoded for simplicity, store in a db with hashed passwords in production applications
        private List<User> _users = new List<User>
        { 
            new User { Id = 1, FirstName = "Test", LastName = "User", Username = "test", Password = "test" } 
        };

        private readonly AppSettings _appSettings;

        public UserService(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        public User Authenticate(string username, string password)
        {
            var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);

            // return null if user not found
            if (user == null)
                return null;

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] 
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            user.Token = tokenHandler.WriteToken(token);

            return user.WithoutPassword();
        }

        public IEnumerable<User> GetAll()
        {
            return _users.WithoutPasswords();
        }
    }
}
ASP.NET Core JWT App Settings (Development)
**Path: /appsettings.Development.json**

Configuration file with application settings that are specific to the development environment.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}
ASP.NET Core JWT App Settings
**Path: /appsettings.json**

Root configuration file containing application settings for all environments.

IMPORTANT: The "Secret" property is used by the api to sign and verify JWT tokens for authentication, update it with your own random string to ensure nobody else can generate a JWT to gain unauthorised access to your application.

{
  "AppSettings": {
    "Secret": "THIS IS USED TO SIGN AND VERIFY JWT TOKENS, REPLACE IT WITH YOUR OWN SECRET, IT CAN BE ANY STRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
ASP.NET Core JWT Program
**Path: /Program.cs**

The program class is a console app that is the main entry point to start the application, it configures and launches the web api host and web server using an instance of IHostBuilder. ASP.NET Core applications require a host in which to execute.

Kestrel is the web server used in the example, it's a new cross-platform web server for ASP.NET Core that's included in new project templates by default. Kestrel is fine to use on it's own for internal applications and development, but for public facing websites and applications it should sit behind a more mature reverse proxy server (IIS, Apache, Nginx etc) that will receive HTTP requests from the internet and forward them to Kestrel after initial handling and security checks.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                        .UseUrls("http://localhost:4000");
                });
    }
}
ASP.NET Core JWT Startup
**Path: /Startup.cs**

The startup class configures the request pipeline of the application and how all requests are handled.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApi.Helpers;
using WebApi.Services;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            // configure DI for application services
            services.AddScoped<IUserService, UserService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
    }
}
ASP.NET Core JWT Web Api csproj
**Path: /WebApi.csproj**

The csproj (C# project) is an MSBuild based file that contains target framework and NuGet package dependency information for the application.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.5.0" />
  </ItemGroup>
</Project>
Thank for reading! Please share if you liked it!