Showing posts with label CORS. Show all posts
Showing posts with label CORS. Show all posts

Tuesday, July 5, 2022

How to enable CORS options in Apollo-Server-Micro?

 According the Apollo Server documentation, the CORS option is not available in server configuration.  

"Note that apollo-server-micro does not have a built-in way of setting CORS headers."

when  we create a apollo server, we can't set the cors options in the configuration object.

import {ApolloServer} from 'apollo-server-micro';
import 'reflect-metadata';
import { buildSchema } from 'type-graphql';
import { PetsResolver } from '../../src/schema/pet.resolver';

const schema = await buildSchema({
  resolvers: [PetsResolver],
});


const server = new ApolloServer({
    schema,
    csrfPrevention: true,  // see below for more about this
    cache: "bounded",
});

As a result, we should encounter the following CORS policy issue 

Access to fetch at 'http://localhost:3000/api/graphql' from origin 'https://studio.apollographql.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Since we can't add the cors option with the configruation object, we have to manually add those cors options in the handler function

export default async function handler(req:any, res:any){
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader(
        "Access-Control-Allow-Origin",
        "https://studio.apollographql.com"
    );
    res.setHeader(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept,
        Access-Control-Allow-Methods, Access-Control-Allow-Origin,
        Access-Control-Allow-Credentials, Access-Control-Allow-Headers"
    );
    res.setHeader(
        "Access-Control-Allow-Methods",
        "POST, GET, PUT, PATCH, DELETE, OPTIONS, HEAD"
    );
    if (req.method === "OPTIONS") {
        res.end();
        return false;
    }

    await startServer;
    await server.createHandler({path:"/api/graphql"})(req, res);
}


Now the cross site access violation should be resolved and we can manipulate the query and mutation in the apollo-studio.


Sunday, March 29, 2020

how to fix "Access to XMLHttpRequest at 'http://localhost:7071/api/' from origin 'http://localhost:3000' has been blocked by CORS policy" in Azure Serverless implementation?

when i implemented the Web API using Azure functions in Azure Serverless development. i try to run the Azure fucntion in the localhost from visual studio code. the error came up immdiately after i test the create function.

"Access to XMLHttpRequest at 'http://localhost:7071/api/createSpeaker/' from origin 'http://localhost:3000' 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."

the error message clearly indicated that it was a CORS issue. which is the web app hosts on port 3000 and tries to access the web API hosts on port 7071.

according to the microsoft document. it suggested that we should add the following configuration to the local.settings.json file which is the configure file for azure functions running in local mode.

https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash

"Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  },

however the above never works for me. acutally the following command line did fix the issue

func host start --cors *

Happy programming and enjoy the fun




Tuesday, April 11, 2017

Advanced configuration and implementation in enabling Cross-Origin Requests in ASP.NET Web API 2

After we deploy the Web Api or WCF to cloud or in the public network. It means that we already expose the data to any one who know the url of the Web Api or WCF.

I will skip the introduction to setting up the Cross-Origin Requests in ASP.NET Web API 2 here.

For more information about the CORS for Web Api. you can visit MSDN link

Enabling Cross-Origin Requests in ASP.NET Web API 2


i will only focus on the a little bit advance topic on CORS implementation, since i had spend
extend period of time to complete the implementation.


1. control the CORS with custom setting in web.config file.

the configuration setting will allow us to add more domains without any code change and depolyment, we only need system admin to add more domain in the name attribute that separate by
comma.

<configSections>
    <section name="CORSSettings" type="MyApp.CORSSettings, MyApp" />
  </configSections>


 <CORSSettings>
    <CorsSupport>
      <Domain Name="http://firstdomain,http://seconddomain,http://thirddomain" AllowMethods="*" AllowHeaders="*" AllowCredentials="true">
      </Domain>
    </CorsSupport>
  </CORSSettings>


2. Server Side Implementation  

 In the WebApiConfig class

added the following code to enable the CORS globally

var cORSSettings = ConfigurationManager.GetSection("CORSSettings") as CORSSettings;
            if (cORSSettings == null)
                throw new InvalidOperationException("Missing CORS configuration");
            var domains = cORSSettings.CorsSupport.OfType<CorsDomain>();
            foreach (var domain in domains)
            {
                var cors = new EnableCorsAttribute(domain.Name, domain.AllowHeaders, domain.AllowMethods);
                cors.SupportsCredentials = true;
                config.EnableCors(cors);
            }

please ensure the CORS object with property SupportsCredentials to be True, if your web api is configured with windows authentication and disable anonymous access. otherwise you will always receive XMLHttpRequest Network Error




3. Client Side Implementation

Even though you have enable the cors with SupportCredentials, you still will encouter the PreFlight request OPTIONS Error like
  "Origin http://YourDomain is not allowed by Access-Control-Allow-Origin"

when you use .ajax the jquery wrappper to execute the client call

$.ajax({
    type: 'get',
    url: 'http://www.example.com/api/test',
    xhrFields: {
        withCredentials: true
    }

actually we should use this XMLHttpRequest directly to call the web api to solve the preFlight request OPTIONS Error


                    var xmlHttpRequest = new XMLHttpRequest();
                    xmlHttpRequest.open('GET', sWCFUrl, true);
                    xmlHttpRequest.withCredentials = true;
                    xmlHttpRequest.onreadystatechange = processData;
                    xmlHttpRequest.send();
     

 I hope this post can help solve the headache on CORS implementation especiallly with windows authentication eanble and anonymous access diable.