×

iFour Logo

Basic Authentication in Swagger (Open API) .NET5

Kapil Panchal - February 05, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Basic Authentication in Swagger (Open API) .NET5

Swagger or OpenAPI is used to describe the standard and specification for the RESTful API description. For creating REST API these specifications are a great attempt and these specifications provide an advantage to understand the RESTful service easily and used to provide easy documentation and detail of capabilities and organization.

 

Table of Content

What is OpenAPI?


OpenAPI Specification is a standard used in industry for describing HTTP APIs and used to integrate API with complex business processes or with third parties. OpenAPI is supported by all cloud providers and API registries.OpenAPI Specification is used to describe the format for REST APIs.

OpenAPI describes the following:

  • OpenAPI describe endpoint (/employee) and operation on the endpoint (GET /employee, POST /employee)
  • OpenAPI is used to describe input and output parameter for each operation
  • OpenAPI is used to describe the authentication method
  • OpenAPI is used to describe terms, license, contact, and other information.

Need of OpenAPI


OpenAPI is used to describe their own structure. After written, OpenAPI specification and swagger tool API can be drive in the following ways:

  • Design-First: using Swagger Codegen, the user can generate a serve stub for API after implemented server logic – your API is ready to use.

  • Use Swagger Codegen: Swagger Codegen is used to generate client libraries for API in 40 languages.

  • Use Swagger UI:Swagger UI is used to render interactive API documentation which is used to calls API directly in the browser.

  • Use specification for connecting API. For example, import specification to SoapUI for your API.

What is Swagger?


Swagger is used together with a set of open-source tools and build around the OpenAPI specification for design, build, document, and consume REST APIs.

Swagger includes the following tools:

  • Swagger Editor – Swagger Editor is used to writeOpenAPI specification for browser

  • Swagger UI – Swagger UI is used to render interactive API documentation.

  • Swagger Codegen –Swagger Codegen is used for the generation of server stubs and client libraries from OpenAPI specification.

OpenAPI specification or Swagger defines the following types of authentication in API:

  • Basic Authentication
  • OAuth2 Authentication
  • JWT bearer Authentication

Basic Authentication

Basic Authentication is a very simple authentication scheme which builds into HTTP protocol which uses a simple username and password for access restricted resource. Using Bs64 encoding, Username and password are translated to standard "Authorization". This scheme is used by organizations internally within their "LAN" infrastructure.

Figure 1 Basic Authentication

Suggestion:

Use other security mechanisms such as HTTP/SSL with Bs64 encoding because Bs64 encoding can be easily decoded.

OAuth2 Authentication

OAuth2 Authentication is an authentication protocol that is used to limit access to user data on the server. OAuth2 Authentication used by GitHub, Google, and Facebook APIs. OAuth2 Authentication used to flow, which allow the user to share protected content from the server without sharing credential for that OAuth2 Authentication used access token which is used by the client application to protect resource on behalf of the resource owner.

ai-Hiring-banner

Figure 2 OAuth2 Authentication

JWT bearer Authentication

Bearer Authentication (Token Authentication) uses a security token called bearer token which can be encrypt string generated by the server in the response of the request.This token is sent by Authorization Header. JWT (JSON Web token) is an open standard which is used to transmitted information securely between parties using JSON object. JWT uses the RSA encryption algorithm for verifying information.

Figure 3 JWT bearer Authentication

Let's start with an example:

Step 1: Create an application.

Open Visual Studio 2019->Go to File manager ->project.

Create a new Asp.net Core Web Application project with the "Auth_Demo” name and click on the Create button.

ai-Hiring-banner

Figure 4 Create an Asp.net Core web application

Step 2: Choose Template.

Select the Asp.Net Core Web API template and click on the Create button.

ai-Hiring-banner

Figure 5 Select Asp.Net Core Web API Template

Step 3: Add Business Logic.

Right-click on solution->Add->New Folder

Create a new folder with the "Service" name.

Step 4: Add Service Method and Interface.

Right-click on service Folder->Add->class and name it “EmployeeService”

