【发布时间】:2017-04-24 15:16:03
【问题描述】:
我正在使用 WebApi 并尝试使用 OWIN 添加基于令牌的身份验证。当客户端和服务在同一个端口时,它工作正常。但是当两者都在不同的服务器上时面临一个问题。 我正在使用 Jquery Ajax 方法来调用令牌服务。 这是我使用的代码示例。 OWIN代码:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
ConfigureOAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/WagtokenService"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new ProjectAuthorizationServiceProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
提供者
public class ProjectAuthorizationServiceProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
if (allowedOrigin == null) allowedOrigin = "*";
bool isValidUser = false;
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
if (context.UserName == "Test@Mail.com" && context.Password == "national")
{
isValidUser = true;
}
if (!isValidUser)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "admin"));
context.Validated(identity);
}
}
WebApi 配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://192.168.2.175:3330", "WagtokenService,accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "NewActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
点击登录按钮时会调用以下代码sn-p。
$('#a_login').click(function (e) {
debugger;
if (isValidEmailAddress($('#txt_UID').val()) && $('#txt_PWD').val() != "") {
var loginData = {
grant_type: 'password',
username: $('#txt_UID').val(),
password: $('#txt_PWD').val()
};
$.ajax({
url: url_bearerToken,
type: 'POST',
data: loginData,
contentType: "application/json",
done: function (data) {
// alert('success fully sign in to the application');
sessionStorage.setItem(bearer_token_key, data.access_token);
},
success: function (data) {
// alert('success fully sign in to the application');
sessionStorage.setItem(bearer_token_key, data.access_token);
window.location.href = "../Admin/UserProfiler.html";
},
error: function (x, h, r) {
///e.preventDefault();
// alert("Invalid user credentials");
$('#div_alert').show();
sessionStorage.setItem(bearer_token_key, '');
}
});
}
else {
$('#div_alert').show();
}
});
得到关注问题。
XMLHttpRequest 无法加载 http://localhost:53014/WagtokenService。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://192.168.2.175:3330' 不允许访问。
【问题讨论】:
-
在启动类的owin IAppBuilder接口中启用cors应该足够了。尝试删除 config.EnableCors(cors);在 web api 配置类中,然后再试一次?
-
是的,你是正确的马库斯。在一个地方(Web API 或 OWIN 或 Webconfig)启用 CORS 就足够了。
-
太棒了!它解决了你的问题吗?
-
是的,马库斯,之前我在响应头中有多个 Access-Control-Allow-Origin,现在已经解决了,谢谢
标签: asp.net-web-api cors access-token preflight owin-middleware