I am writing an Angular 4 application that needs to get some data from Asp.Net WebApi. We are using windows authentication for the WebAPI and I am wondering how I can pass user's windows identity from my Angular Application to WebApi. I've found couple examples that are involving nesting your application with MVC application but I would to keep UI away from MVC. Is there a way to do it without adding .net mvc to my Angular website?
When you send your http request from Angular to your WebAPI you need to use RequestOptions({ withCredentials=true})
Here's a sample security service that calls an 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 || {});
}
}
This is the auth class
export class Auth {
isAdmin: boolean;
isUser: boolean;
}
If you are using .net Core then in your WebAPI Controller you can now access
this.User.Identity.IsAuthenticated
NB: If you are using ASP.Net Core 2.0 then you need to follow the "Windows Authentication (HTTP.sys / IISIntegration)" section here https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
You must also remember to enable Windows Authentication on the host e.g IIS or IISExpress.
You will likely need to enable CORS the documentation here is good: https://docs.microsoft.com/en-us/aspnet/core/security/cors
If you get errors around "preflight checks" then you will also need to enable Anonymous Access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With