当前位置: 首页 > 知识库问答 >
问题:

Spring SAML:更新元数据提供程序不会更新使用的签名证书

陆栋
2023-03-14

我最近实现了一个Spring SAML解决方案,该解决方案允许客户向服务注册其IdP元数据,并使用其SAML身份验证来访问我的SP。

IdP 元数据存储为数据库条目,作为自定义 AbstractReloadingMetadataProvider 实现的一部分,如下所示:

public class DbIdpMetadataProvider extends AbstractReloadingMetadataProvider {
...
  @Override
  protected byte[] fetchMetadata() throws MetadataProviderException {
  IdpProviderData provider  = null; // DAO of IdP metadata in DB

  try {

    log.info("Attempting to retrieve DB provider data for entity: " + entityId);

    provider = dbService.getIdpByEntityId(entityId);

    // verify that we have a provider
    if ( null != provider) {

      // get last update time recorded in DB
      DateTime lastUpdate = getLastUpdate();

      log.info("Performing refresh of Metadata Provider XML by reading from database");


      String metadataBody = provider.getMetadataBody();
      emitChangeEvent();
      return metadataBody.getBytes();
    }


    // if no provider, throw an exception as this metadata provider instance is invalid
    else {
      log.error("IdP Provider could not be found for EntityId: " + entityId );
      throw new MetadataProviderException("Metadata could not be found for String entity: " + entityId);
    }

  }
  catch(Exception e) {
    log.error("Failed to query database for provider entity: " + entityId);
    throw new MetadataProviderException("Failed to query database for provider entity: " + entityId, e);
  }

}

当元数据更新时,我将元数据XML保存到数据库中,并从CachingMetadataManager中删除元数据提供程序的前一个实例。然后,我将证书从元数据导入到本地密钥库中,并将一个新的元数据提供者实例添加到CachingMetadataManager:

@Autowired
private MetadataManager       metadataManager;

...

/**
 * Update our existing IdP metadata provider with new XML and other information
 */
public void updateIdpMetadata(IdPRegistrationData _data) throws RequiredDataException, NotFoundException, SystemException {
  IdpProviderData           provider;
  XMLObject                 xml;
  String                    metadataXml;
  EntityDescriptor          entity;
  String                    entityId;

  try {

    // validation
    validateIdpRegistrationData(_data);

    //ensure our top level DOM element is the IDPSSO entity descriptor, removing all other metadata
    xml         = parseMetadataXml(_data.getMetadataXml());
    entity      = getIDPSSOParentEntityDescriptor(xml);
    entityId    = entity.getEntityID();
    metadataXml = serialize(entity);

    // get our provider Data
    provider    = getIdpByAccountSysid(_data.getAccountSysid());

    if ( null == provider) {
      throw new NotFoundException(NotFoundExceptionType.ACCOUNT);
    }

    // update our provider
    provider.setEntityId(entityId);
    provider.setMetadataBody(metadataXml);

    // save data in database
    metadataStoreDao.saveAndFlush(provider);
    keystoreMgr.importMetadataCertificates(xml, provider.getUrlContext());

    // remove existing provider from metadata store
    removeDelegateFromManager(entityId);

    // reintroduce delegate to manager
    loadIdpMetadata(provider);

  }
  catch(NotFoundException e) {
    log.error("No previous version of IDP registration metadata found to update.",e);
    throw (e);
  }
  catch (MetadataProviderException e){
    log.error("Failed to update Keystore and Signing algorithm of IdP Metadata.",e);
    throw new SystemException("Failed to update certificates.");
  }
  catch(RequiredDataException e) {
    log.error("Missing required data for update.",e);
    throw(e);
  }

}

/**
 * Remove the metadata provider from our manager
 */
private void removeDelegateFromManager( String _entityId ) throws MetadataProviderException {
  ExtendedMetadataDelegate  delegate;
  DbIdpMetadataProvider     provider;

  delegate  = findMetadataDelegate(_entityId);

  if( null == delegate){
    log.error("Failed to find Delegate in metadata manager for Entity ID: " + _entityId );
    return;
  }

  metadataManager.removeMetadataProvider(delegate);
  provider = (DbIdpMetadataProvider)delegate.getDelegate();
  provider.destroy();
  metadataManager.setRefreshRequired(true);
  metadataManager.refreshMetadata();

}    

/**
 * load our provider data to a metadata provider object
 */
private void loadIdpMetadata(IdpProviderData _providerData) throws MetadataProviderException {
  DbIdpMetadataProvider idpProvider;

  // initialize our IdP provider
  idpProvider     = new DbIdpMetadataProvider(_providerData);
  idpProvider.setParserPool(parser);
  addIdpToMetadataManager(idpProvider);

}

/**
 * Add the metadata provider to our cache
 */
private void addIdpToMetadataManager(DbIdpMetadataProvider _provider) throws MetadataProviderException {
  ExtendedMetadataDelegate  delegate;
  ExtendedMetadata          extMeta = new ExtendedMetadata();

  // initialize our provider
  _provider.initialize();

  extMeta     = createExtendedMetadata(_provider);

  delegate    = new ExtendedMetadataDelegate(_provider, extMeta);
  delegate.setMetadataTrustCheck(false);
  delegate.initialize();

  metadataManager.addMetadataProvider(delegate);
  metadataManager.setRefreshRequired(true);
  metadataManager.refreshMetadata();
}

问题在于,刷新数据库条目时,不会应用IdP元数据中元素中定义的新签名证书。

打印元数据XML时,我可以看到新证书:

