Azure

Primary Authentication For Azure Features (Open API) .Web 6

Introduction

On this article, we’re going to study the way to arrange the essential authentication for our Azure Operate APIs utilizing Open API in Web 6.0. As everyone knows, its newly launched Framework was formally launched in November 2021 with LTS (Lengthy Time period Assist). Right here I’m sharing the hyperlink to put in the SDK for .Web 6.0 and together with this we additionally want Visual Studio 2022 IDE to work with it.

Step 1

Create an Azure Operate mission in Visual Studio and ensure to go along with the identical course of from the picture proven beneath.

Step 2

Add the identify of the mission within the subsequent step and select the trail of the situation to save lots of this mission.

Step 3

On this step, below the features employee, we are able to see the newest .Web 6 (LTS) within the dropdown which we put in earlier, and below the operate select the HTTP Set off with Open API as a result of we’ve got to allow the essential authentication with Open API and do not do another modifications on prime it. After this, a skeletal operate mission can be created and the place we are able to go along with our authentication setup. 

Step 4 – Understanding the Open API specification

Assuming we discover the underlying format produced code, we’ll discover new traits starting with OpenApi as soon as once more our Operate. These attributes over the Methodology management what will get created as a characteristic of the OpenAPI Doc Specification. Beneath is the reference for the attributes.

  • OpenApiOperation – This guides to “Operation Object” from the OpenAPI Specification.
  • OpenApiResponseWithBody – This guides to “Response Object” from the OpenAPI Specification.
  • OpenApiParameter – This pertains to “Parameter Object” from the OpenAPI Specification.
  • OpenApiSecurity – This pertains to the “Safety Scheme Object” from the OpenAPI Specification.

Not regularly we’ll make works that will move boundaries within the Question line of the Operate Url.

[OpenApiOperation(operationId: "Run", tags: new[] { "http" }, Abstract = "Primary authentication token movement by way of header", Description = "This exhibits the essential authentication token movement by way of header", Visibility = OpenApiVisibilityType.Essential)]
[OpenApiSecurity("basic_auth", SecuritySchemeType.Http, Scheme = OpenApiSecuritySchemeType.Basic)]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]

Step 5 – Primary Auth Setup

These authentication steps will not be a part of the preliminary setup we have to change the open API safety property values of the attributes. Right here the kind defines the HTTP as it’s handled because the Set off APIs and the scheme is Primary for Authentication.

  • SortSecuritySchemeType.Http
  • SchemeOpenApiSecuritySchemeType.Primary
[OpenApiSecurity("basic_auth", SecuritySchemeType.Http, Scheme = OpenApiSecuritySchemeType.Basic)]

Step 6 – ValidateToken Methodology

On this technique, we have been extracting the request header from the operate API and validating the consumer credentials to move and right here i’m sharing the steps that we adopted to validate the token

Notice: I’ve used static username and password 

username: “Jay”

password: “12345”

  • Checking the header
  • Extracting the credentials & eradicating the “Primary” substring
  • Decode the bottom64 string
  • Break up the username: password
  • Extracting the person username and password
  • Validating the credentials.
non-public bool ValidateToken(string header) {
    //Checking the header
    if (!string.IsNullOrEmpty(header) && header.StartsWith("Primary")) {
        //Extracting credentials
        // Eradicating "Primary " Substring
        string encodedUsernamePassword = header.Substring("Primary ".Size).Trim();
        //Decoding Base64
        Encoding encoding = Encoding.GetEncoding("iso-8859-1");
        string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
        //Splitting Username:Password
        int seperatorIndex = usernamePassword.IndexOf(':');
        // Extracting the person username and password
        var username = usernamePassword.Substring(0, seperatorIndex);
        var password = usernamePassword.Substring(seperatorIndex + 1);
        //Validating the credentials 
        if (username is "Jay" && password is "12345") return true;
        else return false;
    } else {
        return false;
    }
}

Step 7

Line 10 – extract the header from the HTTP request

Line 11 – move the header parameter to validatetoken technique for additional validation and based mostly on a response add a legitimate response as okobjectresult or make it the unauthorized response.

