ADAL 未通过 CORS header

ADAL not passing over CORS header

我创建了一个 angular 5 应用程序,它使用 adal-angular5 包通过 ADFS 2016 登录用户。angular 应用程序还连接到一个 API 从中检索数据并将数据发送到相应的数据库。 angular 应用程序位于 https://localhost:4200, while the api is located at https://localhost:44377。在 api 端点上添加授权属性以验证从应用程序传递的 id_token 后,我开始在 Chrome 上收到 CORS 故障。

实际的失败信息是"Failed to load extracted-adfs-url: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

adal5Service 的配置:

const config = {
      instance: 'https://my.adfs.server.url/',
      tenant: 'adfs',
      clientId: 'E1CF1107-xxxx-xxxx-xxxx-36052DD2C714',
      redirectUrl: 'https://localhost:4200/',
      postLogoutRedirectUri: 'https://localhost:4200/',
      endpoints: {
        'https://localhost:44377/api/price' : 'E1CF1107-xxxx-xxxx-xxxx-36052DD2C714'
      }
    };

指向授权端点的angular服务:

private headers = this.getHeaders();

getPriceItemDetails(): Observable<PriceItemDetail[]> {
    const url = `${this.domainRoute}/${this.baseUrl}`;
    return this.httpClient
      .get<PriceItemDetail[]>(url, { headers: this.headers })
      .catch(err => this.handleError(err));
  }

  private getHeaders() {
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('Accept', 'application/json');
    headers = headers.append('Access-Control-Allow-Origin', this.domainRoute);
    headers = headers.append('Access-Control-Allow-Headers', 'Content-Type, Accept');
    headers = headers.append('Authorization', `Bearer ${this.service.userInfo.token}`);
    return headers;
  }

APICors配置:

<add key="cors:allowOrigins" value="https://localhost:4200"/>

var origins = ConfigurationManager.AppSettings["cors:allowOrigins"];
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET,POST,OPTIONS");
config.EnableCors(cors);

API端点:

[RoutePrefix("api/price")]
public class PriceController : ApiController
{
    private RepoPrice _repoPrice;

    public PriceController()
    {
        _repoPrice = new RepoPrice();
    }

    [Route()]
    [HttpGet]
    [Authorize]
    [ResponseType(typeof(IEnumerable<PriceItemDetail>))]
    public IHttpActionResult GetPriceItem()
    {
        // redacted code
    }
}

Angular 的 ADFS 设置:

RedirectUri                          : {https://localhost:4200/}
Name                                 : Angular App
Description                          :
ClientId                             : E1CF1107-xxxx-xxxx-xxxx-36052DD2C714
BuiltIn                              : False
Enabled                              : True
ClientType                           : Public
ADUserPrincipalName                  :
ClientSecret                         :
LogoutUri                            :
JWTSigningCertificateRevocationCheck : None
JWTSigningKeys                       : {}
JWKSUri                              :

API 的 ADFS 设置:

AllowedAuthenticationClassReferences : {}
EncryptionCertificateRevocationCheck : CheckChainExcludeRoot
PublishedThroughProxy                : False
SigningCertificateRevocationCheck    : CheckChainExcludeRoot
WSFedEndpoint                        : https://localhost:44377/
AdditionalWSFedEndpoint              : {}
ClaimsProviderName                   : {}
ClaimsAccepted                       : {}
EncryptClaims                        : True
Enabled                              : True
EncryptionCertificate                :
Identifier                           : {https://localhost:44377}
NotBeforeSkew                        : 0
EnableJWT                            : False
AlwaysRequireAuthentication          : False
Notes                                :
OrganizationInfo                     :
ProxyEndpointMappings                : {}
ProxyTrustedEndpoints                : {}
ProtocolProfile                      : WsFed-SAML
RequestSigningCertificate            : {}
EncryptedNameIdRequired              : False
SignedSamlRequestsRequired           : False
SamlEndpoints                        : {}
SamlResponseSignature                : AssertionOnly
SignatureAlgorithm                   : http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
TokenLifetime                        : 0
AllowedClientTypes                   : Public, Confidential
IssueOAuthRefreshTokensTo            : AllDevices
RefreshTokenProtectionEnabled        : True
RequestMFAFromClaimsProviders        : False
ScopeGroupId                         :
Name                                 : localhost:44377
AutoUpdateEnabled                    : False
MonitoringEnabled                    : False
MetadataUrl                          :
ConflictWithPublishedPolicy          : False
IssuanceAuthorizationRules           : @RuleTemplate = "AllowAllAuthzRule"
                                        => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit",                                        Value = "true");


IssuanceTransformRules               : @RuleTemplate = "LdapClaims"
                                       @RuleName = "AD-UPN"
                                       c:[Type ==
                                       "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname",                                        Issuer == "AD AUTHORITY"]
                                        => issue(store = "Active Directory", types =
                                       ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query =
                                       ";userPrincipalName;{0}", param = c.Value);


DelegationAuthorizationRules         :
LastPublishedPolicyCheckSuccessful   :
LastUpdateTime                       : 12/31/1899 6:00:00 PM
LastMonitoredTime                    : 12/31/1899 6:00:00 PM
ImpersonationAuthorizationRules      :
AdditionalAuthenticationRules        :
AccessControlPolicyName              :
AccessControlPolicyParameters        :
ResultantPolicy                      :

我有其他端点在 API 端点上没有授权属性,它们仍在使用上面使用的 CORS headers。我的假设是在设置 ADFS 连接时遗漏了一个设置,但我找不到它可能是什么。

非常感谢任何有关如何解决我的浏览器 CORS 问题的帮助。

我的端点参数有误。我将端点设置为 api 中的特定端点,而不仅仅是通用 api 端点。设置端点的正确方法是

endpoints: {
    'https://localhost:44377/api/' : 'E1CF1107-xxxx-xxxx-xxxx-36052DD2C714'
  }