Web 中的 OWIN CORS 问题 API

OWIN CORS Issue in Web API

我正在使用 WebApi 并尝试使用 OWIN 添加基于令牌的身份验证。当客户端和服务在同一端口时,它工作正常。但是当两者都在不同的服务器上时会遇到问题。 我正在使用 Jquery Ajax 方法来调用令牌服务。 这是我使用的代码示例。 欧文代码:

 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());  

       }  

   }  

提供商

    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 == "Test@Mail.com" && 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 配置

    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 }  
               );  
}  
} 

单击登录按钮时将调用以下代码片段。

$('#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();  
    }  
});  

正在关注问题。

XMLHttpRequest 无法加载 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' 因此不允许访问。

正如 Marcus 所说,在 Web API 或 OWIN 中提及 CORS 设置就足够了。