【问题标题】:Angular 5: Post-request & windows authenticationAngular 5:请求后和 Windows 身份验证
【发布时间】:2018-01-24 08:24:38
【问题描述】:

我需要在我的项目中进行 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.

附:当我设置匿名身份验证时,所有 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);
    }
}

【问题讨论】:

    标签: angular asp.net-core-2.0


    【解决方案1】:

    尝试同时启用匿名和 Windows 身份验证,并在您的控制器上设置 [Authorize] 属性。我相信 401 Unauthorized 响应是由启用 CORS 引起的,并且是 preflight 标头不包含身份验证令牌的结果。

    另一种方法是将您的 http POST 更改为“简单请求”,将 Content-Type 值限制为:

    • application/x-www-form-urlencoded
    • 多部分/表单数据
    • 文本/纯文本

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-24
      • 2014-02-05
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多