Angular 使用带web api2的角度8的CORS原点误差
我正在使用web api 2开发angular 8。当我试图登录调用下面的链接时,它给了我这个错误 CORS策略已阻止从源“”访问“”处的XMLHttpRequest:请求的资源上不存在“访问控制允许源”标头 这是我的密码Angular 使用带web api2的角度8的CORS原点误差,angular,asp.net-web-api2,angular8,Angular,Asp.net Web Api2,Angular8,我正在使用web api 2开发angular 8。当我试图登录调用下面的链接时,它给了我这个错误 CORS策略已阻止从源“”访问“”处的XMLHttpRequest:请求的资源上不存在“访问控制允许源”标头 这是我的密码 public Login(apiUrl: any, itemName: any): Observable<any> { const body = 'userName=' + itemName.UserName + '&password=' + it
public Login(apiUrl: any, itemName: any): Observable<any> {
const body = 'userName=' + itemName.UserName + '&password=' + itemName.Password + '&grant_type=password';
const options = { headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
}) };
return this.http.post(this.loginUrl + apiUrl, body, options);
}
这是我用来验证用户身份的服务
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
try
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
var roles = await _repo.GetRolesAsync(user.Id);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("UserName", context.UserName));
identity.AddClaim(new Claim("userId", user.Id));
context.Validated(identity);
}
catch (Exception ex)
{
throw ex;
}
}
您需要从您的服务中删除响应头,因为您在启动类中允许cors,这在这里没有意义
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
try
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
var roles = await _repo.GetRolesAsync(user.Id);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("UserName", context.UserName));
identity.AddClaim(new Claim("userId", user.Id));
context.Validated(identity);
}
catch (Exception ex)
{
throw ex;
}
}
非常感谢,这很有帮助。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
try
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
var roles = await _repo.GetRolesAsync(user.Id);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("UserName", context.UserName));
identity.AddClaim(new Claim("userId", user.Id));
context.Validated(identity);
}
catch (Exception ex)
{
throw ex;
}
}