Windows Authentication and Angular 4 application

我与影子孤独终老i 提交于 2019-11-30 00:47:43

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!