ADAL不会传递CORS标头

时间:2018-08-07 20:56:27

标签: angular cors adfs adal

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

实际失败消息为“无法加载extractd-adfs-url:对预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。因此不允许访问“ null”。“

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'
      }
    };

指向授权端点的角度服务:

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;
  }

API Cors配置:

<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终结点上不具有authorize属性,这些终结点仍在使用上面使用的CORS标头。我的假设是设置ADFS连接时缺少某个设置,但是我找不到它。

任何有关如何解决浏览器的CORS问题的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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