  <!--  new signing key  -->
  <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
    <KeyDescriptor use="encryption">
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <X509Data>
          <X509Certificate>MIIC4jCCAcqgAwIBAgIQafZAY7...</X509Certificate>
        </X509Data>
      </KeyInfo>
    </KeyDescriptor>
    <KeyDescriptor use="signing">
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <X509Data>
          <X509Certificate>MIIC3DCCAcSgAwIBAgIQeny6jM...</X509Certificate>
        </X509Data>
      </KeyInfo>
    </KeyDescriptor>
    <KeyDescriptor use="signing">
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <X509Data>
          <X509Certificate>MIIC3DCCAcSgAwIBAgIQRtno3W...</X509Certificate>
        </X509Data>
      </KeyInfo>

我在SP启动登录时收到来自我的IdP的SUCCESS SAML响应:

<?xml version="1.0" encoding="UTF-8"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" Destination="https://{my-domain}:443/eas-saml/saml/SSO" ID="_0d023fb8-bf24-4b78-b690-c9b53df4db72" InResponseTo="a22h6bb0gf2e8f314e00316b198ddg1" IssueInstant="2018-10-17T18:31:47.332Z" Version="2.0">
   <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://{my-domain}/adfs/services/trust</Issuer>
   <samlp:Status>
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
   </samlp:Status>
   <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_317d062d-247e-4405-9dd8-0ef3d032bf3f" IssueInstant="2018-10-17T18:31:47.332Z" Version="2.0">
      <Issuer>http://{my-domain}/adfs/services/trust</Issuer>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
         <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
            <ds:Reference URI="#_8049000b-6e76-416c-84aa-180d61ca359a">
               <ds:Transforms>
                  <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                  <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
               </ds:Transforms>
               <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
               <ds:DigestValue>x/PKyqXDECmE2IBNiZ0pqet3HqQYgDwlbeo1Vb3gXD8=</ds:DigestValue>
            </ds:Reference>
         </ds:SignedInfo>
         <ds:SignatureValue>UvhpsDE7XT1uvqGbA+IZ2sC9t8x0i42/P7tdNXO...</ds:SignatureValue>
         <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <ds:X509Data>
               <ds:X509Certificate>MIIC3DCCAcSgAwIBAgIQRtno3W...</ds:X509Certificate>
            </ds:X509Data>
         </KeyInfo>
      </ds:Signature>
      <Subject>
         <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">userId</NameID>
         <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
            <SubjectConfirmationData InResponseTo="a22h6bb0gf2e8f314e00316b198ddg1" NotOnOrAfter="2018-10-17T18:36:47.332Z" Recipient="https://{my-domain}:443/eas-saml/saml/SSO"/>
         </SubjectConfirmation>
      </Subject>
      <Conditions NotBefore="2018-10-17T18:31:47.327Z" NotOnOrAfter="2018-10-17T18:33:47.327Z">
         <AudienceRestriction>
            <Audience>https://{my-domain}/eas-saml</Audience>
         </AudienceRestriction>
      </Conditions>
      <AttributeStatement>
         <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn">
            <AttributeValue>userId</AttributeValue>
         </Attribute>
         <Attribute Name="http://E-Mail-Addresses">
            <AttributeValue>user@domain.com</AttributeValue>
         </Attribute>
      </AttributeStatement>
      <AuthnStatement AuthnInstant="2018-10-17T18:31:47.233Z" SessionIndex="_317d062d-247e-4405-9dd8-0ef3d032bf3f">
         <AuthnContext>
            <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
         </AuthnContext>
      </AuthnStatement>
   </Assertion>
</samlp:Response>

其中,作为日志输出显示具有以下堆栈跟踪的故障:

