×

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.

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

 

Ready to enhance your Swagger documentation with secure and seamless API integrations? Discover our custom API integration services to streamline your .NET5 development process today!

Conclusion - Open API vs Swagger Basic Authentication


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. 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   Ready to enhance your Swagger documentation with secure and seamless API integrations? Discover our custom API integration services to streamline your .NET5 development process today! Conclusion - Open API vs Swagger Basic Authentication 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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
UWP vs WPF - Key Differences Explained!
UWP vs WPF - Key Differences Explained!

Several experts, particularly those just starting out, often find themselves confused about WPF and UWP, wondering if they are the same. Since they are used to create great UIs for...

Predictive Analytics with ML and .NET
Predictive Analytics with ML and .NET

Many companies rely on advanced technologies to make informed decisions in their business. For instance, some Chief Technology Officers (CTOs) turn to Power BI consulting services,...

C# 8 vs C# 11: Exploring the Key Differences for Business
C# 8 vs C# 11: Exploring the Key Differences for Business

Importance of C# - custom software development C# has been dominating the world of programming for the last two decades. Did you know it is the favored language of about 31%...