Showing posts with label Azure AD. Show all posts
Showing posts with label Azure AD. Show all posts

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;