C# WEB API / REST API CORS

Date: 2017-01-09
using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;

namespace WebApi.Helpers
{
    public class Startup
    {
        private class CorsHeaderFilter : System.Web.Http.Filters.ActionFilterAttribute
        {
            public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
        }

        public void Configuration(IAppBuilder app)
        {           
            ConfigureCors(app); // Cors support that just works (before ConfigureOAuth!)
            ConfigureOAuth(app);

            var config = new HttpConfiguration();
            config.Filters.Add(new CorsHeaderFilter());
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }        
        private static void SetCorsHeaders(IOwinContext context)
        {
            try
            {
                context.Response.Headers["Access-Control-Allow-Origin"] = context.Request.Headers.Get("Origin") ?? "*";
                context.Response.Headers["Access-Control-Allow-Headers"] = context.Request.Headers.Get("Access-Control-Request-Headers");
                context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
                context.Response.Headers["Access-Control-Expose-Headers"] = "Date, Content-Type, Content-Disposition, X-Total-Count, X-Employer-Code";
                context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
            }
            catch (Exception)
            {
                // ignore
            }
        }

        private void ConfigureCors(IAppBuilder app)
        {
            app.MapWhen(ctx => ctx.Request.Method.Equals("OPTIONS", System.StringComparison.OrdinalIgnoreCase), appBuilder =>
            {
                appBuilder.Run(context =>
                {
                    SetCorsHeaders(context);
                    return context.Response.WriteAsync("");
                });
            });

            app.Use(async (context, next) =>
            {
                SetCorsHeaders(context);
                await next();
                SetCorsHeaders(context);
            });
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            var serverOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
                Provider = new UserAuthorizationServerProvider(),
                RefreshTokenProvider = new RefreshTokenProvider()
            };

            app.UseOAuthAuthorizationServer(serverOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
}
5800cookie-checkC# WEB API / REST API CORS