简体   繁体   English

使用 Angular 的服务器上的 WebApi 身份验证失败

[英]WebApi authentication failed on server with Angular

I am using Asp.Net web API 2.0 with Angular 6 for UI.我正在使用 Asp.Net Web API 2.0 和 Angular 6 for UI。 The solution contains the projects for angular and web API.该解决方案包含 angular 和 web API 的项目。 My solution works fine (I am able to access pages and login) when I am running it on Visual Studio on localhost.当我在本地主机上的 Visual Studio 上运行它时,我的解决方案工作正常(我能够访问页面和登录)。 However when I deploy the build on server I am unable to login and getting the below error:但是,当我在服务器上部署构建时,我无法登录并收到以下错误:

Access to XMLHttpRequest at 'http://xx.xx.xx.xxx:xxxxx/authenticate' from origin 'http://xx.xx.xx.xxx:xxxxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“http://xx.xx.xx.xxx:xxxxx”访问“http://xx.xx.xx.xxx:xxxxx/authenticate”处的 XMLHttpRequest:无“访问控制” -Allow-Origin' 标头存在于请求的资源上。

To quickly handle CORS for Web API, add below settings in web.config file of Web API inside <system.webServer> section:要快速处理 Web API 的 CORS,请在<system.webServer>部分内的 Web API 的 web.config 文件中添加以下设置:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

But there is a security risk involved in enabling CORS.但是启用 CORS 存在安全风险。 A good explanation is here .一个很好的解释是here

您能否将此以下代码添加到 startup.cs -> configure()

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials());

Browser security prevents a web page from making AJAX requests to another domain.浏览器安全防止网页向另一个域发出 AJAX 请求。 This restriction is called the same-origin policy and prevents a malicious site from reading sensitive data from another site.此限制称为同源策略,可防止恶意站点从其他站点读取敏感数据。 However, sometimes you might want to let other sites call your web API.但是,有时您可能希望让其他站点调用您的 Web API。

Install-Package Microsoft.AspNet.WebApi.Cors

Open the file App_Start/WebApiConfig.cs .打开文件App_Start/WebApiConfig.cs Add the following code to the WebApiConfig.Register method: config.EnableCors();将以下代码添加到 WebApiConfig.Register 方法中: config.EnableCors();

Next, add the [EnableCors] attribute to the Controller class接下来,将[EnableCors] 属性添加到 Controller 类中

[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }

Now you can access the API's现在您可以访问 API 的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM