对预检请求的响应未通过访问控制检查:它没有HTTP正常状态.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

查看:74
本文介绍了对预检请求的响应未通过访问控制检查:它没有HTTP正常状态.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.来源为 http://localhost:xxxx 的xx:xxyy/xxx/xxxxxx/Method '被CORS政策封锁:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态.

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()以及其他策略设置,这对我有效,适用于从我的角度对我的api进行的POST调用,该调用在两个不同的端口号上运行.

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).

您可以使用修饰[授权],在仅希望经过身份验证的用户的特定路由上检查传入的用户.就我而言,我只有一种方法可以期望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调用预检检查.就像我的情况一样,在我从我的有角度的应用程序获取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正常状态.GET POST PUT DELETE无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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