Friday, September 19, 2025

Web - AI Based Regex Generator

Problem Statement: 

I want to dynamically generate RegEx based on human provided input with simple .Net, C# web application. 

Implementation:

- Create web application using .Net C#, Web API

- As prerequisite need to get the Open AI Service details. If it's not already exists follow this

  • Go to Portal.Azure.Com
  • Search for Azure OpenAI 


  • Create new Open AI and click to go to Azure AI Foundry
  • In Azure AI Foundry, Left side click Home. This is your Open AI API Key to use in code below
  • In Azure AI Foundry, Left side click PlayGrounds/Chat, you should be able to setup new Chatbot with new deployment model (For ex: GPT3.5Turbo, GPT5 etc,.). This is your Deployment Model Name to use in code below.
  • Click the View Code on Chat, to get the Endpoint details. This is your Chat Completion Endpoint to use in code below.



- In index.cshtml, simply add textbox and post call
  

<h2>Balaji - AI-Powered Regex Validator - POC</h2>

<form method="post">

    <label for="rule">Enter validation rule (human text):</label><br />

    <input type="text" id="rule" name="Rule" value="@Model.Rule" size="50" /><br /><br />

     <button type="submit">Generate Regex</button><br /><br />

     @if (!string.IsNullOrEmpty(Model.GeneratedRegex))

    {

        <div><strong>Generated Regex:</strong> @Model.GeneratedRegex</div>

         <br />

        <label for="inputText">Enter text to validate:</label>

        <br />

        <input type="text" id="inputText" name="InputText" value="@Model.InputText" size="50" />

         <br />

         <br />

        <div id="result">@Model.ValidationResult</div>

    }

</form>



 - In Index.cshtml.cs, add below logic to generate the validation from AI code. 


using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System.Net.Http;

using System.Text;

using System.Text.Json;

using System.Threading.Tasks;

 

namespace POCRegexBuilderAI.Pages

{

    public class IndexModel : PageModel

    {

        [BindProperty]

        public string Rule { get; set; }

        [BindProperty]

        public string InputText { get; set; }

        public string GeneratedRegex { get; set; }

        public string ValidationResult { get; set; }

 

        public async Task<IActionResult> OnPostAsync()

        {

            if (!string.IsNullOrEmpty(Rule))

            {

                // Call OpenAI API to generate regex

                var regex = await GenerateRegexFromRule(Rule);

                GeneratedRegex = regex;

 

                if (!string.IsNullOrEmpty(InputText) && !string.IsNullOrEmpty(regex))

                {

                    try

                    {

                        var isValid = System.Text.RegularExpressions.Regex.IsMatch(InputText, regex);

                        ValidationResult = isValid ? " Valid input" : " Invalid input";

                    }

                    catch

                    {

                        ValidationResult = "⚠️ Invalid regex pattern.";

                    }

                }

            }

             return Page();

        }

        private async Task<string> GenerateRegexFromRule(string rule)

        {

            var apiKey = "1.ReplaceYourOpenAIKey";

            var prompt = $"Convert this rule to regex: {rule}";

            var requestBody = new

            {

                model = "gpt-35-turbo", //2.Replace with your deployment model

                messages = new[]

                {

                new { role = "user", content = prompt }

            }

            };

             using var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

             var chatCompletionUrl = "https://api.openai.com/v1/chat/completions";//3.Replace with your chatmodel endpoint

             var content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");

            var response = await client.PostAsync(chatCompletionUrl, content);

            var responseString = await response.Content.ReadAsStringAsync();

 

            using var doc = JsonDocument.Parse(responseString);

            var regex = doc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();

             return regex.Trim();

        }

     }

}

 

- Now simply try with human text ("Zipcode with alphabet numeric with Min 3 and Max 5 character") to convert into Regex to apply in any textbox UI as output. It will show the validation simply as below







Friday, February 21, 2025

