Angular 5:请求后& Windows身份验证

时间:2017-11-19 12:15:50

标签: angular asp.net-core-2.0

我的项目中需要Windows身份验证,但是后请求被破坏了。 我有一个HttpInterceptor的全局实现。

在我的后端启用了Cors。

services.AddCors(options => options.AddPolicy("AllowAllOrigin", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()))

当我发送get-request时,我在后端检索用户身份,这没关系。 发布请求有什么问题?

OPTIONS http://localhost:56789/api/document/GetDocuments 401 (Unauthorized)
Failed to load http://localhost:56789/api/document/GetDocuments: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

P.S。当我设置匿名身份验证时,所有get / post请求都有效,但我没有用户身份

环境

Angular version: ^5.1.0-beta.1
Angular-cli version: ^1.6.0-beta.2 

Browser:
- [ x ] Chrome (desktop) version 62.0.3202.94

For Tooling issues:
- Node version: XX  8.8.1
- Platform:  Windows 

我的前端服务:

@Injectable()
export class DocumentService {
    controllerName: string = 'document';
    constructor(private http: HttpClient, @Inject('API_URL') private apiUrl: string) { }

    getDocuments(view: AppModels.View.BaseView): rx.Observable<AppModels.Document.DocumentList> {        
        return this.http.post<AppModels.Document.DocumentList>(`${this.apiUrl}/${this.controllerName}/GetDocuments`, view);
    }
}

我的HttpInterceptor:

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest, next: HttpHandler): rx.Observable<HttpEvent> {
        const headers = {};
        const clone = req.clone({ setHeaders: headers, withCredentials: true })
        return next.handle(clone);
    }
}

1 个答案:

答案 0 :(得分:2)

尝试同时启用匿名和Windows身份验证,并在控制器上设置[授权]属性。我认为401 Unauthorized响应是由启用CORS引起的,并且是由于预检头不包含身份验证令牌。

另一种方法是将您的http POST更改为一个简单的请求&#39;它将Content-Type值限制为:

  • 应用程序/ x-WWW窗体-urlencoded
  • multipart / form-data
  • 文本/纯

&#39;简单请求&#39;不要触发CORS预检。有关CORS规范的详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

相关问题