Azure

Safe Serverless Azure Capabilities Utilizing JWT Auth And C# (.Web 6)

Introduction

On this article, we’re going to find out about find out how to safe our Azure perform serverless APIs utilizing JWT(JSON Net Tokens) &.Web 6. After we are constructing these capabilities, we usually must care for the authentication and authorization as a result of each API must be approved earlier than pulling or pushing the info from the system/server. On this article, we’re utilizing one customary customized authentication for our Azure capabilities utilizing JWT. 

If you wish to know extra about Azure Capabilities do try this superb article 

Stipulations

Organising our Azure Perform Undertaking

 When you opened the Visual Studio seek for Azure perform within the search bar as proven within the under picture

 

 Within the subsequent step it asks us to create a challenge title and its location to save lots of the challenge and together with the perform title

 Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

When you clicks on the create it takes you to the following part the place we’ve to pick the template and framework and the azure perform authorization stage. In order we already downloaded and put in the .Web 6 SDK(Software program Improvement Package). It reveals the .Web 6 within the Dropdown we’ve to decide on that and ensure to pick Authorization stage as Nameless after which click on on create.

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

Pattern Perform Performing the Credential Test

The credential verify is the very first thing to do. This merely implies that we examine a set of credentials we have obtained to a set of credentials saved in a customized database or in a service/protocol aside from App Providers’ common ones. On this instance, we’ll ship a JSON object to our perform as an argument and simply return true every time.

utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Azure.WebJobs.Extensions.Http;
utilizing Microsoft.Extensions.Logging;
utilizing System;
utilizing System.Threading.Duties;
namespace AzureFuntions_Auth_JWT {
    public static class Function1 {
        [FunctionName(nameof(UserAuthenication))]
        public static async Process < IActionResult > UserAuthenication(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth")] UserCredentials userCredentials, ILogger log) {
            log.LogInformation("C# HTTP set off perform processed a request.");
            // TODO: Carry out customized authentication right here; we're simply utilizing a easy laborious coded verify for this instance
            bool authenticated = userCredentials?.Person.Equals("Jay", StringComparison.InvariantCultureIgnoreCase) ?? false;
            if (!authenticated) {
                return await Process.FromResult(new UnauthorizedResult()).ConfigureAwait(false);
            } else {
                return await Process.FromResult(new OkObjectResult("Person is Authenticated")).ConfigureAwait(false);
            }
        }
    }
    public class UserCredentials {
        public string Person {
            get;
            set;
        }
        public string Password {
            get;
            set;
        }
    }
}

Run & Check this API response in Postman

When you run this perform it’ll run utilizing the storage emulator and we will see the respective API URL within the emulator as proven within the fig under.

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

Copy that URL and open postman to verify the response from that Endpoint.

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

As per the above picture, it validates the person credentials and sends again the response with output as we hardcoded the values for the demo function you possibly can truly work as per your want.

Generate JWT

JSON Net Tokens are nothing greater than a approach to ship JSON strings securely. We could merely retrieve the suitable details about the person and encrypt it right into a token, which we ship to the consumer as a cookie, somewhat than having the person switch credentials forwards and backwards on every name after which validating the person’s credentials time and again. When the consumer makes additional calls, the JWT is handed again to the applying, which decrypts the contents and verifies that they’re professional.

As a result of the token is given with every request, you will wish to watch out to not add pointless info, such because the username, person ID, person electronic mail, and function(s). I’ve created a separate class named GenerateJWTToken for issuing JWT per request.

To deal with JWT in Azure Capabilities we’d like a bundle, Please discover the nuget library under

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

GenerateJWTToken.cs

utilizing JWT;
utilizing JWT.Algorithms;
utilizing JWT.Serializers;
utilizing System.Collections.Generic;
namespace AzureFuntions_Auth_JWT {
    /// <abstract>
    ///     Service class for performing authentication.
    /// </abstract>
    public class GenerateJWTToken {
        non-public readonly IJwtAlgorithm _algorithm;
        non-public readonly IJsonSerializer _serializer;
        non-public readonly IBase64UrlEncoder _base64Encoder;
        non-public readonly IJwtEncoder _jwtEncoder;
        public GenerateJWTToken() {
            // JWT particular initialization.
            _algorithm = new HMACSHA256Algorithm();
            _serializer = new JsonNetSerializer();
            _base64Encoder = new JwtBase64UrlEncoder();
            _jwtEncoder = new JwtEncoder(_algorithm, _serializer, _base64Encoder);
        }
        public string IssuingJWT(string person) {
            Dictionary < string, object > claims = new Dictionary < string, object > {
                // JSON illustration of the person Reference with ID and show title
                {
                    "username",
                    person
                },
                // TODO: Add different claims right here as crucial; perhaps from a person database
                {
                    "function",
                    "admin"
                }
            };
            string token = _jwtEncoder.Encode(claims, "Your Secret Securtity key string"); // Put this key in config
            return token;
        }
    }
}

