0

当我尝试访问 Web.API 端点时出现 CORS 错误。我有一个 agular 应用程序,用于身份验证的身份服务器和用于数据管理的 web.api。

API 在端口:52177 上运行,Angular APP 在:52178 上运行,IS4 在:4165 上运行。

这是IS配置

new Client {
                    RequireConsent = false,
                    ClientId = "angular_spa",
                    ClientName = "Angular SPA",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowedScopes = { "openid", "profile" },
                    RedirectUris =
                    {
                        "http://localhost:52178/auth-callback"
                    },
                    PostLogoutRedirectUris = {"http://localhost:52178/?logout=true"},
                    AllowedCorsOrigins =
                    {
                        "http://localhost:52178",
                        "http://localhost:52177"
                    },
                    AllowAccessTokensViaBrowser = true,
                    AccessTokenLifetime = 3600,
                    IdentityTokenLifetime = 3600
                }

角应用

 return {
            authority: 'http://localhost:4165',
            client_id: 'angular_spa',
            redirect_uri: 'http://localhost:52178/auth-callback',
            post_logout_redirect_uri: 'http://localhost:52178/?logout=true',
            response_type: "id_token token",
            scope: "openid profile",
            filterProtocolClaims: true,
            loadUserInfo: true,
            automaticSilentRenew: true

        };

API

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:4165",
                RequiredScopes = new[] { "openid", "profile" },
                PreserveAccessToken = true,

                NameClaimType = System.Security.Claims.ClaimTypes.Name,
                RoleClaimType = System.Security.Claims.ClaimTypes.Role
            });

这是我得到的错误

Access to XMLHttpRequest at 'http://localhost:52177/api/books?length=0&pageIndex=0&pageSize=10' from origin 'http://localhost:52178' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我将 :52178 和 :52177 Origins 添加到 IS4 的客户端配置中,但它仍然不起作用。有什么我想念的想法吗?

4

1 回答 1

1

正如@mackie 提到的,API 本身需要启用 CORS。我必须安装 Install-Package Microsoft.AspNet.WebApi.Cors 并在 WebApiConfig 为我的客户端应用程序启用 CORS

var cors = new EnableCorsAttribute("http://localhost:52178", "*", "*");
config.EnableCors(cors);
于 2019-07-31T21:58:43.970 回答