Angular .NET核心允许身份验证中间件中的COR

Angular .NET核心允许身份验证中间件中的COR,angular,asp.net-core,authorization,asp.net-core-2.0,Angular,Asp.net Core,Authorization,Asp.net Core 2.0,我目前有一个angular应用程序web客户端,它与我的.net core 2 web api分离。angular应用程序位于localhost:35000,而web api位于localhost:36000。因此,我需要在不同的地方允许CORS请求成功。在Startup.cs中,我将身份验证中间件配置如下: services.AddOpenIddict(options => { // Integrate with EFCore

我目前有一个angular应用程序web客户端,它与我的.net core 2 web api分离。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();
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”)]放在上面。我尝试了多种方法来克服这一问题,包括向我的请求添加指定的头,如在我的web客户端中的以下内容:

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", `*`);
        }
    }
}

关于如何允许这个授权请求通过我的中间件,我已经没有什么想法了。非常感谢您的帮助。

恐怕您不能在
访问控制允许源代码
标题中使用“
*
”通配符。
见:

在响应认证请求时,服务器必须指定 取而代之的是Access Control Allow origin标头值中的origin 无法指定“*”通配符


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