Ale*_*erM 10 windows-authentication asp.net-web-api angular
我正在编写一个Angular 4应用程序,需要从Asp.Net WebApi获取一些数据.我们正在为WebAPI使用Windows身份验证,我想知道如何将用户的Windows身份从我的Angular应用程序传递到WebApi.我发现了几个涉及使用MVC应用程序嵌套应用程序的示例,但我希望UI远离MVC.有没有办法在不将.net mvc添加到我的Angular网站的情况下做到这一点?
小智 5
当您将Angular的http请求发送到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 || {});
}
}
Run Code Online (Sandbox Code Playgroud)
这是auth类
export class Auth {
isAdmin: boolean;
isUser: boolean;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是.net Core,那么您现在可以访问WebAPI控制器
this.User.Identity.IsAuthenticated
注意:如果您使用的是ASP.Net Core 2.0,则需要按照"Windows身份验证(HTTP.sys/IISIntegration)"部分进行操作 https://docs.microsoft.com/en-us/aspnet/core/migration/ 1X至2X /同一性-2X
您还必须记住在主机上启用Windows身份验证,例如IIS或IISExpress.
你可能需要启用CORS这里的文档是好的:https: //docs.microsoft.com/en-us/aspnet/core/security/cors
如果您在"预检检查"中遇到错误,那么您还需要启用匿名访问
| 归档时间: |
|
| 查看次数: |
15640 次 |
| 最近记录: |