问题描述
我正在尝试通过asp.net Web API 2对用户进行身份验证并生成令牌。当我使用邮递员发送请求时,它将生成令牌。但是当我使用Reactjs和Axios发送请求时,它给了我一个错误。
CORS策略已阻止从原点“ http:// localhost:3000”访问http:// localhost:4093 / token处的XMLHttpRequest:请求中不存在“ Access-Control-Allow-Origin”标头资源。
错误:网络错误 在createError(createError.js:16) 在XMLHttpRequest.handleError(xhr.js:83)
获取http:// localhost:4093 / token net :: ERR_Failed
我在WebApiConfig.cs中启用了cors,并将标头添加到ApplicationOAuthProvider.cs
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
);
}
}
ApplicationOAuthProvider.cs
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] { "*" });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password);
if (user == null)
{
context.SetError("invalid_grant","The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
login.js
submitCredential = user => {
const qs = require('querystring')
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}
const data = { username: user.Email,password: user.Password,grant_type: 'password' };
axios.get('http://localhost:4093/token',qs.stringify(data),config)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)