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

11

我正在编写一个Angular 4应用程序,需要从Asp.Net WebApi获取一些数据。我们使用Windows身份验证来保护WebAPI,我想知道如何将用户的Windows身份从我的Angular应用程序传递到WebApi。我找到了一些示例,这些示例涉及将应用程序与MVC应用程序嵌套在一起,但我希望将UI与MVC分开。有没有一种方法可以在不向我的Angular网站添加.net mvc的情况下完成这个任务?


也许这个链接对您有帮助:https://stackoverflow.com/questions/41337145/how-can-i-get-and-post-an-action-using-angular-2-in-mvc/41341743#41341743 - Alex Beugnet
从我所看到的,他们正在使用常规身份验证。我想使用Windows身份验证。 - AlexanderM
@AlexanderM这个问题已经得到了恰当的回答吗?如果是,请标记答案。 - RayLoveless
1个回答

5
当您从Angular向WebAPI发送HTTP请求时,需要使用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 Authentication (HTTP.sys / IISIntegration)”部分:https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
您还必须记得在主机(例如 IIS 或 IISExpress)上启用 Windows 身份验证。
您可能需要启用 CORS,这里的文档很好:https://learn.microsoft.com/en-us/aspnet/core/security/cors
如果出现“preflight checks”错误,则还需要启用匿名访问。

你在回复中提到了"IIS或IISExpress"。你尝试过使用IISExpress并且它可以工作吗?因为我已经尝试过了,但是无法使其工作。 - Dan
是的,两者都可以在Chrome上使用。你尝试过哪些浏览器? - Stephen James
只支持Internet Explorer浏览器。我会尝试Chrome看看是否可行。 - Dan
1
只是提醒一下,如果要使用RequestOptions,你需要导入import { RequestOptions } from '@angular/http'; - XAMlMAX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接