Now let’s eat this JWT Code within the Practical Code to get the token on foundation of Person credentials and connect that token within the response the place that token may be consumed to get entry for different endpoints for this we have to modify the prevailing API lets make these adjustments and verify that response within the postman.

We simply created an object for GenerateJWTToken Class to entry that IssuingJWT Perform which you’ll be able to see in line quantity 27 & 28 within the code under 

Function1.cs

utilizing Microsoft.AspNetCore.Http;
utilizing Microsoft.AspNetCore.Mvc;
utilizing Microsoft.Azure.WebJobs;
utilizing Microsoft.Azure.WebJobs.Extensions.Http;
utilizing Microsoft.Extensions.Logging;
utilizing System;
utilizing System.Threading.Duties;
namespace AzureFuntions_Auth_JWT {
    public static class Function1 {
        [FunctionName(nameof(UserAuthenication))]
        public static async Process < IActionResult > UserAuthenication(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth")] UserCredentials userCredentials, ILogger log) {
            log.LogInformation("C# HTTP set off perform processed a request.");
            // TODO: Carry out customized authentication right here; we're simply utilizing a easy laborious coded verify for this instance
            bool authenticated = userCredentials?.Person.Equals("Jay", StringComparison.InvariantCultureIgnoreCase) ?? false;
            if (!authenticated) {
                return await Process.FromResult(new UnauthorizedResult()).ConfigureAwait(false);
            } else {
                GenerateJWTToken generateJWTToken = new();
                string token = generateJWTToken.IssuingJWT(userCredentials.Person);
                return await Process.FromResult(new OkObjectResult(token)).ConfigureAwait(false);
            }
        }
    }
    public class UserCredentials {
        public string Person {
            get;
            set;
        }
        public string Password {
            get;
            set;
        }
    }
}

Run and Check the identical API within the postman once more

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

Within the subsequent step we’ve to validate the JWT Token which we’ve generated utilizing the auth API and now utilizing the identical token let’s entry one other API for that we have to Validate the token through the use of the Key and username let’s hook it up the code now.

ValidateJWT.cs

utilizing JWT.Algorithms;
utilizing JWT.Builder;
utilizing Microsoft.AspNetCore.Http;
utilizing System;
utilizing System.Collections.Generic;
namespace AzureFuntions_Auth_JWT {
    public class ValidateJWT {
        public bool IsValid {
            get;
        }
        public string Username {
            get;
        }
        public string Position {
            get;
        }
        public ValidateJWT(HttpRequest request) {
            // Test if we've a header.
            if (!request.Headers.ContainsKey("Authorization")) {
                IsValid = false;
                return;
            }
            string authorizationHeader = request.Headers["Authorization"];
            // Test if the worth is empty.
            if (string.IsNullOrEmpty(authorizationHeader)) {
                IsValid = false;
                return;
            }
            // Test if we will decode the header.
            IDictionary < string, object > claims = null;
            attempt {
                if (authorizationHeader.StartsWith("Bearer")) {
                    authorizationHeader = authorizationHeader.Substring(7);
                }
                // Validate the token and decode the claims.
                claims = new JwtBuilder().WithAlgorithm(new HMACSHA256Algorithm()).WithSecret("Your Secret Securtity key string").MustVerifySignature().Decode < IDictionary < string, object >> (authorizationHeader);
            } catch (Exception exception) {
                IsValid = false;
                return;
            }
            // Test if we've person declare.
            if (!claims.ContainsKey("username")) {
                IsValid = false;
                return;
            }
            IsValid = true;
            Username = Convert.ToString(claims["username"]);
            Position = Convert.ToString(claims["role"]);
        }
    }
}

Let’s create one other endpoint which should settle for authentication to be able to fetch the info from the system and within the output we’re passing the JSON object of the person credentials after profitable authentication go. On this API truly, we have been validating the API with our Credentials as soon as its passes then we’re allowed to ship the success response because the output.

GetData

[FunctionName(nameof(GetData))]
public static async Process < IActionResult > GetData(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "data")] HttpRequest req, ILogger log) {
    // Test if we've authentication data.
    ValidateJWT auth = new ValidateJWT(req);
    if (!auth.IsValid) {
        return new UnauthorizedResult(); // No authentication data.
    }
    string postData = await req.ReadAsStringAsync();
    return new OkObjectResult($ "{postData}");
}

Run and take a look at the API in Postman

Secure Serverless Azure Functions Using JWT Auth & C# (.Net 6)

That’s all there’s to it!

Supply Code – GItHub

Preserve Studying…..!

Show More

Related Articles

Leave a Reply

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

Back to top button