org.openid4java.association.Association Java Examples

The following examples show how to use org.openid4java.association.Association. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenIDServerAssociationStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Super will generate the association and it will be persisted by the DAO.
 *
 * @param type     association type defined in the OpenID 2.0
 * @param expiryIn date
 * @return <code>Association</code>
 */
@Override
public Association generate(String type, int expiryIn)
        throws AssociationException {
    String handle = storeId + timestamp + "-" + getCounter();
    final Association association = Association.generate(type, handle, expiryIn);
    cache.addToCache(association);
    // Asynchronous write to database
    Thread thread = new Thread() {
        @Override
        public void run() {
            if(log.isDebugEnabled()) {
                log.debug("Storing association " + association.getHandle() + " in the database.");
            }
            dao.storeAssociation(association);
        }
    };
    thread.start();
    return association;
}
 
Example #2
Source File: AuthRequest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
protected AuthRequest(String claimedId, String delegate, boolean compatibility,
                      String returnToUrl, String handle, String realm,
                      RealmVerifier verifier)
{
    if (! compatibility)
    {
        set("openid.ns", OPENID2_NS);
        setClaimed(claimedId);
    }

    setIdentity(delegate);

    if ( returnToUrl != null ) setReturnTo(returnToUrl);
    if ( realm != null ) setRealm(realm);

    if (! Association.FAILED_ASSOC_HANDLE.equals(handle)) setHandle(handle);
    setImmediate(false);

    _realmVerifier = verifier;
}
 
Example #3
Source File: AuthSuccess.java    From openid4java with Apache License 2.0 6 votes vote down vote up
protected AuthSuccess(String opEndpoint, String claimedId, String delegate,
                      boolean compatibility,
                      String returnTo, String nonce,
                      String invalidateHandle, Association assoc,
                      boolean signNow)
        throws AssociationException
{
    if (! compatibility)
    {
        set("openid.ns", OPENID2_NS);
        setOpEndpoint(opEndpoint);
        setClaimed(claimedId);
        setNonce(nonce);
    }

    set("openid.mode", MODE_IDRES);

    setIdentity(delegate);
    setReturnTo(returnTo);
    if (invalidateHandle != null) setInvalidateHandle(invalidateHandle);
    setHandle(assoc.getHandle());

    buildSignedList();
    setSignature(signNow ? assoc.sign(getSignedText()) : "");
}
 
Example #4
Source File: PrivateAssociationCryptoStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
    public Association load(String handle) {

        if(IdentityUtil.isBlank(handle)){
            throw new IllegalArgumentException("Handle is empty");
        }
        if(log.isDebugEnabled()){
            log.debug("Inside load(); handle : " + handle);
        }
        String timeStamp = handle.substring((Integer.toString(storeId)).length(), handle.indexOf("-"));
        Date expireDate = new Date(Long.parseLong(timeStamp)+ this.expireIn);
        if(log.isDebugEnabled()){
            log.debug("Calculated Expiry Time : " + expireDate.getTime());
        }
//        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
//        PBEKeySpec spec = new PBEKeySpec(serverKey.toCharArray(), handle.getBytes(), 1, 256);
//        SecretKey secretKey = factory.generateSecret(spec);

        return Association.createHmacSha256(handle, (serverKey + handle).getBytes(), expireDate);
    }
 
Example #5
Source File: PrivateAssociationReplicationStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public Association load(String handle) {
    // get association using map
    Association association = OpenIDAssociationReplicationManager.getPersistenceManager().getAssociation(handle);

    // no association found for the given handle
    if (association == null) {
        log.warn("Association " + handle + " not found in the map.");
        return null;
    }

    // if the association is expired
    if (association.hasExpired()) {
        log.warn("Association is expired for handle " + handle);
        remove(handle); // remove from map
        return null;

    }

    return association;
}
 
Example #6
Source File: OpenIdServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyExpiredAssociationGetResponse() {
    request.addParameter("openid.assoc_handle", "test");
    openIdService = OpenIdService.createServiceFrom(request, null);
    Association association = null;
    try {
        association = Association.generate(Association.TYPE_HMAC_SHA1, "test", 2);
    } catch (final Exception e) {
        fail("Could not generate association");
    }
    when(sharedAssociations.load("test")).thenReturn(association);
    synchronized (this) {
        try {
            this.wait(3000);
        } catch (final InterruptedException ie) {
            fail("Could not wait long enough to check association expiry date");
        }
    }
    final Response response = this.openIdService.getResponse("test");
    request.removeParameter("openid.assoc_handle");
    assertNotNull(response);

    assertEquals(1, response.getAttributes().size());
    assertEquals("cancel", response.getAttributes().get("openid.mode"));
}
 
