我正在编写一个Angular 4应用程序,需要从Asp.Net WebApi获取一些数据。我们正在为WebAPI使用Windows身份验证,我想知道如何将用户的Windows身份从我的Angular应用程序传递到WebApi。我发现了几个涉及使用MVC应用程序嵌套应用程序的示例,但我希望UI远离MVC。有没有办法在不将.net mvc添加到我的Angular网站的情况下做到这一点?
答案 0 :(得分: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 || {});
}
}
这是auth类
export class Auth {
isAdmin: boolean;
isUser: boolean;
}
如果您使用的是.net Core,那么您现在可以访问WebAPI控制器
this.User.Identity.IsAuthenticated
NB:如果您使用的是ASP.Net Core 2.0,那么您需要遵循&#34; Windows身份验证(HTTP.sys / IISIntegration)&#34;这里的部分 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
如果你得到错误&#34;预检检查&#34;那么你还需要启用匿名访问