[FunctionName("Function1")]
[OpenApiOperation(operationId: "Run", tags: new [] {
    "http"
}, Abstract = "Primary authentication token movement by way of header", Description = "This exhibits the essential authentication token movement by way of header", Visibility = OpenApiVisibilityType.Essential)]
[OpenApiSecurity("basic_auth", SecuritySchemeType.Http, Scheme = OpenApiSecuritySchemeType.Basic)]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]
public async Process < IActionResult > Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req) {
    //Getting the Header - extracting from the request
    var headers = req.Headers["Authorization"];
    if (ValidateToken(headers)) {
        _logger.LogInformation("C# HTTP set off operate processed a request.");
        string identify = req.Question["name"];
        string requestBody = await new StreamReader(req.Physique).ReadToEndAsync();
        dynamic information = JsonConvert.DeserializeObject(requestBody);
        identify = identify ?? information?.identify;
        string responseMessage = string.IsNullOrEmpty(identify) ? "This HTTP triggered operate executed efficiently. Move a reputation within the question string or within the request physique for a personalised response." : $ "Howdy, {identify}. This HTTP triggered operate executed efficiently.";
        return new OkObjectResult(responseMessage);
    } else {
        return new UnauthorizedResult();
    }
}

Last Code

utilizing System;
utilizing System.IO;
utilizing System.Linq;
utilizing System.Web;
utilizing System.Textual content;
utilizing System.Threading.Duties;
utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Azure.WebJobs.Extensions.Http;
utilizing Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
utilizing Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
utilizing Microsoft.Extensions.Logging;
utilizing Microsoft.OpenApi.Fashions;
utilizing Newtonsoft.Json;
namespace BasicAuth_AzureFunction_API {
    public class Function1 {
        non-public readonly ILogger < Function1 > _logger;
        public Function1(ILogger < Function1 > log) {
                _logger = log;
            }
            [FunctionName("Function1")]
            [OpenApiOperation(operationId: "Run", tags: new [] {
                "http"
            }, Abstract = "Primary authentication token movement by way of header", Description = "This exhibits the essential authentication token movement by way of header", Visibility = OpenApiVisibilityType.Essential)]
            [OpenApiSecurity("basic_auth", SecuritySchemeType.Http, Scheme = OpenApiSecuritySchemeType.Basic)]
            [OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
            [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]
        public async Process < IActionResult > Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req) {
            //Getting the Header - extracting from the request
            var headers = req.Headers["Authorization"];
            if (ValidateToken(headers)) {
                _logger.LogInformation("C# HTTP set off operate processed a request.");
                string identify = req.Question["name"];
                string requestBody = await new StreamReader(req.Physique).ReadToEndAsync();
                dynamic information = JsonConvert.DeserializeObject(requestBody);
                identify = identify ?? information?.identify;
                string responseMessage = string.IsNullOrEmpty(identify) ? "This HTTP triggered operate executed efficiently. Move a reputation within the question string or within the request physique for a personalised response." : $ "Howdy, {identify}. This HTTP triggered operate executed efficiently.";
                return new OkObjectResult(responseMessage);
            } else {
                return new UnauthorizedResult();
            }
        }
        non-public bool ValidateToken(string header) {
            //Checking the header
            if (!string.IsNullOrEmpty(header) && header.StartsWith("Primary")) {
                //Extracting credentials
                // Eradicating "Primary " Substring
                string encodedUsernamePassword = header.Substring("Primary ".Size).Trim();
                //Decoding Base64
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
                //Splitting Username:Password
                int seperatorIndex = usernamePassword.IndexOf(':');
                // Extracting the person username and password
                var username = usernamePassword.Substring(0, seperatorIndex);
                var password = usernamePassword.Substring(seperatorIndex + 1);
                //Validating the credentials 
                if (username is "Jay" && password is "12345") return true;
                else return false;
            } else {
                return false;
            }
        }
    }
}

Step 8

Run the app to see the terminal open like beneath.

Step 9

Copy the above URL and open it within the browser to see the Swagger UI like beneath.

To authenticate your endpoint, you must enter the Username and Password, added to the Authorization header.

The end result display exhibits the request header of Authorization with the bottom64 encoded worth.

On this article, we discovered how can arrange fundamental authentication for Azure operate HTTP set off API by way of Swagger and Run and take a look at it with Postman. If you wish to clone the mission right here.

Hope this text helps you !!!

Continue to learn…..!

Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close