webapi 2.0 cross origin behaviour

2019-08-22 21:46发布

i am using default webapi ApplicationOAuthProvider code below to login. and i add in

   <add name="Access-Control-Allow-Origin" value="*" />

in the web.config and client is able to login via www.testapi.com/token. everything works fine.

But when i create a custom webapi function. it is still asking me for access-origin control to enable. So i do so by adding this line of code in WebapiConfig.cs

 EnableCorsAttribute cors = new EnableCorsAttribute("http://www.myweb.com:82", "*", "*");
        config.EnableCors(cors);

this time it prompt error saying

''Access-Control-Allow-Origin' header contains multiple values 'http://www.myweb.com:82, *', but only one is allowed. Origin 'http://www.myweb.com:82' is therefore not allowed access.

so i remove the <add name="Access-Control-Allow-Origin" value="*" /> in the web.config and it works!!.

i return to the login and it is asking for <add name="Access-Control-Allow-Origin" value="*" /> to be added. but if i add this in. my webapi method will not be able to call.

if i dont add. client will not be able to log in.

is there a way for both to work? below is the response of 200 with error. enter image description here

Update 1 startup.auth.cs

   public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);//as instructed

webapiconfig.cs

 public static void Register(HttpConfiguration config)
    {


        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        WebApiConfig.Register(config);
        config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
        //var jsonp = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
        //config.Formatters.Insert(0, jsonp);
    }
}

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-22 22:05
  1. Install Microsoft.AspNet.WebApi.Cors nuget package
  2. Install Microsoft.Owin.Cors nuget package
  3. Add config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE")); to the above of WebApiConfig.Register(config); line at Startup.cs file.
  4. Add app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); to the Startup.Auth.cs file. This must be done prior to calling IAppBuilder.UseWebApi
查看更多
3楼-- · 2019-08-22 22:14

ok finally i managed to get it work with help from "@manprit Singh Sahota"

i remove all the access policy from web.config. and also the line below in WebApiConfig

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

i only add this line to the Startup.Auth.cs

 public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);//working line

enter image description here

查看更多
登录 后发表回答