Right-click on service Folder->Add->New Item->Interface and name it “IEmployeeService”

IEmployeeService
namespaceAuth_Demo.Service
{
publicinterfaceIEmployeeService
    {
boolLogin(string username, string password);
    }
}
              
IEmployeeService
namespaceAuth_Demo.Service
{
publicclassEmployeeService:IEmployeeService
    {
publicboolLogin(string username, string password)
        {
returnusername.Equals("admin") &&password.Equals("1234");
        }
    }
}
              

Step 5: Add Authentication handler

Right-click on solution->Add->class “BasicAuthenticationHandler”

usingAuth_Demo.Service;
usingMicrosoft.AspNetCore.Authentication;
usingMicrosoft.Extensions.Logging;
usingMicrosoft.Extensions.Options;
using System;
usingSystem.Linq;
usingSystem.Net.Http.Headers;
usingSystem.Security.Claims;
usingSystem.Text;
usingSystem.Text.Encodings.Web;
usingSystem.Threading.Tasks;

namespaceAuth_Demo
{
publicclassBasicAuthenticationHandler :AuthenticationHandler
    {
#region Property  
readonlyIEmployeeService _employeeService;
#endregion

#region Constructor  
publicBasicAuthenticationHandler(IEmployeeServiceemployeeService,
IOptionsMonitor options,
            ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
            _employeeService = employeeService;
        }
#endregion

protectedoverrideasync TaskHandleAuthenticateAsync()
        {
string username = null;
try
            {
varauthHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');
                username = credentials.FirstOrDefault();
var password = credentials.LastOrDefault();

if(!_employeeService.Login(username, password))
thrownewArgumentException("Invalid credentials");
            }
catch (Exception ex)
            {
returnAuthenticateResult.Fail($"Authentication failed: {ex.Message}");
            }

var claims = new[] {
newClaim(ClaimTypes.Name, username)
            };
var identity = newClaimsIdentity(claims, Scheme.Name);
var principal = newClaimsPrincipal(identity);
var ticket = newAuthenticationTicket(principal, Scheme.Name);

returnAuthenticateResult.Success(ticket);
        }

    }
}

              

Looking to Hire ASP.Net Developer?

Your Search ends here.

Step 6: Add Employee Controller and Employee Model.

EmployeeModel
namespaceAuth_Demo
{
publicclassEmployeeModel
    {
publicint Id { get; set; }
publicstring Name { get; set; }
    }
}
               
Employee Controller
usingMicrosoft.AspNetCore.Authorization;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Logging;
usingSystem.Collections.Generic;

namespaceAuth_Demo.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
publicclassEmployeeController :ControllerBase
    {
privatereadonlyILogger _logger;

publicEmployeeController(ILogger logger)
        {
            _logger = logger;
        }

        [HttpGet]
publicIEnumerableGet()
        {
            Listemp = new List
            {
newEmployeeModel{Id=1,Name="Dhoni" },
newEmployeeModel{Id=2,Name="Virat" },
newEmployeeModel{Id=3,Name="Rohit" },
newEmployeeModel{Id=4,Name="Jasprit" },
newEmployeeModel{Id=5,Name="Chahal" }
            };

return emp;

        }
    }
}

               

Step 7: Configure the Startup file.

Add configuration in Configure service method.

services.AddSwaggerGen(c =>
            {
c.SwaggerDoc("v1", newOpenApiInfo { Title = "Test_Demo", Version = "v1" });
c.AddSecurityDefinition("basic", newOpenApiSecurityScheme
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "basic",
                    In = ParameterLocation.Header,
                    Description = "Authentication"
                });
c.AddSecurityRequirement(newOpenApiSecurityRequirement
                {
                    {
newOpenApiSecurityScheme
                            {
                                Reference = newOpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "basic"
                                }
                            },
newstring[] {}
                    }
                });
            });
services.AddAuthentication("BasicAuthentication")
.AddScheme("BasicAuthentication", null);

services.AddTransient();

               

Step 8: Build and Run project.

