简体   繁体   中英

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

I have made a asp.net web api which works perfectly when i try to access it by making views inside the api itself. I have made a register, a login and a data page where you are redirected after login. where a table with some data is shown. this works perfectly through the api views itself. Now the problem that arises here is that if i try to register by adding another project into the solution that'll work flawlessly. but i cant seem to login. i get a bad blocked by cors error. even though i have enabled cors in the api project.

This is the 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');
                }
            });
        });

The startup.auth.cs class: public partial class 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);

    }

The webapi.config register 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);
    }
}

How you are accessing "localhost:5833" ?? did you hosted your client/app at webserver ?? if you are using file protocol "file:\\" to access server resource you might get this cors error because of browser security. (for example double click to open the HTML file in browser is using a file:\\ protocol)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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