2017-09-11 64 views
5

我正在編寫一個需要從Asp.Net WebApi獲取一些數據的Angular 4應用程序。我們正在爲WebAPI使用Windows身份驗證,我想知道如何將用戶的Windows身份從我的Angular Application傳遞到WebApi。我發現了一些涉及將應用程序與MVC應用程序嵌套的示例,但是我會讓UI遠離MVC。有沒有辦法做到這一點,而無需添加.net mvc到我的Angular網站?Windows身份驗證和Angular 4應用程序

+0

也許該鏈接會幫助你的錯誤 https://docs.microsoft.com/en-us/aspnet/core/security/cors

你可能需要在這裏啓用CORS的文檔是好的:https://stackoverflow.com/questions/41337145/how-can-i-get-and-post-an-action-using-angular-2-in-mvc/41341743#41341743 –

+0

從我能看到的是他們正在使用常規認證。我想使用Windows身份驗證 – AlexanderM

+0

@AlexanderM正確回答了這個問題嗎?如果是這樣,請標記答案。 – RayLoveless

回答

2

當您從角發送的HTTP請求發送到您的WebAPI你需要使用 RequestOptions({withCredentials =真})

下面是調用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的核心然後在您的WebAPI控制器您現在可以訪問 this.User.Identity.IsAuthenticated

注意:如果您正在使用ASP.Net 2.0的核心,那麼你需要遵循 「Windows身份驗證(HTTP.sys中/ IISIntegration)」 這裏段 https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

你還必須記住啓用Windows主機上的身份驗證,例如IIS或IISExpress。如果你身邊「預檢」,那麼你也將需要啓用匿名訪問

+0

你在回覆「IIS或IISExpress」中說過。你有沒有嘗試IISExpress,它的工作?因爲我有,我不能使它工作 – Dan

+0

是的,兩者都使用Chrome。哪些瀏覽器嘗試過? –

+0

只有Internet Explorer。這是需要支持的主要瀏覽器。我會嘗試Chrome來查看它是否有效 – Dan