2017-09-11 19 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

相关问题