Ravi Kiran Chanduri

Ravi Kiran Chanduri

  • 676
  • 1.4k
  • 1.3m

Web Api OWIN CORS Issue

Dec 8 2016 5:33 AM
HI ,
I am working with Web Api and trying to add token based authentication using OWIN
I have implemented in my code and able to generate the token and access the webapi resource uing the token .
it is working when client and service in the same port and getting problem when both are in different server.
I have implemented Web API CORS and able to access from other server .
I have implemented Microsoft.Owin.Cors and used in the Startup class .
I am using Jquery Ajax method to call the token service .
Here is the code sample i have used .
 
 
OWIN Code :
 
  1. public class Startup  
  2.    {  
  3.        public void Configuration(IAppBuilder app)  
  4.        {  
  5.            HttpConfiguration config = new HttpConfiguration();  
  6.            WebApiConfig.Register(config);  
  7.            ConfigureOAuth(app);  
  8.            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  
  9.            app.UseWebApi(config);  
  10.        }  
  11.        public void ConfigureOAuth(IAppBuilder app)  
  12.        {  
  13.   
  14.            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()  
  15.            {  
  16.   
  17.                AllowInsecureHttp = true,  
  18.                TokenEndpointPath = new PathString("/WagtokenService"),  
  19.                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),  
  20.                Provider = new ProjectAuthorizationServiceProvider()  
  21.            };  
  22.   
  23.            // Token Generation  
  24.            app.UseOAuthAuthorizationServer(OAuthServerOptions);  
  25.   
  26.            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());  
  27.   
  28.        }  
  29.   
  30.    }  
 Provider
  1. public class ProjectAuthorizationServiceProvider : OAuthAuthorizationServerProvider  
  2.    {  
  3.        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)  
  4.        {  
  5.            context.Validated();  
  6.        }  
  7.   
  8.        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)  
  9.        {  
  10.            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");  
  11.            if (allowedOrigin == null) allowedOrigin = "*";  
  12.            bool isValidUser = false;  
  13.            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin"new[] { "*" });  
  14.   
  15.            if (context.UserName == "[email protected]" && context.Password == "national")  
  16.            {  
  17.                isValidUser = true;  
  18.            }  
  19.   
  20.            if (!isValidUser)  
  21.            {  
  22.                context.SetError("invalid_grant""The user name or password is incorrect.");  
  23.                return;  
  24.            }  
  25.   
  26.            var identity = new ClaimsIdentity(context.Options.AuthenticationType);  
  27.            identity.AddClaim(new Claim("sub", context.UserName));  
  28.            identity.AddClaim(new Claim("role""admin"));  
  29.   
  30.            context.Validated(identity);  
  31.        }  
  32.    }  
 WebApi Config 
  1. public static class WebApiConfig  
  2.     {  
  3.         public static void Register(HttpConfiguration config)  
  4.         {  
  5.             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");  
  6.   
  7.             config.EnableCors(cors);  
  8.   
  9.             config.Routes.MapHttpRoute(  
  10.                 name: "DefaultApi",  
  11.                 routeTemplate: "api/{controller}/{id}",  
  12.                 defaults: new { id = RouteParameter.Optional }  
  13.             );  
  14.             config.Routes.MapHttpRoute(  
  15.                name: "NewActionApi",  
  16.                routeTemplate: "api/{controller}/{action}/{id}",  
  17.                defaults: new { id = RouteParameter.Optional }  
  18.                );  
  19. }  
  20. }  
 Following code block will be called when log in button clicked 
  1. $('#a_login').click(function (e) {  
  2.         debugger;  
  3.         if (isValidEmailAddress($('#txt_UID').val()) && $('#txt_PWD').val() != "") {  
  4.             var loginData = {  
  5.                 grant_type: 'password',  
  6.                 username: $('#txt_UID').val(),  
  7.                 password: $('#txt_PWD').val()  
  8.             };  
  9.   
  10.             $.ajax({  
  11.                 url: url_bearerToken,  
  12.                 type: 'POST',  
  13.                 data: loginData,  
  14.                 contentType: "application/json",  
  15.                 done: function (data) {  
  16.                     // alert('success fully sign in to the application');  
  17.                     sessionStorage.setItem(bearer_token_key, data.access_token);  
  18.                 },  
  19.                 success: function (data) {  
  20.                     // alert('success fully sign in to the application');  
  21.                     sessionStorage.setItem(bearer_token_key, data.access_token);  
  22.                     window.location.href = "../Admin/UserProfiler.html";  
  23.                 },  
  24.                 error: function (x, h, r) {  
  25.                     ///e.preventDefault();  
  26.                     // alert("Invalid user credentials");  
  27.                     $('#div_alert').show();  
  28.                     sessionStorage.setItem(bearer_token_key, '');  
  29.                 }  
  30.             });  
  31.         }  
  32.         else {  
  33.             $('#div_alert').show();  
  34.         }  
  35.     });  
 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
 
 

Answers (6)