Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

482
Views
CORS in Ajax request against asp.net webforms with Identity Server 4 authorization

I'm currently working on a site that uses a number of ajax requests and iframes to load and search data. It was built using C#, ASP.Net webforms and jQuery (mainly used for the AJAX requests) and acts as a client to an IdentityServer4 based a single sign on solution.

The authorization / authentication process from the ASP.Net webforms client to IdentityServer works fine. However, the problem I have is when I'm redirected from IdentityServer4 to ASP.Net webforms and perform a search within the ASP.Net webforms site that involves making a jQuery AJAX request, I get the following error when I view the console tab in the web browser below.

Access to XMLHttpRequest at 'https://localhost:44307/connect/authorize? ' (redirected from 'https://localhost:44304/ajax/WebRequest.aspx/GetQuoteSearchDetails') from origin 'https://localhost:44304' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

I've provided a snapshot of the error described above here for your review, reference and clarification.

Below is the ASP.Net Webforms client setup so far.

    public void Configuration(IAppBuilder app)
    {
      JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();  
      IdentityModelEventSource.ShowPII = true;          
      // For more information on how to configure your application, visit 

      // Fix for Bad Request 400 stemming from too many nonce cookies added to the header which 
      // caused the site to crash. It appears that the authentication cookies were disappearing in the authentication
      // process. Hence the following line of code preserves such cookies from being lost. 

      app.UseKentorOwinCookieSaver();

      app.UseCookieAuthentication(new CookieAuthenticationOptions()
      {               
        AuthenticationType = "Cookies",
        LoginPath = new PathString("/Master/Login")
      });
      JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //in Identity3 example  https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/Clients/WebFormsClient/Startup.cs
      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
      {
        AuthenticationType = "oidc",
        Authority = "https://localhost:44307",
        ClientId = "WebformsClient",
        ResponseType = "code id_token",  //OpenIdConnectResponseType.CodeIdTokenToken,
        ClientSecret = "secret",
        Scope = "openid profile",
        RedirectUri = "https://localhost:44304/signin-oidc", //"https://localhost:44319/signin-oidc",
        PostLogoutRedirectUri = "https://localhost:44304/signout-callback-oidc", //"https://localhost:44319/signout-callback-oidc",
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
          AuthenticationFailed = context =>
          {
            context.HandleResponse();
            context.Response.Redirect("/Error?message=" + context.Exception.Message);
            return Task.FromResult(0);
          }
        },
        UseTokenLifetime = false,
        RequireHttpsMetadata = false,
        TokenValidationParameters = new TokenValidationParameters
        {
          NameClaimType = JwtRegisteredClaimNames.GivenName,
          RoleClaimType = ClaimTypes.Role
        },
        //ProtocolValidator = new OpenIdConnectProtocolValidator
        //{
        //    RequireNonce = false
        //},
        SignInAsAuthenticationType = "Cookies",
      });

      app.UseKentorOwinCookieSaver();
        app.UseStageMarker(PipelineStage.Authenticate); //in Identity3 example
      } 

Below is the IdentityServer4 setup for webforms client mentioned above.

new Client
{
  ClientId = "WebformsClient",
  ClientName = "Asp.Net Webforms Client",
  AllowedGrantTypes = GrantTypes.Hybrid,
  RequireConsent = false,
  AllowAccessTokensViaBrowser = true,
  AlwaysSendClientClaims = true,
  AlwaysIncludeUserClaimsInIdToken = true, 

  // where to redirect to after login                        
  RedirectUris = new List<string>()
  {
    "https://localhost:44304/signin-oidc"
  },                        

  //// where to redirect to after logout
  PostLogoutRedirectUris = new List<string>()
  {
    "https://localhost:44304/signout-callback-oidc"
  },

  AllowedScopes = new List<string>
  {
    IdentityServerConstants.StandardScopes.OpenId,
    IdentityServerConstants.StandardScopes.Profile
  },

  ClientSecrets =
  {
    new Secret("secret".ToSha256())
  },

  AllowedCorsOrigins = new List<string> {"192.168.6.112"}       
}

Having done some fact finding around the aforementioned issue which is related to CORS, I've tried the following suggestions below but had no joy so far.

Adding custom headers inside the WebformsClient's Web config (truncated for the sake of brevity)


    <system.webServer>    
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
          <add name="Access-Control-Allow-Headers" value="Content-Type, soapaction"/>
        </customHeaders>
      </httpProtocol>
    </system.webServer>

Setting custom headers in the WebformsClient Application_BeginRequeset handler

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
      //// Preflight request comes with HttpMethod OPTIONS
      if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
      {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        // The following line solves the error message
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        // If any http headers are shown in preflight error in browser console add them below
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
      }
    }

One of the AJAX requests that handles the requests and sends data back (also adding custom headers to allow CORS)

    ajax: {
      beforeSend: function (xhr) {
        xhr.setRequestHeader('Access-Control-Allow-Origin','*');
        xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
        xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type, soapaction');
      },
      method: "POST",
      url: "dummyURL",
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      //crossDomain: true,
      xhrFields: {
        withCredentials: true
      },
      //headers : {
      //    "accept": "application/json",
      //    "Access-Control-Allow-Origin":"*"
      //},
      data: function (d) {
        var SearchDetails = new Object();
        var aoData = [];

        // Removed some code for security reasons.

        return JSON.stringify({ SearchDetails: aoData });
      },
      datasrc: ""
    }   

With the information I've provided above I'm hoping if anyone could shed some light with regards to what needs to be done and if there's anything that I've omitted.

Any useful input and suggestions would be greatly appreciated.

UPDATE:

I've managed to resolve the original issue regarding the 'Access-Control-Allow-Origin' but now faced with another issue.

By adding the following response headers in server's (IdentityServer4) web.config under the "System.Webserver" tag as shown below, will remove the above issue but now leads to another problem relating to http status code 405 BAD METHOD, OPTIONS not allowed" (refer to snapshot below).

    <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="https://localhost:44304" />
          <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
          <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, soapaction" />
          <add name="Access-Control-Allow-Credentials" value="true" />
          <add name="Accept" value="application/json" />
        </customHeaders>
    </httpProtocol>

Http status code 405 "BAD METHOD: OPTIONS" snapshot.

Http status code 405 error snapshot

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!