Example #7
Source File: InMemoryConsumerAssociationStore.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public synchronized Association load(String opUrl)
{
    removeExpired();

    Association latest = null;

    if (_opMap.containsKey(opUrl))
    {
        Map handleMap = (Map) _opMap.get(opUrl);

        Iterator handles = handleMap.keySet().iterator();
        while (handles.hasNext())
        {
            String handle = (String) handles.next();

            Association association = (Association) handleMap.get(handle);

            if (latest == null ||
                    latest.getExpiry().before(association.getExpiry()))
                latest = association;
        }
    }

    return latest;
}
 
Example #8
Source File: AuthSuccess.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public static AuthSuccess createAuthSuccess(
                   String opEndpoint, String claimedId, String delegate,
                   boolean compatibility,
                   String returnTo, String nonce,
                   String invalidateHandle, Association assoc,
                   boolean signNow)
        throws MessageException, AssociationException
{
    AuthSuccess resp = new AuthSuccess(opEndpoint, claimedId, delegate,
                            compatibility, returnTo, nonce,
                            invalidateHandle, assoc, signNow);

    resp.validate();

    if (DEBUG) _log.debug("Created positive auth response:\n"
                          + resp.keyValueFormEncoding());

    return resp;
}
 
Example #9
Source File: InMemoryConsumerAssociationStore.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public synchronized Association load(String opUrl, String handle)
{
    removeExpired();

    if (_opMap.containsKey(opUrl))
    {
        Map handleMap = (Map) _opMap.get(opUrl);

        if (handleMap.containsKey(handle))
        {
            return (Association) handleMap.get(handle);
        }
    }

    return null;
}
 
Example #10
Source File: JdbcConsumerAssociationStore.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public void save ( String opUrl, Association association )
{
	cleanupExpired ( ) ;
	
	try
	{
		JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ;

		int cnt = jdbcTemplate.update ( _sqlInsert,
										new Object[]
											{
											 	opUrl,
												association.getHandle ( ),
												association.getType ( ),
												association.getMacKey ( ) == null ? null :
												    new String (
																Base64.encodeBase64 ( association.getMacKey ( ).getEncoded ( ) ) ),
												association.getExpiry ( ) } ) ;
	}
	catch ( Exception e )
	{
		_log.error ( "Error saving association to table: " + _tableName, e ) ;
	}
}
 
Example #11
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 6 votes vote down vote up
@Inject
public ConsumerManager(RealmVerifierFactory realmFactory, Discovery discovery,
    HttpFetcherFactory httpFetcherFactory)
{
    _realmVerifier = realmFactory.getRealmVerifierForConsumer();
    // don't verify own (RP) identity, disable RP discovery
    _realmVerifier.setEnforceRpId(false);

    _discovery = discovery;
    _httpFetcher = httpFetcherFactory.createFetcher(HttpRequestOptions.getDefaultOptionsForOpCalls());

    if (Association.isHmacSha256Supported())
        _prefAssocSessEnc = AssociationSessionType.DH_SHA256;
    else
        _prefAssocSessEnc = AssociationSessionType.DH_SHA1;
}
 
Example #12
Source File: XmlPersistenceHelper.java    From OpenID-Attacker with GNU General Public License v2.0 6 votes vote down vote up
public static void saveAssociationStoreToDisk(File saveFile, List<Association> associationList) throws XmlPersistenceError {
//        try {
//            JAXBContext jaxbContext = JAXBContext.newInstance(CustomInMemoryServerAssociationStore.class);
//            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//            jaxbMarshaller.marshal(associationStore, saveFile);
//            LOG.info(String.format("Saved successfully associations to '%s'", saveFile.getAbsoluteFile()));
//        } catch (JAXBException ex) {
//            throw new XmlPersistenceError(String.format("Could not save associations to File '%s'", saveFile.getAbsoluteFile()), ex);
//        }
        try {
            FileOutputStream f_out = new FileOutputStream(saveFile);
            ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
            obj_out.writeObject(associationList);
        } catch (IOException ex) {
            throw new XmlPersistenceError(String.format("Could not save associations to File '%s'", saveFile.getAbsoluteFile()), ex);
        }
    }
 
