Search Results :

×

Configure SAML Single Sign-On (SSO) in ASP.NET Core Decoupled Application

This guide provides detailed steps to set up SAML Single Sign-On (SSO) in ASP.NET Core decoupled architecture application using any SAML-compliant Identity Provider (IdP).The backend (ASP.NET Core) handles SSO authentication, generates a JWT Token, and exposes it securely to any frontend (React, Angular, Vue, etc.).

Platform Support: The ASP.NET Core SAML middleware supports ASP.NET Core 2.0 and above. It supports all the ASP.NET Core platforms, including Windows, Linux and macOS.

NuGet Package
.NET CLI

PM> NuGet\Install-Package miniOrange.SAML.SSO


Note: To integrate the miniOrange ASP.NET SAML SSO middleware in your application, you will be required to add the below namespaces, services and middleware in your project, below is a sample implementation for reference.

  using miniOrange.saml;
  using System.Reflection;
  var builder=WebApplication.CreateBuilder(args);
  // Add services to the container.
  builder.Services.AddRazorPages();
  builder.Services.AddAuthentication(options =>
  {
    options.DefaultAuthenticationScheme ="SS0_OR_Admin";
    options.DefaultScheme = "SSO_OR_Admin";
    options.DefaultChallengeScheme = "SSO_OR_Admin";
  })
  .AddCookie("moAdmin", options =>
  {
    
  })
  .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
  {
    
  })
  .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
  {
    options.TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidateAudience = true,
      ValidateLifetime = true,
      ValidateIssuerSigningKey = true,
      ValidIssuer = "your-issuer",
      ValidAudience = "your-audience",
      IssuerSigningKey = new
  SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
    };
  })
  .AddPolicyScheme("SSO_OR_Admin", "SSO_OR_Admin", options =>
  {
    options.ForwardDefaultSelector = context =>
    {
      // Check if Bearer token exists
      string authHeader = context.Request.Headers["Authorization"].FirstOrDefault() ?? "";
      if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer"))
      {
        return JwtBearerDefaults.AuthenticationScheme;
      }
      foreach (var cookie in context.Request.Cookies)
      {
         if (cookie.Key.Contains(".AspNetCore.Cookies") &&
        context.Request.Query["ssoaction"] != "config")
        {
          return CookieAuthenticationDefaults.AuthenticationScheme;
        }
    }
    return "moAdmin";
    };
  });
  var app = builder.Build();
  if(!app.Environment.IsDevelopment())
  {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
  }
  app.UseHttpsRedirection();
  app.UseRouting();
  app.UseAuthorization();
  app.MapRazorPages();
  app.UseCookiePolicy();
  app.UseAuthentication();
  app.UseStaticFiles();
  app.UseminiOrangeSAMLSSOMiddleware();
  app.Run();
NuGet Package
.NET CLI

PM> NuGet\Install-Package miniOrange.SAML.SSO


Note: To integrate the miniOrange ASP.NET SAML SSO middleware in your application, you will be required to add the below namespaces, services and middleware in your project, below here is a sample .

  using miniOrange.saml;
  using System.Reflection;
  public class Startup
  {
   public Startup(IConfiguration configuration)
   {
    Configuration = configuration;
   }
   public IConfiguration Configuration {get;}
   // This method gets called by the runtime. Use this method to add services to the container.
   public void ConfigureServices(IServiceCollection services)
   {
    services.AddRazorPages();
  services.AddAuthentication(options =>
  {
    options.DefaultAuthenticationScheme ="SS0_OR_Admin";
    options.DefaultScheme = "SSO_OR_Admin";
    options.DefaultChallengeScheme = "SSO_OR_Admin";
  })
  .AddCookie("moAdmin", options =>
  {
    
  })
  .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
  {
    
  })
  .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
  {
    options.TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidateAudience = true,
      ValidateLifetime = true,
      ValidateIssuerSigningKey = true,
      ValidIssuer = "your-issuer",
      ValidAudience = "your-audience",
      IssuerSigningKey = new
  SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
    };
  })
  .AddPolicyScheme("SSO_OR_Admin", "SSO_OR_Admin", options =>
  {
    options.ForwardDefaultSelector = context =>
    {
      // Check if Bearer token exists
      string authHeader = context.Request.Headers["Authorization"].FirstOrDefault() ?? "";
      if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer"))
      {
        return JwtBearerDefaults.AuthenticationScheme;
      }
      foreach (var cookie in context.Request.Cookies)
      {
         if (cookie.Key.Contains(".AspNetCore.Cookies") &&
        context.Request.Query["ssoaction"] != "config")
        {
          return CookieAuthenticationDefaults.AuthenticationScheme;
        }
    }
    return "moAdmin";
    };
  });
   }
   // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
    if (env.IsDevelopment())
    {
     app.UseDeveloperExceptionPage();
    }
   else
    {
     app.UseExceptionHandler("/Error");
    app.UseHsts();
    }
   app.UseHttpsRedirection();
   app.UseCookiePolicy();
   app.UseAuthentication();
   app.UseStaticFiles();
   app.UseminiOrangeSAMLSSOMiddleware();
   app.UseRouting();
   app.UseAuthorization();
   app.UseEndpoints(endpoints =>
   {
    endpoints.MapRazorPages();
   });
  }
 }

If you get the CORS issues while making API calls, add the below service and policy.

builder.Services.AddCors(options =>
{
  options.AddPolicy("<policy-name>",policy =>
  {
    policy.WithOrigins("<your-origin>",policy)
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
  });
});
//Add this in the middleware section
app.UseCors("<policy-name>");

