-
Notifications
You must be signed in to change notification settings - Fork 11
/
CorsConfig.cs
51 lines (45 loc) · 1.62 KB
/
CorsConfig.cs
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
using Microsoft.Owin.Cors;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Cors;
namespace ReferenceProject
{
/// <summary>
/// Represents CORS configuration.
/// </summary>
/// <remarks>For more information see https://github.com/drwatson1/AspNet-WebApi/wiki#cross-origin-resource-sharing-cors</remarks>
public static class CorsConfig
{
/// <summary>
/// Initializes and configures <see cref="CorsOptions"/> instance.
/// </summary>
/// <param name="origins">String of allowed origins delimited by: ';'</param>
public static CorsOptions ConfigureCors(string origins = null)
{
if (string.IsNullOrWhiteSpace(origins))
return CorsOptions.AllowAll;
var corsPolicy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true,
SupportsCredentials = true,
PreflightMaxAge = 86400
};
corsPolicy.Headers.Add("Authorization");
// StringSplitOptions.RemoveEmptyEntries doesn't remove whitespaces.
origins.Split(';')
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToList()
.ForEach(origin => corsPolicy.Origins.Add(origin));
if (!corsPolicy.Origins.Any())
return CorsOptions.AllowAll;
return new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
};
}
}
}