Azure AD SAML SSO for Web Application

Requirement:

External vendor having SAML based app registered in their Azure AD and wanted to do SSO from web application.


Prerequisites:

- Create a SAML app in Azure AD and then provide us the Metadata, EntityId details. (This usually would be done by external vendor side, we can mock ourside to test internally)

- Will use SustainSys library for SAML setup in C#. Refer: https://saml2.sustainsys.com/en/v2/

- Web application with .Net Core, C#, Razor

Implementation Steps:

- Create SAML App in Azure AD (For mock test). Go to Entra Id -> Enterprise applications -> Add New Application -> Create Your Own Application -> Provide Some App Name + Choose "Integrate any other application you don't find in the gallery (Non-gallery)"

- Go to your web project, add Sustainsys.Saml2.AspNetCore2 from Nuget. 

- Update the startup to include SAML2 steps, something like below

using Microsoft.AspNetCore.Authentication.Cookies;

using Sustainsys.Saml2;

using Sustainsys.Saml2.AspNetCore2;

using Sustainsys.Saml2.Metadata;

          .....

builder.Services.AddAuthentication(opt =>

{

    // Default scheme that maintains session is cookies.

    opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;

 

    // If there's a challenge to sign in, use the Saml2 scheme.

    opt.DefaultChallengeScheme = Saml2Defaults.Scheme;

})

.AddCookie()

.AddSaml2(opt =>

{

    // Set up our EntityId, this is our application.

    opt.SPOptions.EntityId = new EntityId("YourAppName"); //This would be the External AD SAML App's Identifier (Entity ID)

 

    opt.IdentityProviders.Add(

        new IdentityProvider(

            new EntityId("SamlAppIdentiferURL"), //Saml App's Microsoft Entra Identifier

            opt.SPOptions)

        {

            MetadataLocation = "SamlAppMetadataUrl", //Saml App's Meatadata Url

            LoadMetadata = true

        });

});

 

- Now we can initiate the Challenge in code 

var props = new AuthenticationProperties

 {

     RedirectUri = "/"

 };

 return Challenge(props, Saml2Defaults.Scheme); 

//You can set some different default scheme in startup and change in runtime here too



- Read the claims as below

  var authResult = await HttpContext.AuthenticateAsync();

  Properties = authResult.Properties!.Items;

  Claims = authResult.Principal!.Claims;


Tuesday, February 11, 2025

Read B2C Token from Razor MVC Application

 To Retrieve B2C logged in users token for delegate permissions, follow below steps,


Add below lines in startup,


// Configuration to sign-in users with Azure AD B2C

   services.AddMicrosoftIdentityWebAppAuthentication(Configuration, Constants.AzureAdB2C).

        EnableTokenAcquisitionToCallDownstreamApi(new string[] { "https://graph.microsoft.com/.default" })

       .AddInMemoryTokenCaches();

services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>

{

    options.TokenValidationParameters = new TokenValidationParameters

    {

        ValidAudience = "https://graph.microsoft.com"

    };

    options.SaveTokens = true;

});

 

services.Configure<ConfidentialClientApplicationOptions>(options =>

{

    options.ClientSecret = Configuration["AzureAdB2C:ClientSecret"];

});

 

services.ConfigureApplicationCookie(options =>

{

    options.Cookie.SameSite = SameSiteMode.None;

    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;

});

 

Now retrieve token from Controller with below syntax,

    HttpContext.GetTokenAsync("access_token").Result

    or

    HttpContext.GetTokenAsync("id_token").Result


   



Friday, June 14, 2024

Azure AD B2C SSO to Microsoft Entra ID (AD) using OIDC - User Flow

 How to Setup SSO on Azure AD B2C to Azure AD Entra ID


Prerequesties: 

- Create Azure AD Entra ID Tenant

- Create Azure AD B2C Tenant

