【问题标题】:CORS origin error using angular 8 with web api2使用 angular 8 和 web api2 的 CORS 起源错误
【发布时间】: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


    【解决方案1】:

    您需要从服务中删除响应标头,因为您在启动类中允许 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;
                }
    
            }
    

    【讨论】:

    • 非常感谢它的帮助。
    猜你喜欢
    • 2017-05-28
    • 2017-05-31
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-10-30
    • 2017-12-05
    相关资源
    最近更新 更多