【发布时间】:2016-10-03 06:56:04
【问题描述】:
我需要从 web api 服务器实现 OWIN 授权。下面是我的启动课。
[assembly: OwinStartup(typeof(SpaServerSide.MyStartUp))]
namespace SpaServerSide
{
public class MyStartUp
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
app.Map("/signalr", map =>
{
map.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
var hubConfig = new Microsoft.AspNet.SignalR.HubConfiguration { };
map.RunSignalR(hubConfig);
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/#")
});
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
Provider = new SpaServerSide.Shared.OAuthTokenServer()
};
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
}
}
然后,我将 OAuthAuthorizationServerProvider 实现如下:
public class OAuthTokenServer : OAuthAuthorizationServerProvider
{
public ASPIdentityUserManager cusUserManager;
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
var user = await cusUserManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "Username and password do not match.");
return;
}
var identity = await cusUserManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
context.Validated(identity);
}
}
之后,我在http://localhost:5587 上托管了Web 服务器,在http://localhost 上托管了客户端网站。当我尝试使用 Angular JS 请求令牌时,浏览器向我抛出了 CORS 错误。消息如下:
跨域请求被阻止:同源策略不允许读取 http://localhost:5587/Token 的远程资源。 (原因:CORS 缺少标头“访问控制允许来源”)。
请给我建议任何我会错过的东西。
【问题讨论】:
标签: asp.net-web-api oauth cors