forked from content-manager-sdk/Community
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCORSModule.cs
More file actions
94 lines (72 loc) · 2.89 KB
/
CORSModule.cs
File metadata and controls
94 lines (72 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
// THANK YOU:
// * https://evolpin.wordpress.com/2012/10/12/the-cors/
// * Thomas Tran
public class CORSModule : IHttpModule
{
private string[] origins;
private string methods = "POST,GET,OPTIONS";
private string headers = "Content-Type, Authorization";
public void Init(HttpApplication context)
{
//Get list of origin domains
var originConfigs = ConfigurationManager.AppSettings["allowedOrigins"];
this.origins = (originConfigs ?? "").Split(',').Select(o => o.Trim()).ToArray();
context.PreSendRequestHeaders += delegate
{
var response = context.Response;
#region try to build the current url requested by user
var referredUrl = "";
if (context.Request.UrlReferrer != null)
{
referredUrl = context.Request.UrlReferrer.Scheme + "://" + context.Request.UrlReferrer.Host;
if (context.Request.UrlReferrer.Port != 80)
{
referredUrl = referredUrl + ":" + context.Request.UrlReferrer.Port;
}
}
#endregion
//check the current origin within the list from config file.
//if yes, add it to the response header
if (this.origins.Contains(referredUrl, StringComparer.InvariantCultureIgnoreCase))
{
response.AppendHeader("Access-Control-Allow-Origin", referredUrl);
response.AppendHeader("Access-Control-Allow-Credentials", "true");
if (!string.IsNullOrWhiteSpace(this.methods))
{
response.AppendHeader("Access-Control-Allow-Methods", this.methods);
}
if (!string.IsNullOrWhiteSpace(this.headers))
{
response.AppendHeader("Access-Control-Allow-Headers", this.headers);
}
}
//otherwise allow all origins by default if no origins set in appSettings
else if (this.origins.Length == 0)
{
response.AppendHeader("Access-Control-Allow-Origin", "*");
response.AppendHeader("Access-Control-Allow-Credentials", "false");
if (!string.IsNullOrWhiteSpace(this.methods))
{
response.AppendHeader("Access-Control-Allow-Methods", this.methods);
}
if (!string.IsNullOrWhiteSpace(this.headers))
{
response.AppendHeader("Access-Control-Allow-Headers", this.headers);
}
}
//fix preflight
if (context.Request.HttpMethod == "OPTIONS")
{
response.StatusCode = (int)HttpStatusCode.OK;
}
};
}
public void Dispose()
{
}
}