【发布时间】:2020-09-09 16:25:41
【问题描述】:
我正在使用 web api 2 处理 angular 8。当我尝试登录调用以下链接 http://localhost:20863/api/token 时,它给了我这个错误。
从源“http://localhost:4200”访问“http://localhost:20863/api/token”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
这是我的代码
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);
}
虽然我允许来自 web api 的 cors,但这里是我的 startup.cs 代码。
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
UnityConfig.Register(config);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
这是我用来验证用户身份的服务。
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;
}
}
【问题讨论】:
标签: angular asp.net-web-api2 angular8