Step by Step guide for ASP.NET Core SAML SSO using your Identity Provider.


  • After integration, open your browser and browse the connector dashboard with the URL below:
    https://<asp.net-middleware-base-url>/?ssoaction=config
  • If the registration page or login page pops up, you have successfully added the miniOrange ASP.NET middleware authentication SAML SSO connector to your application.
ASP.NET Core- registeration page

  • Register or log in with your account by clicking the Register button to configure the middleware.
  • Under the Plugin Settings tab, select your identity provider from the list shown.
ASP.NET Core SAML Single Sign-On (SSO) using miniOrange as IDP - Add New IDP

There are two ways detailed below with which you can get the SAML SP metadata to configure onto your Identity Provider end.

A] Using SAML metadata URL or metadata file

  • In the Plugin Settings menu, look for Service Provider Settings. Under that, you can find the metadata URL as well as the option to download the SAML metadata.
  • Copy metadata URL or download the metadata file to configure the same on your identity provider end.
  • You may refer to the screenshot below:
ASP.NET Core- Service Provider Metadata

B] Uploading metadata manually

  • From the Service Provider Settings section, you can manually copy the service provider metadata like SP Entity ID, ACS URL, Single Logout URL and share it with your identity provider for configuration.
  • You may refer to the screenshot below:
ASP.NET Core- enter sp data manually

There are two ways detailed below with which you can configure your SAML Identity Provider metadata in the middleware.

A] Upload metadata using the Upload IDP Metadata button:

  • If your identity provider has provided you with the metadata URL or metadata file (.xml format only), then you can simply configure the identity provider metadata in the middleware using the Upload IDP Metadata option.
  • Copy metadata URL or download the metadata file to configure the same on your identity provider end.
  • You may refer to the screenshot below:
ASP.NET Core- Upload IDP Metadata

  • You can choose any one of the options according to the metadata format you have available.

B] Configure the identity provider metadata manually:

  • After configuring your Identity Provider, it will provide you with IDP Entity ID, IDP Single Sign On URL and SAML X509 Certificate fields respectively.
  • Click Save to save your IDP details.
ASP.NET Core- Configure IDP Manually
  • Click on the Test Configuration button to test whether the SAML Configuration you’ve done is correct.
  • The screenshot below shows a successful result. Click on SSO Integration to further continue with the SSO Integration.
ASP.NET Core- Test Configuration

  • If you are experiencing any error on the middleware end you’ll be shown with the window similar to below.
ASP.NET Core- Test Configuration Error

  • To troubleshoot the error you can follow the below steps:
  • Under Troubleshoot tab, enable the toggle to receive the plugin logs.
ASP.NET Core- TroubleShoot

  • Once enabled, you will be able to retrieve plugin logs by navigating to Plugin Settings tab and clicking on Test Configuration.
  • Download the log file from the Troubleshoot tab to see what went wrong.

  • After testing the configuration, Map your application attributes with the Identity Provider (IdP) attributes.
  • Note: All the mapped attributes will be stored in the session so that you can access them in your application.
ASP.NET Core- Attribute Mapping


  • This steps allow you to retrieve the SSO user information in your application in the form of user claims.
  • Note: This trial middleware only supports user information in claims, retrieving user information in session and headers is available in the premium plugin
  • Create a GET Endpoint in the .NET side to return the JWT token after login.
    Note: If you have a method to create a JWT, you just need to pick the claims from the .NET cookie.
    Below is the code for your reference:
  • [HttpGet("gettoken")]
    public string GetToken()
    {
      if(User.Identity!=null && User.Identity.IsAuthenticated)
      {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes
        ("Your-JWT-secret-key"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var identity = (ClaimsIdentity)User.Identity;
        var claims = identity.Claims;

        var token = new JwtSecurityToken(
          issuer:"<issuer-name>",
          audience:"<audience>",
          claims:claims,
          expires: DateTime.UtcNow.AddHours(1),
          signingCredentials: creds
          );
          return new JwtSecurityTokenHandler().WriteToken(token);
      }
      return null;
      }
  • Hover on Select Actions and click on Copy SSO Link.
ASP.NET Core Copy SSO Link

  • Use the following URL as a link in the application from where you want to perform SSO:
  • https://<application-url>?ssoaction=login&appid=<app-id>
  • After login, you will be redirected back to your frontend application, then you will be required to make an api call to get the token and user information.
  • Below is the sample code you can use to make the api call to the token endpoint to get the token from the frontend side.
  • fetch("https://<backend-api-baseurl>/api/gettoken", {
      method: "GET",
    })
    .then((response) => {
      //here you will receive the jwt token and the user details
      console.log(response);
    });
  • Start your ASP.NET Core Web API application
  • Start your frontend application
  • From the frontend application, click the SSO Login button you have added
  • After SAML login, you will be redirected back to your frontend application. At this point, your frontend application calls the /api/gettoken endpoint, which returns the token and user details. You can use the JWT token to make your further api calls.
JWT Token

Note: If you are using the Authorize attribute on the API for token validation, you will be required to specify the authentication policy as we have now multiple policies registered.

For JWT use: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]


Please reach out to us at aspnetsupport@xecurify.com, and our team will assist you with setting up the ASP.NET Core SAML SSO. Our team will help you to select the best suitable solution/plan as per your requirement.

ADFS_sso ×
Hello there!

Need Help? We are right here!

support