Example #13
Source File: ServerManager.java    From openid4java with Apache License 2.0 6 votes vote down vote up
/**
 * Signs an AuthSuccess message, using the association identified by the
 * handle specified within the message.
 *
 * @param   authSuccess     The Authentication Success message to be signed.
 *
 * @throws  ServerException If the Association corresponding to the handle
 *                          in the @authSuccess cannot be retrieved from
 *                          the store.
 * @throws  AssociationException    If the signature cannot be computed.
 *
 */
public void sign(AuthSuccess authSuccess)
    throws ServerException, AssociationException
{
    String handle = authSuccess.getHandle();

    // try shared associations first, then private
    Association assoc = _sharedAssociations.load(handle);

    if (assoc == null)
        assoc = _privateAssociations.load(handle);

    if (assoc == null) throw new ServerException(
            "No association found for handle: " + handle);

    authSuccess.setSignature(assoc.sign(authSuccess.getSignedText()));
}
 
Example #14
Source File: ConsumerAssociationStoreTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public void testSaveLoadRemove()
{
    _associationStore.save("http://example.com", Association.generateHmacSha1("a", 60));
    _associationStore.save("http://example.com", Association.generateHmacSha256("b", 60));
    _associationStore.save("http://example.com", Association.generateHmacSha1("c", 60));

    assertNotNull(_associationStore.load("http://example.com", "a"));
    assertNotNull(_associationStore.load("http://example.com", "b"));
    assertNotNull(_associationStore.load("http://example.com", "c"));

    assertNotNull(_associationStore.load("http://example.com"));

    _associationStore.remove("http://example.com", "b");

    assertNull(_associationStore.load("http://example.com", "b"));
}
 
Example #15
Source File: InMemoryServerAssociationStore.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public synchronized Association generate(String type, int expiryIn)
        throws AssociationException
{
    removeExpired();

    String handle = _timestamp + "-" + _counter++;

    Association association = Association.generate(type, handle, expiryIn);

    _handleMap.put(handle, association);

    if (DEBUG) _log.debug("Generated association, handle: " + handle +
                          " type: " + type +
                          " expires in: " + expiryIn + " seconds.");

    return association;
}
 
Example #16
Source File: CustomInMemoryServerAssociationStore.java    From OpenID-Attacker with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized Association generate(String type, int expiryIn)
  throws AssociationException {
    removeExpired();

    String handle;
    // If this is the first, just use the prefix
    handle = associationPrefix;
    while (_handleMap.containsKey(handle)) {
        // Otherwise, use prefix plus counter
        ++counter;
        handle = associationPrefix + "-" + counter;
    }

    Association association = Association.generate(type, handle, expiryIn);

    _handleMap.put(handle, association);

    if (DEBUG) {
        LOG.debug("Generated association, handle: " + handle
          + " type: " + type
          + " expires in: " + expiryIn + " seconds.");
    }
    removeExpired();

    return association;
}
 
Example #17
Source File: PrivateAssociationCryptoStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
    public Association generate(String type, int expiryIn) throws AssociationException {

        if(log.isDebugEnabled()){
            log.debug("Inside generate();  type : " + type + " expiryIn  : " + expiryIn);
        }

        long timestamp = new Date().getTime();
        if(log.isDebugEnabled()){
            log.debug("Current Time : " + timestamp);
        }
        // make time in to millisecond before it is set
        if(this.expireIn == 0){
            this.expireIn = expiryIn * 1000;
        }
        if(log.isDebugEnabled()){
            log.debug("Expires In : " + this.expireIn);
        }
        Date expireDate = new Date(timestamp + this.expireIn);
        if(log.isDebugEnabled()){
            log.debug("Expiry Time : " + expireDate.getTime());
        }

        String handle = Integer.toString(storeId) + Long.toString(timestamp) + "-" + Integer.toString(counter++);

        if(log.isDebugEnabled()){
            log.debug("Handle generated by crypto store : " + handle);
        }

//        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
//        PBEKeySpec spec = new PBEKeySpec(serverKey.toCharArray(), handle.getBytes(), 1, 256);
//        SecretKey secretKey = factory.generateSecret(spec);

        Association association = Association.createHmacSha256(handle, (serverKey + handle).getBytes(), expireDate);
        OpenIDServerManager.setThreadLocalAssociation(association);
        return association;
    }
 