    2018-10-17 18:31:47 INFO  SAMLDefaultLogger:129 - AuthNResponse;FAILURE;172.17.0.1;https://{my-domain}/eas-saml;http://{my-domain}/adfs/services/trust;;;org.opensaml.common.SAMLException: Response doesn't have any valid assertion which would pass subject validation
      at org.springframework.security.saml.websso.WebSSOProfileConsumerImpl.processAuthenticationResponse(WebSSOProfileConsumerImpl.java:229)
      at org.springframework.security.saml.SAMLAuthenticationProvider.authenticate(SAMLAuthenticationProvider.java:88)
      at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
      at org.springframework.security.saml.SAMLProcessingFilter.attemptAuthentication(SAMLProcessingFilter.java:92)
      at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    Caused by: org.opensaml.xml.validation.ValidationException: Signature is not trusted or invalid
      at org.springframework.security.saml.websso.AbstractProfileBase.verifySignature(AbstractProfileBase.java:272)
      at org.springframework.security.saml.websso.WebSSOProfileConsumerImpl.verifyAssertionSignature(WebSSOProfileConsumerImpl.java:419)
      at org.springframework.security.saml.websso.WebSSOProfileConsumerImpl.verifyAssertion(WebSSOProfileConsumerImpl.java:292)
      at org.springframework.security.saml.websso.WebSSOProfileConsumerImpl.processAuthenticationResponse(WebSSOProfileConsumerImpl.java:214)
      ... 39 more

如果重新启动服务,签名将被识别,响应将被成功处理。

有人知道我做错了什么吗?元数据管理器的刷新是否足以允许使用新证书?还是我错过了一步?

共有1个答案

劳韬
2023-03-14

我在另一个帖子里找到了答案

由于我当前使用的是 XML 配置文件,因此我修改了安全上下文 XML 以设置凭据解析程序,如下所示:

<!-- Provider of default SAML Context -->
<bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderImpl">
  <property name="metadataResolver">
            <bean class="com.mydomain.CustomMetadataCredentialResolver">
                <constructor-arg index="0" ref="metadata" />
                <constructor-arg index="1" ref="keyManager" />
                <property name="useXmlMetadata" value="true" />
            </bean>
  </property> 
</bean>

然后我创建了一个扩展org.springframework.security.saml.trust.MetadataCredentialResolver的类

现在,我只需覆盖cacheCredentials方法:

@Component
public class CustomMetadataCredentialResolver extends MetadataCredentialResolver {

  public CustomMetadataCredentialResolver(MetadataManager metadataProvider, KeyManager keyManager) {
    super(metadataProvider, keyManager);
  }

  @Override
  protected void cacheCredentials( MetadataCacheKey cacheKey, Collection<Credential> credentials ) {
    //no-op
  }
}

我可能会清理它以清除命令上的缓存,而不是从不缓存凭据,但现在它可以工作。

 类似资料:
  • 我只是尝试在google play核心库API提供的应用程序更新服务中实现。 在发布了较新版本的应用程序后进行了内部测试。我在play store中获得了更新版本的应用程序,如图1所示。但是,我无法看到“更新”按钮在同一页上,正如屏幕上的-2。另外,应用程序是禁用的,以更新根据代码的实现。请帮我处理这件事。谢谢。屏幕肖像1屏幕肖像2 ` }`

  • 我目前正在重构遗留代码,以使用Android架构组件,并在一种存储库模式中设置一个房间数据库和截取请求。因此,表示层/域层要求存储库获取LiveData对象进行观察,或告诉他与服务器同步,然后删除旧的db条目,并从服务器中重新提取所有当前条目。 我已经写了同步部分的测试,所以我确信,对象被正确地获取并插入到数据库中。但是当写一个测试来观察db表的条目时(并测试对象是否被正确保存,以及在将它们放入d

  • 我正在更新APIendpoint中的数据。正如我所说,我使用表单请求验证将验证与控制器分开。 这适用于存储请求。 但是,当我试图更新下面提到的单个数据时,响应返回以下响应数据。 因为,数据已经存储在数据库中。当我发送更新数据的请求时...应该返回更新的数据。但是,它不返回。 需要帮助来解决这个问题。 正文中的JSON数据: 当前响应: 问题要求: 更新:

  • 问题内容: 我正在更新我的Kubernetes容器: 以下是我的service.yaml: 以下是我的deployment.yaml: 第一次可以正常运行,但是在随后的运行中,我的广告连播没有得到更新。 我已经在https://github.com/kubernetes/kubernetes/issues/33664上阅读了建议的解决方法,该方法是: 我能够运行上面的命令,但是它没有为我解决问题。

  • 问题内容: 我正在尝试使用array 更新 ng-grid。我 这里 有个小伙伴。 添加按钮添加新行。更新按钮更新阵列中的最后一项。 选择一行并按更新按钮。没发生什么事。 按添加按钮。现在,UI将使用新元素&以及以前更新的元素进行更新。 相同的行为一次又一次地重复。 我试过了。我得到: “错误:$ apply已经在进行中” 我什至尝试通过将块放置在呼叫中来进行尝试。同样是同样的错误! 任何指针!

  • 我正在将Keycloak作为身份代理运行,并配置了一个身份提供程序。 当具有来自我的IdP的有效令牌的用户第一次访问我的应用程序时,该用户将使用来自该令牌的信息在Keycloak中创建。这包括电子邮件、用户名、名字和名字。然后Keycloak发出带有用户信息的令牌。 当同一用户随后登录时,将根据Keycloak数据库中的用户信息精心编制Keycloak令牌。 我的问题是这样的:如果用户在IdP更改