CORS在使用OWIN身份验证的web api中无效

时间:2014-07-28 06:45:47

标签: asp.net-mvc asp.net-web-api cors owin katana

在我的应用程序中,我使用带有基于令牌的身份验证的web api和CORS支持,但是当客户端请求令牌时,由于CORS发生错误(跨源请求被阻止:同源策略不允许读取远程资源) (我的站点名称)。可以通过将资源移动到同一域或启用CORS来解决此问题。)

我已经配置了CORS支持所需的一切(我想是这样)。这是我的配置

Owin启动课程

   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

应用的网址

服务器应用程序(应该支持CORS)

{http://talenterp}

令牌终点:

{http://talenterp/token}

客户端应用

{http://talentmvc:85}

注意:我已添加

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

在AuthorizationServerProvider的GrantResourceOwnerCredentials()方法中

5 个答案:

答案 0 :(得分:59)

请确保您只有

  

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

配置,也是旧样式&#39; config.EnableCors()&#39;在您的Global.asax或WebApiConfig中。此外:将上述语句作为您的Owin Startup类中的第一个语句。是的,这确实有所不同,稍后设置它也会导致角色无法工作。

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

        ... etc

答案 1 :(得分:5)

OWIN和Microsoft.AspNet.WebApi.Cors是两个独立的库,每个库都需要单独配置。

禁止在OWIN中使用CORS:

public void Configuration(IAppBuilder app)
{
        //app.UseCors(CorsOptions.AllowAll);

找到GrantResourceOwnerCredentials方法并将Access-Control-Allow-Origin添加到上下文中,以便在完成身份验证后返回一个调用时,浏览器会找到标题并接受它。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost" });

现在将Nuget的Microsoft.AspNet.WebApi.Cors包安装到您的webapi项目中,并将其添加到Register方法

public static void Register(HttpConfiguration config)
{
        var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");

        config.EnableCors(cors);

这对我有用。

答案 2 :(得分:1)

特别是如果您在使用CORS时遇到Web API承载令牌问题,请不要忘记将“TOKEN”放在允许的方法列表中。

请将代码放在web.config的system.webServer中,这就是我解决的问题

<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE, TOKEN" />
 </customHeaders>

答案 3 :(得分:0)

我遇到了类似的问题,我在startup.cs中尝试了上述所有选项,我添加了app.UseCors(CorsOptions.AllowAll);在顶部和禁用的WebApiConfig中

public static void Register(HttpConfiguration config)
{
    //var cors = new EnableCorsAttribute("*", "*", "*");
    //config.EnableCors(cors);
}

并禁用了cors

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
}

并以相反的顺序重复此操作,并且在web.config中包含了条目,但所有条目均无效。

当我开始自问为什么app.UseWebApi(config);仍然无法访问时,我发现它在某处有效。我环顾四周,发现安装Install-Package Microsoft.AspNet.WebApi.OwinSelfHost可以解决此问题。

最终,它解决了整个问题,尽管app.UseCors(CorsOptions.AllowAll)必须放在startup.cs方法中。实际上,如果没有app.UseWebApi(config),我在邮递员中进行了测试,而终点实际上不存在。总体来说,现在对我来说效果很好。

答案 4 :(得分:0)

有同样的问题。除了上述指示(仅使用app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll),并将其设置为第一件事)外,我还必须在应用程序Web.config文件中指定以下内容,以便能够处理选项请求:

<system.webServer>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
  <remove name="OPTIONSVerbHandler"/>
  <remove name="TRACEVerbHandler"/>          
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
</system.webServer>

由于我在身份验证请求中发送了一些标头,因此在实际的POST请求之前发送了一个Options请求,并且它需要在发送POST之前返回正确的“ Access-Control-Allow-Origin”标头。

如果options响应未返回任何CORS标头,则将完全不发送POST。添加的配置支持此行为以及跟踪。

如本post

中所述