Windows身份验证和Angular 7应用程序

时间:2019-09-03 09:38:17

标签: asp.net angular asp.net-web-api angular7 windows-authentication

我已经开发了Intranet应用程序

后端:ASP.NET WEB API-2(所有控制器都具有Authorize属性), 前端:Angular 7(在生成产品后,我将生成的脚本移到了后端项目中):

....
  <app-root> 
      <div id="preloader"></div>
  </app-root>


  <script type="text/javascript" src="~/Scripts/SPA/runtime.26209474bfa8dc87a77c.js"></script>
  <script type="text/javascript" src="~/Scripts/SPA/es2015-polyfills.bda95d5896422d031328.js" nomodule></script>
  <script type="text/javascript" src="~/Scripts/SPA/polyfills.8bbb231b43165d65d357.js"></script>
  <script type="text/javascript" src="~/Scripts/SPA/main.122a2bd84f391ab8df1d.js"></script>
</body>

问题是系统提示在部署到服务器后输入我的用户名/密码。如果用户输入凭据,它可以正常运行,但是我希望应用程序自动抓住登录的用户。

这是我的web.config

<authentication mode="Windows" />
   <authorization>
     <deny users="?" />
   </authorization>

这是我的角形拦截器

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class CredentialsInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

在Visual Studio 2019项目设置中

匿名身份验证:已启用

Windows身份验证:已启用

托管管道模式:集成

Global.asax

protected void Application_BeginRequest(Object sender, EventArgs e)
       {
           //Preflight request comes with HttpMethod OPTIONS
           //The following line solves the error message
           //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4202");
           HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
           if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
           {
               HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
               HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
               HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization");
               HttpContext.Current.Response.End();
           }
       }

2 个答案:

答案 0 :(得分:1)

当您输入凭据时,一切正常,这意味着这是客户端问题,而不是服务器端问题。浏览器不会自动发送您的凭据。

仅当该网站位于“ Internet选项”中的“受信任的网站”列表中时,Chrome和IE才会自动发送当前登录用户的凭据。

  1. 打开“开始”菜单。
  2. 键入“ Internet选项”,然后单击它。
  3. 点击“安全”标签。
  4. 单击“受信任的站点”图标。
  5. 点击“站点”按钮。
  6. 将您网站的域添加到列表中。您可以使用通配符。

这也可以通过组策略进行设置,因此可以将该设置推送到组织中的每台计算机。请参阅答案here

Firefox使用其自己的设置:network.negotiate-auth.delegation-uris。我敢肯定,也可以通过组策略进行设置。

答案 1 :(得分:0)

您还需要在跨域请求中允许 SupportsCredentials

服务器端(Web API):

true属性上将 SupportsCredentials 属性设置为[EnableCors]

[EnableCors(origins: "http://exampleclient.com", headers: "*", 
methods: "*", SupportsCredentials = true)]