Example #18
Source File: OpenIDAssociationReplicationManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void removeExpiredAssociations() {
    Date currentTime = new Date();
    for (Map.Entry<String, Association> entry : associationMap.entrySet()) {
        Association association = entry.getValue();
        if(currentTime.after(association.getExpiry())) {
            if (log.isDebugEnabled()) {
                log.debug("Current time : " + currentTime.getTime() + ", expiry time : "
                        + association.getExpiry().getTime() + ". Hence removing expired association : "
                        + association.getHandle());
            }
            removeAssociation(association.getHandle());
        }
    }

}
 
Example #19
Source File: OpenIDAssociationDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
     * Tries to store the association in the identity database. But if the entry
     * already exists this operation doesn't do anything useful.
     *
     * @param association
     */
    public void storeAssociation(Association association) {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;

        try {

//            if (!isAssociationExist(connection, association.getHandle())) {
                prepStmt = connection.prepareStatement(OpenIDSQLQueries.STORE_ASSOCIATION);
                prepStmt.setString(1, association.getHandle());
                prepStmt.setString(2, association.getType());
                prepStmt.setTimestamp(3, new java.sql.Timestamp(association.getExpiry().getTime()));
                prepStmt.setString(4, Base64.encode(association.getMacKey().getEncoded()));
                prepStmt.setString(5, associationStore);
                prepStmt.execute();
                connection.commit();
                if(log.isDebugEnabled()) {
                    log.debug("Association " + association.getHandle() + " successfully stored in the database");
                }
//            } else {
//                log.debug("Association " + association.getHandle() + " already exist in the database.");
//            }
            connection.commit();
        } catch (SQLException e) {
            log.error("Failed to store the association " + association.getHandle(), e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }
 
Example #20
Source File: OpenIDAssociationDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the association in the identity database.
 *
 * @param handle
 * @return <code>Association</code>
 */
public Association loadAssociation(String handle) {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet results = null;

    try {
        prepStmt = connection.prepareStatement(OpenIDSQLQueries.LOAD_ASSOCIATION);
        prepStmt.setString(1, handle);
        results = prepStmt.executeQuery();

        if (results.next()) {
            log.debug("Loading association " + handle);
            return buildAssociationObject(results);
        }
        connection.commit();
    } catch (SQLException e) {
        log.error("Failed to load the association " + handle, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, results, prepStmt);
    }
    if(log.isDebugEnabled()) {
        log.debug("Failed to load the association " + handle + " from the database");
    }
    return null;
}
 
Example #21
Source File: OpenIDAssociationCache.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Add the entry to the cache.
 *
 * @param association
 */
public void addToCache(Association association) {

    if(association == null){
        throw new IllegalArgumentException("Association is \'Null\'");
    }
    OpenIDIdentityCacheKey cacheKey = new OpenIDIdentityCacheKey(0, association.getHandle());
    OpenIDIdentityCacheEntry cacheEntry =
            new OpenIDIdentityCacheEntry(association.getType(), association.getMacKey(),
                                         association.getExpiry());
    associationCache.addToCache(cacheKey, cacheEntry);
    if (log.isDebugEnabled()) {
        log.debug("New entry is added to cache for handle : " + association.getHandle());
    }
}
 
Example #22
Source File: PrivateAssociationReplicationStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public Association generate(String type, int expiryIn) throws AssociationException {
    String handle = storeId + timestamp + "-" + getCounter();
    Association association = Association.generate(type, handle, expiryIn);

    // replicating association using cluster messages
    if(log.isDebugEnabled()) {
        log.debug("Storing association " + association.getHandle() + " in the map.");
    }
    OpenIDAssociationReplicationManager.getPersistenceManager().addAssociation(association);

    return association;
}
 
Example #23
Source File: OpenIDServerAssociationStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * First try to load from the memory, in case of failure look in the db.
 *
 * @param handle
 * @return <code>Association<code>
 */
@Override
public Association load(String handle) {

    boolean chacheMiss = false;

    // looking in the cache
    Association association = cache.getFromCache(handle);

    // if failed, look in the database
    if (association == null) {
        if(log.isDebugEnabled()) {
            log.debug("Association " + handle + " not found in cache. Loading from the database.");
        }
        association = dao.loadAssociation(handle);
        chacheMiss = true;
    }

    // no association found for the given handle
    if (association == null) {
        if(log.isDebugEnabled()) {
            log.debug("Association " + handle + " not found in the database.");
        }
        return null;
    }

    // if the association is expired
    if (association.hasExpired()) {
        log.warn("Association is expired for handle " + handle);
        remove(handle); // remove only from db
        return null;

    } else if (chacheMiss) {
        // add the missing entry to the cache
        cache.addToCache(association);
    }

    return association;
}
 
Example #24
Source File: AbstractServerAssociationStoreTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testCleanup() throws AssociationException, InterruptedException
{
    _associationStore.generate(Association.TYPE_HMAC_SHA1, 1);
    _associationStore.generate(Association.TYPE_HMAC_SHA1, 1);
    _associationStore.generate(Association.TYPE_HMAC_SHA1, 1);
    _associationStore.generate(Association.TYPE_HMAC_SHA1, 1);

    Thread.sleep(2000);

    _associationStore.generate(Association.TYPE_HMAC_SHA1, 1);
}
 
Example #25
Source File: AbstractServerAssociationStoreTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testRemove() throws AssociationException
{
    String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 1).getHandle();

    assertNotNull(_associationStore.load(handle));
    _associationStore.remove(handle);
    assertNull(_associationStore.load(handle));
}
 
Example #26
Source File: OpenIDServerManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void sign(AuthSuccess authSuccess)
        throws ServerException, AssociationException {
    String handle = authSuccess.getHandle();

    Association assoc = null;
    try {
        // First try in thread local
        assoc = getThreadLocalAssociation();
    } finally {
        // Clear thread local
        clearThreadLocalAssociation();
    }

    // try shared associations, then private
    if (assoc == null) {
        assoc = getSharedAssociations().load(handle);
    }

    if (assoc == null) {
        assoc = getPrivateAssociations().load(handle);
    }

    if (assoc == null) {
        throw new ServerException("No association found for handle: " + handle);
    }

    authSuccess.setSignature(assoc.sign(authSuccess.getSignedText()));
}
 
Example #27
Source File: AbstractServerAssociationStoreTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testExpiry() throws AssociationException, InterruptedException
{
    String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 1).getHandle();

    assertNotNull(_associationStore.load(handle));
    Thread.sleep(2000);
    assertNull(_associationStore.load(handle));
}
 