- Create Azure AD B2C App Registration. Ref: Balajiprasad's useful codes: Azure AD B2C App Registration (rbalajiprasad.blogspot.com)


On Azure AD Entra ID:

- Go to "Microsoft Entra ID", click "Enterprise Applications"

- Click "New Application" then click "Create your own application"

- Choose account type as Single Tenant

- Set Redirect URL as Web & URL to https:// {b2ctenantname}.b2clogin.com/{b2ctenantname}.onmicrosoft.com/oauth2/authresp  (Replace b2cTenantName)

- Go to "Certificates & Secrets" tab, create new client secret, give some unique name and expiration, store the secret for later purpose


On Azure AD B2C: 

- Go to "Azure AD B2C"

- Go to "Identity Provider", Click to "New OpenID Connect Provider"

- Enter the below details and save,

Name: {{SomeUniqueName}}

Metadata url: https://login.microsoftonline.com/{{ADtenantname}}.onmicrosoft.com/.well-known/openid-configuration

Client ID: {{EntraIDADAppRegistrationApplicationId}}

Client secret:  {{EntraIDADAppRegistrationSecret}}

Scope:  open

Response type: id_token

Response mode: form_post

Domain hint: {{SomeUniqueName}}

User ID: oid

Display name:  name

Given name:  given_name

Surname:  family_name

Email:  unique_name


- Go To "User Flows", Choose the SignIn or SignupSignIn flow then select the identity providers

- Now test the policy run flow or through Web Application, you can see the new Login Button for AD tenant added in Signin page

Azure AD B2C App Registration

 To Create Azure AD B2C App, please follow the below simple steps,


Prerequisites:

- You need login account for https://portal.azure.com/

- You need Directory to create Azure AD B2C Tenant  

- You need Azure AD B2C Tenant under Directory Created


 Steps to create Azure AD B2C App:

- Go to "App Registration" and Create "New Registration" 

  • Give some unique name
  • Choose option for "Account with any identity provider...."
  • Redirect URI can be Web & give your application URL (For ex: https://localhost:5000 and also add https://jwt.ms for testing)
  • Grant consent enabled
- Go to "Authentication" tab of registration page once created

  • Set both Access Token & ID token
  • Public client flow to No
- Go to "Certificates & Secret" tab

  •     Add new client secret with some name and store the secret details for later
- Go to "Api Permissions" tab

  • Client "Add Permission", select Microsoft Graph 
  • Add Delegated permission, all available
  • Add Application permission, Directory.read.all, Directory.readwrite.all, User.read.all, User.readwrite.all (include as required)
  • Grand Admin Consent checkbox for every permissions added, make sure all set to true


Login pages:

In previous steps, we created Azure AD B2C App registration to use in our web applications. But we need Login, Registration, Password Reset pages required to add. There are two ways we can do it, Microsoft providing by default pages to use or we can customize our pages. Ref: User flows and custom policies in Azure Active Directory B2C - Azure AD B2C | Microsoft Learn


Default Pages:  (User Flows)

- Using Microsoft provided default pages called User Flows, On Azure AD B2C page, you can see the tab "User Flow" to add these pages. 
- We can add different flows in here for SignIn, SignUp, Signup_SignIn, PasswordReset
- Any policy xml file name referred as B2C_1_{...} it is user flow policy



Customized Pages: (Identity Experience Framework)

- Using our customized pages called Identity Experience Framework or Custom policies. On Azure AD B2C page, you can see the tab "Identity Experience Framework" to add custom policies which is nothing but manually created xml policy files. Don't worry about xml files steps, all are provided in Microsoft starter pack to reuse.
- Any policy xml file name referred as B2C_1A_{...} it is custom policy


Test: 
- Once user flow or custom policies are added, you can click go and search for the SignUpSignin or SignIn policy file and click to "Run flow" then choose the app registered with one of URL to test
- These details we can configure in our Web Application as well. There are samples available to use these web application code. Ref: Web App Samples