【问题标题】:Windows Authentication and Angular 4 applicationWindows 身份验证和 Angular 4 应用程序
【发布时间】:2018-02-20 03:22:12
【问题描述】:

我正在编写一个需要从 Asp.Net WebApi 获取一些数据的 Angular 4 应用程序。我们正在为 WebAPI 使用 Windows 身份验证,我想知道如何将用户的 Windows 身份从我的 Angular 应用程序传递到 WebApi。我发现了几个涉及将应用程序与 MVC 应用程序嵌套的示例,但我想让 UI 远离 MVC。有没有办法在不将 .net mvc 添加到我的 Angular 网站的情况下做到这一点?

【问题讨论】:

  • 也许该链接会对您有所帮助:stackoverflow.com/questions/41337145/…
  • 据我所知,他们正在使用常规身份验证。我想使用 Windows 身份验证
  • @AlexanderM 这个问题的回答正确吗?如果是,请标记答案。

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


【解决方案1】:

当您将 http 请求从 Angular 发送到您的 WebAPI 时,您需要使用 RequestOptions({ withCredentials=true})

这是一个调用 api 的示例安全服务

@Injectable()
export class SecurityService {
private baseUrl = 'http://localhost:64706/api/security/';
private auth: Auth;
private options = new RequestOptions({ withCredentials: true });

constructor(private http: Http) {
    console.log('Creating Service');

    console.log('Service Pre Http');

    this.http.get(this.baseUrl, this.options)
      .map((res) => this.extractData<Auth>(res))     
      .subscribe(newItem => {
        console.log('Service Subscribe');
        this.auth = newItem;
      })

  }

  public isUser(): Observable<boolean> | boolean {

    if (!this.auth) {
      return this.http.get(this.baseUrl, this.options)
        .map(res => {
          this.auth = this.extractData<Auth>(res);
          return this.auth.isUser;
        });
    }
    else {
      return this.auth.isUser;
    }


  }

  private extractData<T>(res: Response) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    const body = res.json ? res.json() : null;
    return <T>(body || {});
  }

}

这是认证类

export class Auth {
  isAdmin: boolean;
  isUser: boolean;
}

如果您使用的是 .net Core,那么您现在可以在 WebAPI 控制器中访问 this.User.Identity.IsAuthenticated

注意:如果您使用的是 ASP.Net Core 2.0,那么您需要遵循此处的“Windows 身份验证 (HTTP.sys / IISIntegration)”部分 https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

您还必须记住在主机上启用 Windows 身份验证,例如 IIS 或 IISExpress。

您可能需要启用 CORS,这里的文档很好: https://docs.microsoft.com/en-us/aspnet/core/security/cors

如果您在“预检检查”方面遇到错误,那么您还需要启用匿名访问

【讨论】:

  • 您在回复中说“IIS 或 IISExpress”。您是否尝试过 IISExpress 并且它有效?因为我有,但我不能让它工作
  • 是的,两者都使用 Chrome。哪些浏览器试过?
  • 仅限 Internet Explorer。那是需要支持的主要浏览器。我会试试 Chrome 看看它是否有效
  • 仅供参考,使用 RequestOptions 您需要 import { RequestOptions } from '@angular/http';
猜你喜欢
  • 2020-01-06
  • 2018-07-13
  • 2018-06-27
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
相关资源
最近更新 更多