对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态.GET 工作 POST PUT DELETE 不工作 [英] Response to preflight request doesn't pass access control check: It does not have HTTP ok status. GET working POST PUT DELETE not working

查看:85
本文介绍了对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态.GET 工作 POST PUT DELETE 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候

我有一个具有以下架构的 Web 应用程序:Web api:ASP.net core 2.1(Windows 身份验证)用户界面:角度 8

I have one web application with following architecture: Web api: ASP.net core 2.1 (Windows Authentication) UI: angular 8

UI 能够获取数据但无法发送数据.我的意思是 GET 方法工作正常,但 POST、PUT、DELETE 选项不起作用.并且所有方法都使用 POSTMAN 工作.

UI is able to get data but unable to send data. I mean GET method is working fine but POST, PUT, DELETE options are not working . And all the methods are working using POSTMAN.

错误是:在 'http://xx.xxx.xxx 访问 XMLHttpRequest.xx:xxyy/xxx/xxxxxx/Method' 来自 origin 'http://localhost:xxxx' 有被 CORS 政策阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态.

ERROR is: Access to XMLHttpRequest at 'http://xx.xxx.xxx.xx:xxyy/xxx/xxxxxx/Method' from origin 'http://localhost:xxxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

任何帮助将不胜感激.

提前致谢:)

推荐答案

这就是我使用的,它应该适用于您的情况.

This is what i use and it should work i hope for your case.

我的 startup.cs ConfigureServices() 装饰有:

My startup.cs ConfigureServices() decorated with:

services.AddCors(feature =>
                feature.AddPolicy(
                    "CorsPolicy",
                    apiPolicy => apiPolicy
                                    //.AllowAnyOrigin()
                                    //.WithOrigins("http://localhost:4200")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .SetIsOriginAllowed(host => true)
                                    .AllowCredentials()
                                ));

并且,Configure() 方法使用:

And, Configure() method with:

app.UseCors("CorsPolicy");

请注意 SetIsOriginAllowed() 和 allowCreds() 以及其他策略设置,这适用于我从我的 angular 对我的 api 进行 POST 调用,它们在两个不同的端口#s 上运行.

Notice the SetIsOriginAllowed() and allowCreds() along with other policy settings, this works for me with POST calls to my api from my angular, which are running on two different port#s.

更新:

按照评论中的问题,添加有关我们如何检查登录用户(windows auth)btwn api 和 angular(前端)的附加信息.

Following the questions on the comments, adding additional information on how do we check the logged in user (windows auth) btwn api and the angular (frontend).

您可以检查特定路由上的传入用户,该路由只需要使用装饰 [Authorize] 的经过身份验证的用户.就我而言,我只有一种方法可以期望 api 中的 Windows 用户:

You can check the incoming User on a specific route that would only expect the authenticated user using the decoration [Authorize]. In my case, i would have only one method that would expect the windows user in the api:

[HttpGet("UserInfo")]
[Authorize]
public IActionResult GetUserInfo()
{
    string defaultCxtUser = HttpContext?.User?.Identity?.Name;

    if (defaultCxtUser != null && !string.IsNullOrEmpty(defaultCxtUser))
    {
        _logger.LogDebug($"START - Get Context user details for {defaultCxtUser}");
        ADHelper.logger = _logger;
        var userFullName = ADHelper.GetUserIdentityInfo(defaultCxtUser);
        _logger.LogInformation($"Context user {defaultCxtUser} with name: {userFullName}");
        var userInfo = new { Name = userFullName };
        //_logger.LogDebug($"END - GetUserInfo({defaultCxtUser} for {userFullName}");
        return Ok(userInfo);
    }
    else
        return Ok(new { Name = defaultCxtUser });
}

然后我会从我的角度调用这个服务调用,

then i would call this from my angular with the service call as,

// Get the Logged in user info
GetCurrentUserInfo(): Observable<string> {
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  }),
  withCredentials: true
 };

// return this.http.get<string>(`${ApiPath}UserInfo`, httpOptions)
// .pipe(map(v => v as string));
return this.http.get<UserInfo>(`${ApiPath}UserInfo`, httpOptions)
.pipe(map(data => {
  // console.log(data, data.Name);
  return data.Name;
}))
;
}

请查看带有 'withCredentials: true' 行的标题,该行将触发传递当前用户信息,并且只有当它具有在 c# 端读取 User.Identity 对象的授权属性时,它才会被读取和理解.我们在特定方法上这样做的原因是,api 中应该有一些其他的父方法,如 ApiStatus() 或任何可能的方法,应该首先调用.这将确保还使用需要匿名身份验证的 OPTIONS 调用预检检查.就像在我的情况下一样,在我从我的 angular 应用程序获取 userInfo() 之前获取 api 是否可用并正在运行,以及其他一些应用程序环境信息.

Please see the headers with 'withCredentials: true' line that would trigger to pass the current user info, and it would be read and understood only if it has the authorize attr to read the User.Identity object in c# side. The reason we do this on a specific method is that, there should be some other parental method in the api like ApiStatus() or anything that could be, should be called first. This would ensure to also invoke the preflight check with OPTIONS that would require anonymous auth. Like in my case, getting whether the api is available and running, and some other app environment info before i get the userInfo() from my angular app.

这篇关于对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态.GET 工作 POST PUT DELETE 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