我使用默认webapi ApplicationOAuthProvider
代码以下登录。我添加在webapi 2.0跨源的行为
<add name="Access-Control-Allow-Origin" value="*" />
在web.config和客户端能够通过www.testapi.com/token登录。 一切工作正常。
但是,当我创建一个自定义的webapi功能。它仍然要求我启用访问源控制。所以我加入这行代码在WebapiConfig.cs
EnableCorsAttribute cors = new EnableCorsAttribute("http://www.myweb.com:82", "*", "*");
config.EnableCors(cors);
这个时候提示错误说
'访问控制允许来源头包含多个值‘http://www.myweb.com:82,*’这样做,但只有一个是允许的。因此,'http://www.myweb.com:82'不允许访问。
所以我删除了web.config中的<add name="Access-Control-Allow-Origin" value="*" />
,它的工作原理。
我返回到登录,它要求添加<add name="Access-Control-Allow-Origin" value="*" />
。但如果我添加这个。我的webapi方法将无法调用。
如果我不加。客户端将无法登录。
更新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);
}
}
线在你的API控制器'[EnableCors(来源补充一点: “*”,头文件:“*”,方法:“*”,exposedHeaders:“X-My-Header”)]'这是控制器级别。您可以添加相同的特定操作方法来启用核心。 –
它仍然显示相同的错误“只有一个是允许的我没有删除web.config中的访问来源 –