Example #28
Source File: AbstractServerAssociationStoreTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testLoad() throws AssociationException
{
    assertNull(_associationStore.load(null));
    assertNull(_associationStore.load(""));
    assertNull(_associationStore.load("xyz"));

    String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 60).getHandle();

    assertNotNull(_associationStore.load(handle));
    assertNotNull(_associationStore.load(handle));
}
 
Example #29
Source File: ConsumerAssociationStoreTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testCleanup() throws InterruptedException
{
    _associationStore.save("http://example.com", Association.generateHmacSha1("a", 1));
    _associationStore.save("http://example.com", Association.generateHmacSha256("b", 1));
    _associationStore.save("http://example.com", Association.generateHmacSha1("c", 1));

    _associationStore.save("http://example.net", Association.generateHmacSha1("a", 1));
    _associationStore.save("http://example.net", Association.generateHmacSha256("b", 1));
    _associationStore.save("http://example.net", Association.generateHmacSha1("c", 1));

    Thread.sleep(2000);

    _associationStore.save("http://example.org", Association.generateHmacSha1("d", 1));
}
 
Example #30
Source File: OpenIDAssociationReplicationManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void removeAssociation(String handle) {
    if(associationMap.containsKey(handle)) {
        Association association = associationMap.get(handle);
        AssociationClusterMessage associationInfoData = new AssociationClusterMessage(association, true);
        replicateAssociationInfo(associationInfoData);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Association does not exists. Cannot remove association : " + handle);
        }
    }
}