ai-Hiring-banner

Figure 8 Output

Conclusion


In this blog, we have discussed authentication with swagger in .net 5 and Swagger or OpenAPIwhichis used to describe the standard and specification for the RESTful API description. And we have also discussed a few examples.

Basic Authentication in Swagger (Open API) .NET5 Swagger or OpenAPI is used to describe the standard and specification for the RESTful API description. For creating REST API these specifications are a great attempt and these specifications provide an advantage to understand the RESTful service easily and used to provide easy documentation and detail of capabilities and organization.   Table of Content 1. What is OpenAPI? 2. Need of OpenAPI 3. What is Swagger? 3.1. Basic Authentication 3.2. OAuth2 Authentication 3.3. JWT bearer Authentication 3.4. Let's start with an example: 4. Conclusion What is OpenAPI? OpenAPI Specification is a standard used in industry for describing HTTP APIs and used to integrate API with complex business processes or with third parties. OpenAPI is supported by all cloud providers and API registries.OpenAPI Specification is used to describe the format for REST APIs. OpenAPI describes the following: OpenAPI describe endpoint (/employee) and operation on the endpoint (GET /employee, POST /employee) OpenAPI is used to describe input and output parameter for each operation OpenAPI is used to describe the authentication method OpenAPI is used to describe terms, license, contact, and other information. Need of OpenAPI OpenAPI is used to describe their own structure. After written, OpenAPI specification and swagger tool API can be drive in the following ways: Design-First: using Swagger Codegen, the user can generate a serve stub for API after implemented server logic – your API is ready to use. Use Swagger Codegen: Swagger Codegen is used to generate client libraries for API in 40 languages. Use Swagger UI:Swagger UI is used to render interactive API documentation which is used to calls API directly in the browser. Use specification for connecting API. For example, import specification to SoapUI for your API. What is Swagger? Swagger is used together with a set of open-source tools and build around the OpenAPI specification for design, build, document, and consume REST APIs. Swagger includes the following tools: Swagger Editor – Swagger Editor is used to writeOpenAPI specification for browser Swagger UI – Swagger UI is used to render interactive API documentation. Swagger Codegen –Swagger Codegen is used for the generation of server stubs and client libraries from OpenAPI specification. OpenAPI specification or Swagger defines the following types of authentication in API: Basic Authentication OAuth2 Authentication JWT bearer Authentication Basic Authentication Basic Authentication is a very simple authentication scheme which builds into HTTP protocol which uses a simple username and password for access restricted resource. Using Bs64 encoding, Username and password are translated to standard "Authorization". This scheme is used by organizations internally within their "LAN" infrastructure. Figure 1 Basic Authentication Suggestion: Use other security mechanisms such as HTTP/SSL with Bs64 encoding because Bs64 encoding can be easily decoded. Read More: What’s New In .net Productivity? OAuth2 Authentication OAuth2 Authentication is an authentication protocol that is used to limit access to user data on the server. OAuth2 Authentication used by GitHub, Google, and Facebook APIs. OAuth2 Authentication used to flow, which allow the user to share protected content from the server without sharing credential for that OAuth2 Authentication used access token which is used by the client application to protect resource on behalf of the resource owner. Figure 2 OAuth2 Authentication JWT bearer Authentication Bearer Authentication (Token Authentication) uses a security token called bearer token which can be encrypt string generated by the server in the response of the request.This token is sent by Authorization Header. JWT (JSON Web token) is an open standard which is used to transmitted information securely between parties using JSON object. JWT uses the RSA encryption algorithm for verifying information. Figure 3 JWT bearer Authentication Let's start with an example: Step 1: Create an application. Open Visual Studio 2019->Go to File manager ->project. Create a new Asp.net Core Web Application project with the "Auth_Demo” name and click on the Create button. Figure 4 Create an Asp.net Core web application Step 2: Choose Template. Select the Asp.Net Core Web API template and click on the Create button. Figure 5 Select Asp.Net Core Web API Template Step 3: Add Business Logic. Right-click on solution->Add->New Folder Create a new folder with the "Service" name. Step 4: Add Service Method and Interface. Right-click on service Folder->Add->class and name it “EmployeeService” Right-click on service Folder->Add->New Item->Interface and name it “IEmployeeService” IEmployeeService namespaceAuth_Demo.Service { publicinterfaceIEmployeeService { boolLogin(string username, string password); } } IEmployeeService namespaceAuth_Demo.Service { publicclassEmployeeService:IEmployeeService { publicboolLogin(string username, string password) { returnusername.Equals("admin") &&password.Equals("1234"); } } } Step 5: Add Authentication handler Right-click on solution->Add->class “BasicAuthenticationHandler” usingAuth_Demo.Service; usingMicrosoft.AspNetCore.Authentication; usingMicrosoft.Extensions.Logging; usingMicrosoft.Extensions.Options; using System; usingSystem.Linq; usingSystem.Net.Http.Headers; usingSystem.Security.Claims; usingSystem.Text; usingSystem.Text.Encodings.Web; usingSystem.Threading.Tasks; namespaceAuth_Demo { publicclassBasicAuthenticationHandler :AuthenticationHandler { #region Property readonlyIEmployeeService _employeeService; #endregion #region Constructor publicBasicAuthenticationHandler(IEmployeeServiceemployeeService, IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { _employeeService = employeeService; } #endregion protectedoverrideasync TaskHandleAuthenticateAsync() { string username = null; try { varauthHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':'); username = credentials.FirstOrDefault(); var password = credentials.LastOrDefault(); if(!_employeeService.Login(username, password)) thrownewArgumentException("Invalid credentials"); } catch (Exception ex) { returnAuthenticateResult.Fail($"Authentication failed: {ex.Message}"); } var claims = new[] { newClaim(ClaimTypes.Name, username) }; var identity = newClaimsIdentity(claims, Scheme.Name); var principal = newClaimsPrincipal(identity); var ticket = newAuthenticationTicket(principal, Scheme.Name); returnAuthenticateResult.Success(ticket); } } } Looking to Hire ASP.Net Developer? Your Search ends here. See here Step 6: Add Employee Controller and Employee Model. EmployeeModel namespaceAuth_Demo { publicclassEmployeeModel { publicint Id { get; set; } publicstring Name { get; set; } } } Employee Controller usingMicrosoft.AspNetCore.Authorization; usingMicrosoft.AspNetCore.Mvc; usingMicrosoft.Extensions.Logging; usingSystem.Collections.Generic; namespaceAuth_Demo.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] publicclassEmployeeController :ControllerBase { privatereadonlyILogger _logger; publicEmployeeController(ILogger logger) { _logger = logger; } [HttpGet] publicIEnumerableGet() { Listemp = new List { newEmployeeModel{Id=1,Name="Dhoni" }, newEmployeeModel{Id=2,Name="Virat" }, newEmployeeModel{Id=3,Name="Rohit" }, newEmployeeModel{Id=4,Name="Jasprit" }, newEmployeeModel{Id=5,Name="Chahal" } }; return emp; } } } Step 7: Configure the Startup file. Add configuration in Configure service method. services.AddSwaggerGen(c => { c.SwaggerDoc("v1", newOpenApiInfo { Title = "Test_Demo", Version = "v1" }); c.AddSecurityDefinition("basic", newOpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.Http, Scheme = "basic", In = ParameterLocation.Header, Description = "Authentication" }); c.AddSecurityRequirement(newOpenApiSecurityRequirement { { newOpenApiSecurityScheme { Reference = newOpenApiReference { Type = ReferenceType.SecurityScheme, Id = "basic" } }, newstring[] {} } }); }); services.AddAuthentication("BasicAuthentication") .AddScheme("BasicAuthentication", null); services.AddTransient(); Step 8: Build and Run project. Figure 8 Output Conclusion In this blog, we have discussed authentication with swagger in .net 5 and Swagger or OpenAPIwhichis used to describe the standard and specification for the RESTful API description. And we have also discussed a few examples.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.