Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Basic Authentication in Swagger (Open API) .NET5


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Swagger

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:

  1. OpenAPI describe endpoint (/employee) and operation on the endpoint (GET /employee, POST /employee)
  2. OpenAPI is used to describe input and output parameter for each operation
  3. OpenAPI is used to describe the authentication method
  4. 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:

  1. Design-First: using Swagger Codegen, the user can generate a serve stub for API after implemented server logic – your API is ready to use.
  2. Use Swagger Codegen: Swagger Codegen is used to generate client libraries for API in 40 languages.
  3. Use Swagger UI:Swagger UI is used to render interactive API documentation which is used to calls API directly in the browser.
  4. 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:

  1. Swagger Editor – Swagger Editor is used to writeOpenAPI specification for browser
  2. Swagger UI – Swagger UI is used to render interactive API documentation.
  3. 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:

  1. Basic Authentication
  2. OAuth2 Authentication
  3. 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.

ai-Hiring-banner

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.

ai-Hiring-banner

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 5Select 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);
    }
}

EmployeeService
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

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

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:

  1. OpenAPI describe endpoint (/employee) and operation on the endpoint (GET /employee, POST /employee)
  2. OpenAPI is used to describe input and output parameter for each operation
  3. OpenAPI is used to describe the authentication method
  4. 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:

  1. Design-First: using Swagger Codegen, the user can generate a serve stub for API after implemented server logic – your API is ready to use.
  2. Use Swagger Codegen: Swagger Codegen is used to generate client libraries for API in 40 languages.
  3. Use Swagger UI:Swagger UI is used to render interactive API documentation which is used to calls API directly in the browser.
  4. 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:

  1. Swagger Editor – Swagger Editor is used to writeOpenAPI specification for browser
  2. Swagger UI – Swagger UI is used to render interactive API documentation.
  3. 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:

  1. Basic Authentication
  2. OAuth2 Authentication
  3. 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.

ai-Hiring-banner

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.

ai-Hiring-banner

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 5Select 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);
    }
}

EmployeeService
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

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.