Asp.net-Mvc

CORS 無法在具有 OWIN 身份驗證的 Web api 中工作

  • July 28, 2014

在我的應用程序中,我使用基於令牌的身份驗證和 CORS 支持的 web api,但是當客戶端請求令牌時,由於 CORS 發生錯誤(跨源請求被阻止:同源策略不允許讀取遠端資源(我的站點name) 。這可以通過將資源移動到同一域或啟用 CORS 來解決。)

我已經配置了 CORS 支持所需的一切(我認為是這樣)。這是我的配置

歐文創業班

  public class Startup
   {
       public void Configuration(IAppBuilder app)
       {


           var config = new HttpConfiguration
           {
               DependencyResolver = new StructureMapWebApiDependencyResolver(container)

           };


           WebApiConfig.Register(config);  // registering web api configuration
           app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  // cors for owin token pipeline
           app.UseWebApi(config);
           ConfigureOAuth(app);


       }

       public void ConfigureOAuth(IAppBuilder app)
       {
           var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions()
           {

               AllowInsecureHttp = true,
               TokenEndpointPath = new PathString("/token"),
               AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
               Provider = new SimpleAuthorizationServerProvider()
           };
           // Token Generation
           app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
           app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

       }
   }

還有我的 webapi 配置

public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
           config.EnableCors();  // Corse support for Web api
           config.MapHttpAttributeRoutes(); // attribute based urls

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

       }
   }

這裡在 web.config 中配置

<system.webserver>
<httpProtocol>
     <customHeaders>
       <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request-->
       <add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
     </customHeaders>
   </httpProtocol>
</system.webserver>

和我來自 Mozilla 的請求標頭

Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  67
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    talenterp
Origin  http://192.168.1.11:85
Referer http://192.168.1.11:85/
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0

應用程序的 URL 是

伺服器應用程序(應該支持 CORS)

{http://talenterp}

令牌端點:

{http://talenterp/token}

客戶端應用

{http://talentmvc:85}

注意:我已經添加了

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

在我的 AuthorizationServerProvider 的 GrantResourceOwnerCredentials() 方法中

確保你只有

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

配置,而不是Global.asax 或 WebApiConfig 中的舊樣式 ‘config.EnableCors()’。此外:將上述語句作為您自己的 Startup 類中的第一個語句。是的,這確實有所作為,稍後設置它也會導致 cors 不起作用。

public partial class Startup
{
   public void Configuration(IAppBuilder app)
   {
       app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

       ... etc

引用自:https://stackoverflow.com/questions/24989769