【发布时间】:2014-09-19 07:37:10
【问题描述】:
在我的应用程序中,我使用带有基于令牌的身份验证和 CORS 支持的 web api,但是当客户端请求令牌时,由于 CORS(跨源请求被阻止:同源策略不允许读取远程资源) (我的站点名称)。可以通过将资源移动到同一域或启用 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
应用的网址是
服务器应用(应该支持 CORS)
{http://talenterp}
令牌终点:
{http://talenterp/token}
客户端应用
{http://talentmvc:85}
注意:我已经添加了
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
在我的 AuthorizationServerProvider 的 GrantResourceOwnerCredentials() 方法中
【问题讨论】:
-
已解决.. 问题出在配置 CORS app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); config.EnableCors(); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });我刚刚删除了第一个
-
嗨!这真的对你有用吗?谢谢。
-
删除 config.EnableCors() 行而不是 app.UserCors() 可能更好。前者不使用 OWIN,后者使用。展望未来,最好使用 OWIN 管道设置。
-
@BinsonEldhose 请接受回答。
-
您还需要从 web.config 中删除
,参见stackoverflow.com/a/33664502/631527
标签: asp.net-mvc asp.net-web-api cors owin katana