【问题标题】:.NET Core allow CORS in authentication middleware.NET Core 允许在身份验证中间件中使用 CORS
【发布时间】:2018-06-09 11:08:45
【问题描述】:

我目前有一个独立于我的 .net core 2 web api 的 angular 应用程序 web 客户端。 Angular 应用程序托管在 localhost:35000,而 Web api 托管在 localhost:36000。因此,有很多地方我需要允许 CORS 以使请求成功。在Startup.cs中,我的认证中间件配置如下:

services.AddOpenIddict(options =>
            {
                // Integrate with EFCore
                options.AddEntityFrameworkCoreStores<MylestoneIdentityContext>();
                // Use Json Web Tokens (JWT)
                options.UseJsonWebTokens();
                // Set a custom token endpoint (default is /connect/token)
                options.EnableTokenEndpoint(Configuration["Authentication:OpenIddict:TokenEndPoint"]);
                // Set a custom auth endpoint (default is /connect/authorize)
                options.EnableAuthorizationEndpoint(Configuration["Authentication:OpenIddict:AuthorizationEndPoint"]);
                // Allow client applications to use the grant_type=password flow.
                options.AllowPasswordFlow();
                // Enable support for both authorization & implicit flows
                options.AllowAuthorizationCodeFlow();
                options.AllowImplicitFlow();
                // Allow the client to refresh tokens.
                options.AllowRefreshTokenFlow();
                // Disable the HTTPS requirement (not recommended in production)
                options.DisableHttpsRequirement();
                // Register a new ephemeral key for development.
                // We will register a X.509 certificate in production.
                options.AddEphemeralSigningKey();
            });
...
app.UseAuthentication();

并且我已允许对我的应用程序的 CORS 请求如下:

services.AddCors(options =>
            {
                options.AddPolicy("AllowCors",
                    builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });
...
app.UseCors("AllowCors");
...
//also put [EnableCors("AllowCors")] on each controller class declaration

我可以访问服务器并成功注册用户帐户,但是尝试登录时,我仍然在浏览器中收到错误消息:

Failed to load http://localhost:36000/api/connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:35000' is therefore not allowed access. The response had HTTP status code 500.

我认为这可能是由于 /api/connect/token 没有实际的控制器类,我可以将注释 [EnableCors("AllowCors")] 放在上面。我尝试了多种方法来克服这个问题,包括在我的网络客户端中将指定的标头添加到我的请求中,如下所示:

return this.http.post(
            url,
            this.toUrlEncodedString(data),
            new RequestOptions({
                headers: new Headers({
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Access-Control-Allow-Origin": "*"
                })
            }))

命中以下有角度的 http 服务包装器:

post(url, data, opts = {}) {
        this.configureAuth(opts);
        return this.http.post(url, data, opts);
}

configureAuth(opts: any) {
    var i = localStorage.getItem(this.authKey);
    if (i != null) {
        var auth = JSON.parse(i);
        console.log(auth);
        if (auth.access_token != null) {
            if (opts.headers == null) {
                opts.headers = new Headers();
            }
            opts.headers.set("Authorization", `Bearer ${auth.access_token}`);
            opts.headers.set("Access-Control-Allow-Origin", `*`);
        }
    }
}

关于如何允许此授权请求通过我的中间件,我已经没有想法了。感谢所有帮助。

【问题讨论】:

  • 可能不是唯一的问题,但我认为您还需要将 .AllowCredentials() 添加到您的 CORS 策略中,否则它不会接受您在客户端设置的授权标头。哦,在调用 app.UseMvc() 之前,请仔细检查您是否设置了 cors 政策。

标签: angular asp.net-core authorization asp.net-core-2.0


【解决方案1】:

恐怕您不能在Access-Control-Allow-Origin 标头中使用“*”通配符。
MDN: Credentialed requests and wildcards:

在响应凭据请求时,服务器必须指定一个 来源在 Access-Control-Allow-Origin 标头的值中,而不是 指定“*”通配符。

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2022-01-25
    • 2021-10-16
    • 2019-05-19
    • 2019-06-24
    相关资源
    最近更新 更多