簡體   English   中英

Windows身份驗證和Angular 4應用程序

[英]Windows Authentication and Angular 4 application

我正在編寫一個Angular 4應用程序,該應用程序需要從Asp.Net WebApi獲取一些數據。 我們正在對WebAPI使用Windows身份驗證,我想知道如何將用戶的Windows身份從我的Angular應用程序傳遞給WebApi。 我找到了一些示例,這些示例涉及將您的應用程序與MVC應用程序嵌套在一起,但我希望UI遠離MVC。 有沒有一種方法可以不將.net mvc添加到我的Angular網站中?

當您將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 || {});
  }

}

這是auth類

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/zh-cn/aspnet/core/migration/ 1x到2x / identity-2x

您還必須記住要在主機上啟用Windows身份驗證,例如IIS或IISExpress。

您可能需要啟用CORS,這里的文檔很好: https : //docs.microsoft.com/zh-cn/aspnet/core/security/cors

如果您在“預檢檢查”中遇到錯誤,則還需要啟用匿名訪問

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM