Search code examples
asp.net-web-apicorsaccess-tokenpreflightowin-middleware

OWIN CORS Issue in Web API


I am working with WebApi and trying to add token based authentication using OWIN. It is working fine when client and service are in the same port. But facing a problem when both are on different servers. I am using Jquery Ajax method to call the token service. Here is the code sample I have used. OWIN Code :

 public class Startup  
   {  
       public void Configuration(IAppBuilder app)  
       {  
           HttpConfiguration config = new HttpConfiguration();  
           WebApiConfig.Register(config);  
           ConfigureOAuth(app);  
           app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  
           app.UseWebApi(config);  
       }  
       public void ConfigureOAuth(IAppBuilder app)  
       {  

           OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()  
           {  

               AllowInsecureHttp = true,  
               TokenEndpointPath = new PathString("/WagtokenService"),  
               AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),  
               Provider = new ProjectAuthorizationServiceProvider()  
           };  

           // Token Generation  
           app.UseOAuthAuthorizationServer(OAuthServerOptions);  

           app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());  

       }  

   }  

Provider

    public class ProjectAuthorizationServiceProvider : OAuthAuthorizationServerProvider  
   {  
       public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)  
       {  
           context.Validated();  
       }  

       public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)  
       {  
           var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");  
           if (allowedOrigin == null) allowedOrigin = "*";  
           bool isValidUser = false;  
           context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });  

           if (context.UserName == "[email protected]" && context.Password == "national")  
           {  
               isValidUser = true;  
           }  

           if (!isValidUser)  
           {  
               context.SetError("invalid_grant", "The user name or password is incorrect.");  
               return;  
           }  

           var identity = new ClaimsIdentity(context.Options.AuthenticationType);  
           identity.AddClaim(new Claim("sub", context.UserName));  
           identity.AddClaim(new Claim("role", "admin"));  

           context.Validated(identity);  
       }  
   }  

WebApi Config

    public static class WebApiConfig  
    {  
        public static void Register(HttpConfiguration config)  
        {  
            var cors = new EnableCorsAttribute("http://192.168.2.175:3330", "WagtokenService,accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");  

            config.EnableCors(cors);  

            config.Routes.MapHttpRoute(  
                name: "DefaultApi",  
                routeTemplate: "api/{controller}/{id}",  
                defaults: new { id = RouteParameter.Optional }  
            );  
            config.Routes.MapHttpRoute(  
               name: "NewActionApi",  
               routeTemplate: "api/{controller}/{action}/{id}",  
               defaults: new { id = RouteParameter.Optional }  
               );  
}  
} 

Following code snippet will be called when login button is clicked.

$('#a_login').click(function (e) {  
    debugger;  
    if (isValidEmailAddress($('#txt_UID').val()) && $('#txt_PWD').val() != "") {  
        var loginData = {  
            grant_type: 'password',  
            username: $('#txt_UID').val(),  
            password: $('#txt_PWD').val()  
        };  

        $.ajax({  
            url: url_bearerToken,  
            type: 'POST',  
            data: loginData,  
            contentType: "application/json",  
            done: function (data) {  
                // alert('success fully sign in to the application');  
                sessionStorage.setItem(bearer_token_key, data.access_token);  
            },  
            success: function (data) {  
                // alert('success fully sign in to the application');  
                sessionStorage.setItem(bearer_token_key, data.access_token);  
                window.location.href = "../Admin/UserProfiler.html";  
            },  
            error: function (x, h, r) {  
                ///e.preventDefault();  
                // alert("Invalid user credentials");  
                $('#div_alert').show();  
                sessionStorage.setItem(bearer_token_key, '');  
            }  
        });  
    }  
    else {  
        $('#div_alert').show();  
    }  
});  

Getting Following issue .

XMLHttpRequest cannot load http://localhost:53014/WagtokenService. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.175:3330' is therefore not allowed access.


Solution

  • As Marcus said , it is enough to mention CORS setting either in Web API or in OWIN.