Windows Authentication and Angular 4 application

前端 未结 1 1854
逝去的感伤
逝去的感伤 2020-12-25 08:28

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 u

1条回答
  •  天命终不由人
    2020-12-25 09:25

    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(res))     
          .subscribe(newItem => {
            console.log('Service Subscribe');
            this.auth = newItem;
          })
    
      }
    
      public isUser(): Observable | boolean {
    
        if (!this.auth) {
          return this.http.get(this.baseUrl, this.options)
            .map(res => {
              this.auth = this.extractData(res);
              return this.auth.isUser;
            });
        }
        else {
          return this.auth.isUser;
        }
    
    
      }
    
      private extractData(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 (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

    0 讨论(0)
提交回复
热议问题