question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Implement CORS Support

See original GitHub issue

Given that CORS is disabled by default when using HttpListener, here is a work around until I can provide a more elegant solution.

Implementing CORS

You can implement access control via CORS for all requests using a BeforeRouting delegate. Add additional filtering logic if you only want to the policy to vary based on the request. This avoids the need to add these lines to individual routes, and allows you to manage the policy for the entire server in a single location.

server.Router.BeforeRouting += MyCorsPolicy;

Following are several ways you can define your policy.

Using the Wildcard

When using the wildcard value, it is important to remember that:

For requests without credentials, the literal value “*” can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials will result in an error. source

void MyCorsPolicy(IHttpContext context)
{
    context.Response.AddHeader("Access-Control-Allow-Origin", "*");
    context.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");
}

Additionally, when specifying Access-Control-Allow-Headers header:

The simple headers, Accept, Accept-Language, Content-Language, Content-Type (but only with a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain), are always available and don’t need to be listed by this header. source

Single Origin

When specifying a single origin, it is important to remeber that:

Two URLs have the same origin if the protocol, port (if specified), and host are the same for both. source

void MyCorsPolicy(IHttpContext context)
{
    context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:1234/");
    context.Response.AddHeader("Vary", "Origin");
}

Additionally, the Vary header should be provided:

If the server sends a response with an Access-Control-Allow-Origin value that is an explicit origin (rather than the “*” wildcard), then the response should also include a Vary response header with the value Origin — to indicate to browsers that server responses can differ based on the value of the Origin request header. source

Dynamic Origin

Limiting the possible Access-Control-Allow-Origin values to a set of allowed origins requires code on the server side to check the value of the Origin request header, compare that to a list of allowed origins, and then if the Origin value is in the list, to set the Access-Control-Allow-Origin value to the same value as the Origin value. source

void MyCorsPolicy(IHttpContext context)
{
    var domain = context.Request.UrlReferrer?.ToString();

    if (!string.IsNullOrWhiteSpace(domain) && ValidOrigins.Contains(domain))
    {
        context.Response.AddHeader("Access-Control-Allow-Origin", domain);
        context.Response.AddHeader("Vary", "Origin");
    }
}

IEnumerable<string> ValidOrigins
{
    get
    {
        yield return "http://mydomain.org/";
        yield return "http://localhost:1234";
    }
}

Dynamic Routes

If only some routes should allow CORS, you can put whatever logic you want to see in the delegate based on the incoming request. Just remember to follow the rules outlined above!

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
DavidFlaminicommented, Jul 20, 2018

Hi, today I wanted to test locally with both CORS + Basic Auth without configuring a proxy and run into my own post, I ended up parsing the auth header myself like so:

static private bool IsAuthorized(string AuthorizationHeader)
{
    try
    {
        var identity = Encoding.UTF8.GetString(Convert.FromBase64String(AuthorizationHeader.Split(" ")[1])).Split(":");
        var name = identity[0];
        var password = identity[1];


        if (name == "user" && password == "password")
        {
            return true;
        }

        return false;
    }
    catch (Exception ex )
    {

        return false;
    }
}
[RestRoute(PathInfo = "/api/v1/services")]
public IHttpContext Services(IHttpContext context)
{
    context.Response.ContentType = ContentType.JSON;

    if (IsAuthorized(context.Request.Headers["Authorization"]))
    {
        // Do stuff and send some response

    }
    else
    {
        context.Response.StatusCode = Grapevine.Shared.HttpStatusCode.Unauthorized;
        context.Response.SendResponse("{\"Error\": \"Unauthorized\"}");
    }
    return context;
}
1reaction
lacucommented, Nov 19, 2018

I have not been able to solve the CORS problem, I have added the header to the response but it does not work this is my code in the app

context.Response.Headers["Access-Control-Allow-Origin"] = "*";
context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS,PATCH");
context.Response.AddHeader("Access-Control-Allow-Origin", "*");

and this is the result in browser image

Someone find a solution??? Thanks!!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cross-Origin Resource Sharing (CORS) - MDN Web Docs
The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such ...
Read more >
I want to add CORS support to my server
I want to add CORS support to my server. There are some more headers and settings involved if you want to support verbs...
Read more >
Enabling Cross Origin Requests for a RESTful Web Service
You can enable cross-origin resource sharing (CORS) from either in individual controllers or globally. The following topics describe how to do so:.
Read more >
CORS Tutorial: A Guide to Cross-Origin Resource Sharing
Tutorial on modifying existing applications to support CORS. ... Learn all about Cross-Origin Resource Sharing, how it protects you, ...
Read more >
CORS Enabled - W3C Wiki
Open Internet Information Service (IIS) Manager · Right click the site you want to enable CORS for and go to Properties · Change...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found