繁体   English   中英

来自来源'http:// localhost:'的localhost:/ token请求已被CORS阻止

[英]Request at localhost:/token from origin 'http://localhost:' has been blocked by CORS

我制作了一个asp.net网络api,当我尝试通过在api本身内进行查看来访问它时,它可以完美地工作。 我做了一个注册器,一个登录名和一个数据页面,登录后您将在其中重定向。 显示带有一些数据的表。 这可以通过api视图本身完美地工作。 现在这里出现的问题是,如果我尝试通过将另一个项目完美地添加到解决方案中来进行注册,则可以正常工作。 但我似乎无法登录。 我被cors错误阻止了。 即使我在api项目中启用了cors。

这是jQuery:

            $.ajax({

                url: 'http://localhost:58334/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    username: $('#txtUsername').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },

                success: function (response) {
                    sessionStorage.setItem("accessToken", response.access_token);
                    sessionStorage.setItem("userName", response.userName);
                    window.location.href = "Data.html";
                },

                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });

startup.auth.cs类:公共局部类Startup {static Startup(){PublicClientId =“ self”;

        UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            AllowInsecureHttp = true
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }

    public static string PublicClientId { get; private set; }


    public void ConfigureAuth(IAppBuilder app)
    {

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);   
        app.UseOAuthBearerTokens(OAuthOptions);

    }

webapi.config注册methof:

        // Web API routes
        config.MapHttpAttributeRoutes();

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

        EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
       config.EnableCors(cors);
    }
}

您如何访问“ localhost:5833”? 您是否在网络服务器上托管了客户端/应用程序? 如果您使用文件协议“ file:\\”访问服务器资源,则由于浏览器的安全性,您可能会收到此cors错误。 (例如,双击使用文件:\\协议在浏览器中打开HTML文件)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM