DEV Community

Cover image for Basic Authentication in Swagger (Open API) .NET5
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

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 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.

Image description

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.

Image description

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.

Image description

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.

Image description

Step 2: Choose Template.

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

Image description

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

Enter fullscreen mode Exit fullscreen mode

IEmployeeService

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

Enter fullscreen mode Exit fullscreen mode

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<authenticationschemeoptions>
    {
#region Property  
readonlyIEmployeeService _employeeService;
#endregion

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

protectedoverrideasync Task<authenticateresult>HandleAuthenticateAsync()
        {
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);
        }

    }
}
</authenticateresult></authenticationschemeoptions></authenticationschemeoptions>

Enter fullscreen mode Exit fullscreen mode

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; }
    }
}

Enter fullscreen mode Exit fullscreen mode

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<employeecontroller> _logger;

publicEmployeeController(ILogger<employeecontroller> logger)
        {
            _logger = logger;
        }

        [HttpGet]
publicIEnumerable<employeemodel>Get()
        {
            List<employeemodel>emp = new List<employeemodel>
            {
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;

        }
    }
}
</employeemodel></employeemodel></employeemodel></employeecontroller></employeecontroller>

Enter fullscreen mode Exit fullscreen mode

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<authenticationschemeoptions, basicauthenticationhandler="">("BasicAuthentication", null);

services.AddTransient<iemployeeservice, employeeservice="">();
</iemployeeservice,></authenticationschemeoptions,>

Enter fullscreen mode Exit fullscreen mode

Step 8: Build and Run project.

Image description

Image description

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.

Top comments (1)

Collapse
 
onlinemsr profile image
Raja MSR

Thank you for sharing this informative and well-written article on Basic Authentication in Swagger (Open API) .NET5.

The article is well-structured and easy to follow, making it an excellent resource for developers who are looking to implement basic authentication in their Swagger/OpenAPI documentation.