Merge pull request #1378 from ketola/fetch-tokens-by-sub

Fetch tokens by user name
pull/1315/merge
Justin Richer 2018-05-03 14:44:51 -04:00 committed by GitHub
commit dd922b4cf7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 365 additions and 170 deletions

View File

@ -71,7 +71,8 @@ import com.nimbusds.jwt.JWT;
@NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_CLIENT, query = "select a from OAuth2AccessTokenEntity a where a.client = :" + OAuth2AccessTokenEntity.PARAM_CLIENT), @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_CLIENT, query = "select a from OAuth2AccessTokenEntity a where a.client = :" + OAuth2AccessTokenEntity.PARAM_CLIENT),
@NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_TOKEN_VALUE, query = "select a from OAuth2AccessTokenEntity a where a.jwt = :" + OAuth2AccessTokenEntity.PARAM_TOKEN_VALUE), @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_TOKEN_VALUE, query = "select a from OAuth2AccessTokenEntity a where a.jwt = :" + OAuth2AccessTokenEntity.PARAM_TOKEN_VALUE),
@NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_APPROVED_SITE, query = "select a from OAuth2AccessTokenEntity a where a.approvedSite = :" + OAuth2AccessTokenEntity.PARAM_APPROVED_SITE), @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_APPROVED_SITE, query = "select a from OAuth2AccessTokenEntity a where a.approvedSite = :" + OAuth2AccessTokenEntity.PARAM_APPROVED_SITE),
@NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, query = "select a from OAuth2AccessTokenEntity a join a.permissions p where p.resourceSet.id = :" + OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID) @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, query = "select a from OAuth2AccessTokenEntity a join a.permissions p where p.resourceSet.id = :" + OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID),
@NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_NAME, query = "select r from OAuth2AccessTokenEntity r where r.authenticationHolder.userAuth.name = :" + OAuth2AccessTokenEntity.PARAM_NAME)
}) })
@org.codehaus.jackson.map.annotate.JsonSerialize(using = OAuth2AccessTokenJackson1Serializer.class) @org.codehaus.jackson.map.annotate.JsonSerialize(using = OAuth2AccessTokenJackson1Serializer.class)
@org.codehaus.jackson.map.annotate.JsonDeserialize(using = OAuth2AccessTokenJackson1Deserializer.class) @org.codehaus.jackson.map.annotate.JsonDeserialize(using = OAuth2AccessTokenJackson1Deserializer.class)
@ -86,6 +87,7 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
public static final String QUERY_EXPIRED_BY_DATE = "OAuth2AccessTokenEntity.getAllExpiredByDate"; public static final String QUERY_EXPIRED_BY_DATE = "OAuth2AccessTokenEntity.getAllExpiredByDate";
public static final String QUERY_ALL = "OAuth2AccessTokenEntity.getAll"; public static final String QUERY_ALL = "OAuth2AccessTokenEntity.getAll";
public static final String QUERY_BY_RESOURCE_SET = "OAuth2AccessTokenEntity.getByResourceSet"; public static final String QUERY_BY_RESOURCE_SET = "OAuth2AccessTokenEntity.getByResourceSet";
public static final String QUERY_BY_NAME = "OAuth2AccessTokenEntity.getByName";
public static final String PARAM_TOKEN_VALUE = "tokenValue"; public static final String PARAM_TOKEN_VALUE = "tokenValue";
public static final String PARAM_CLIENT = "client"; public static final String PARAM_CLIENT = "client";
@ -93,6 +95,7 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
public static final String PARAM_DATE = "date"; public static final String PARAM_DATE = "date";
public static final String PARAM_RESOURCE_SET_ID = "rsid"; public static final String PARAM_RESOURCE_SET_ID = "rsid";
public static final String PARAM_APPROVED_SITE = "approvedSite"; public static final String PARAM_APPROVED_SITE = "approvedSite";
public static final String PARAM_NAME = "name";
public static final String ID_TOKEN_FIELD_NAME = "id_token"; public static final String ID_TOKEN_FIELD_NAME = "id_token";

View File

@ -53,7 +53,8 @@ import com.nimbusds.jwt.JWT;
@NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_ALL, query = "select r from OAuth2RefreshTokenEntity r"), @NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_ALL, query = "select r from OAuth2RefreshTokenEntity r"),
@NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_EXPIRED_BY_DATE, query = "select r from OAuth2RefreshTokenEntity r where r.expiration <= :" + OAuth2RefreshTokenEntity.PARAM_DATE), @NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_EXPIRED_BY_DATE, query = "select r from OAuth2RefreshTokenEntity r where r.expiration <= :" + OAuth2RefreshTokenEntity.PARAM_DATE),
@NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_BY_CLIENT, query = "select r from OAuth2RefreshTokenEntity r where r.client = :" + OAuth2RefreshTokenEntity.PARAM_CLIENT), @NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_BY_CLIENT, query = "select r from OAuth2RefreshTokenEntity r where r.client = :" + OAuth2RefreshTokenEntity.PARAM_CLIENT),
@NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_BY_TOKEN_VALUE, query = "select r from OAuth2RefreshTokenEntity r where r.jwt = :" + OAuth2RefreshTokenEntity.PARAM_TOKEN_VALUE) @NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_BY_TOKEN_VALUE, query = "select r from OAuth2RefreshTokenEntity r where r.jwt = :" + OAuth2RefreshTokenEntity.PARAM_TOKEN_VALUE),
@NamedQuery(name = OAuth2RefreshTokenEntity.QUERY_BY_NAME, query = "select r from OAuth2RefreshTokenEntity r where r.authenticationHolder.userAuth.name = :" + OAuth2RefreshTokenEntity.PARAM_NAME)
}) })
public class OAuth2RefreshTokenEntity implements OAuth2RefreshToken { public class OAuth2RefreshTokenEntity implements OAuth2RefreshToken {
@ -61,10 +62,12 @@ public class OAuth2RefreshTokenEntity implements OAuth2RefreshToken {
public static final String QUERY_BY_CLIENT = "OAuth2RefreshTokenEntity.getByClient"; public static final String QUERY_BY_CLIENT = "OAuth2RefreshTokenEntity.getByClient";
public static final String QUERY_EXPIRED_BY_DATE = "OAuth2RefreshTokenEntity.getAllExpiredByDate"; public static final String QUERY_EXPIRED_BY_DATE = "OAuth2RefreshTokenEntity.getAllExpiredByDate";
public static final String QUERY_ALL = "OAuth2RefreshTokenEntity.getAll"; public static final String QUERY_ALL = "OAuth2RefreshTokenEntity.getAll";
public static final String QUERY_BY_NAME = "OAuth2RefreshTokenEntity.getByName";
public static final String PARAM_TOKEN_VALUE = "tokenValue"; public static final String PARAM_TOKEN_VALUE = "tokenValue";
public static final String PARAM_CLIENT = "client"; public static final String PARAM_CLIENT = "client";
public static final String PARAM_DATE = "date"; public static final String PARAM_DATE = "date";
public static final String PARAM_NAME = "name";
private Long id; private Long id;

View File

@ -52,6 +52,10 @@ public interface OAuth2TokenRepository {
public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client); public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client);
public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client); public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client);
public Set<OAuth2AccessTokenEntity> getAccessTokensByUserName(String name);
public Set<OAuth2RefreshTokenEntity> getRefreshTokensByUserName(String name);
public Set<OAuth2AccessTokenEntity> getAllAccessTokens(); public Set<OAuth2AccessTokenEntity> getAllAccessTokens();

View File

@ -47,10 +47,31 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId> <artifactId>spring-tx</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.persistence</groupId> <groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.core</artifactId> <artifactId>org.eclipse.persistence.core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>

View File

@ -20,6 +20,7 @@ package org.mitre.oauth2.repository.impl;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -168,9 +169,6 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
} }
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/
@Override @Override
public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) { public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_CLIENT, OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_CLIENT, OAuth2AccessTokenEntity.class);
@ -179,9 +177,6 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
return accessTokens; return accessTokens;
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/
@Override @Override
public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) { public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) {
TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery(OAuth2RefreshTokenEntity.QUERY_BY_CLIENT, OAuth2RefreshTokenEntity.class); TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery(OAuth2RefreshTokenEntity.QUERY_BY_CLIENT, OAuth2RefreshTokenEntity.class);
@ -189,6 +184,22 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList(); List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList();
return refreshTokens; return refreshTokens;
} }
@Override
public Set<OAuth2AccessTokenEntity> getAccessTokensByUserName(String name) {
TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_NAME, OAuth2AccessTokenEntity.class);
query.setParameter(OAuth2AccessTokenEntity.PARAM_NAME, name);
List<OAuth2AccessTokenEntity> results = query.getResultList();
return results != null ? new HashSet<>(query.getResultList()) : new HashSet<>();
}
@Override
public Set<OAuth2RefreshTokenEntity> getRefreshTokensByUserName(String name) {
TypedQuery<OAuth2RefreshTokenEntity> query = manager.createNamedQuery(OAuth2RefreshTokenEntity.QUERY_BY_NAME, OAuth2RefreshTokenEntity.class);
query.setParameter(OAuth2RefreshTokenEntity.PARAM_NAME, name);
List<OAuth2RefreshTokenEntity> results = query.getResultList();
return results != null ? new HashSet<>(query.getResultList()) : new HashSet<>();
}
@Override @Override
public Set<OAuth2AccessTokenEntity> getAllExpiredAccessTokens() { public Set<OAuth2AccessTokenEntity> getAllExpiredAccessTokens() {
@ -216,11 +227,6 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
return new LinkedHashSet<>(JpaUtil.getResultPage(query,pageCriteria)); return new LinkedHashSet<>(JpaUtil.getResultPage(query,pageCriteria));
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokensForResourceSet(org.mitre.uma.model.ResourceSet)
*/
@Override @Override
public Set<OAuth2AccessTokenEntity> getAccessTokensForResourceSet(ResourceSet rs) { public Set<OAuth2AccessTokenEntity> getAccessTokensForResourceSet(ResourceSet rs) {
TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, OAuth2AccessTokenEntity.class);
@ -228,13 +234,9 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
return new LinkedHashSet<>(query.getResultList()); return new LinkedHashSet<>(query.getResultList());
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#clearDuplicateAccessTokens()
*/
@Override @Override
@Transactional(value="defaultTransactionManager") @Transactional(value="defaultTransactionManager")
public void clearDuplicateAccessTokens() { public void clearDuplicateAccessTokens() {
Query query = manager.createQuery("select a.jwt, count(1) as c from OAuth2AccessTokenEntity a GROUP BY a.jwt HAVING count(1) > 1"); Query query = manager.createQuery("select a.jwt, count(1) as c from OAuth2AccessTokenEntity a GROUP BY a.jwt HAVING count(1) > 1");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Object[]> resultList = query.getResultList(); List<Object[]> resultList = query.getResultList();
@ -253,9 +255,6 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
} }
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#clearDuplicateRefreshTokens()
*/
@Override @Override
@Transactional(value="defaultTransactionManager") @Transactional(value="defaultTransactionManager")
public void clearDuplicateRefreshTokens() { public void clearDuplicateRefreshTokens() {

View File

@ -66,7 +66,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.nimbusds.jose.util.Base64URL; import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.PlainJWT; import com.nimbusds.jwt.PlainJWT;
@ -102,35 +101,14 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
@Autowired @Autowired
private ApprovedSiteService approvedSiteService; private ApprovedSiteService approvedSiteService;
@Override @Override
public Set<OAuth2AccessTokenEntity> getAllAccessTokensForUser(String id) { public Set<OAuth2AccessTokenEntity> getAllAccessTokensForUser(String userName) {
return tokenRepository.getAccessTokensByUserName(userName);
Set<OAuth2AccessTokenEntity> all = tokenRepository.getAllAccessTokens();
Set<OAuth2AccessTokenEntity> results = Sets.newLinkedHashSet();
for (OAuth2AccessTokenEntity token : all) {
if (clearExpiredAccessToken(token) != null && token.getAuthenticationHolder().getAuthentication().getName().equals(id)) {
results.add(token);
}
}
return results;
} }
@Override @Override
public Set<OAuth2RefreshTokenEntity> getAllRefreshTokensForUser(String id) { public Set<OAuth2RefreshTokenEntity> getAllRefreshTokensForUser(String userName) {
Set<OAuth2RefreshTokenEntity> all = tokenRepository.getAllRefreshTokens(); return tokenRepository.getRefreshTokensByUserName(userName);
Set<OAuth2RefreshTokenEntity> results = Sets.newLinkedHashSet();
for (OAuth2RefreshTokenEntity token : all) {
if (clearExpiredRefreshToken(token) != null && token.getAuthenticationHolder().getAuthentication().getName().equals(id)) {
results.add(token);
}
}
return results;
} }
@Override @Override
@ -192,7 +170,6 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
throw new InvalidClientException("Client not found: " + request.getClientId()); throw new InvalidClientException("Client not found: " + request.getClientId());
} }
// handle the PKCE code challenge if present // handle the PKCE code challenge if present
if (request.getExtensions().containsKey(CODE_CHALLENGE)) { if (request.getExtensions().containsKey(CODE_CHALLENGE)) {
String challenge = (String) request.getExtensions().get(CODE_CHALLENGE); String challenge = (String) request.getExtensions().get(CODE_CHALLENGE);
@ -220,7 +197,6 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
} }
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken(); OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken();
// attach the client // attach the client
@ -306,8 +282,6 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
refreshToken.setAuthenticationHolder(authHolder); refreshToken.setAuthenticationHolder(authHolder);
refreshToken.setClient(client); refreshToken.setClient(client);
// save the token first so that we can set it to a member of the access token (NOTE: is this step necessary?) // save the token first so that we can set it to a member of the access token (NOTE: is this step necessary?)
OAuth2RefreshTokenEntity savedRefreshToken = tokenRepository.saveRefreshToken(refreshToken); OAuth2RefreshTokenEntity savedRefreshToken = tokenRepository.saveRefreshToken(refreshToken);
return savedRefreshToken; return savedRefreshToken;
@ -410,12 +384,10 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
tokenRepository.saveAccessToken(token); tokenRepository.saveAccessToken(token);
return token; return token;
} }
@Override @Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException { public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException {
OAuth2AccessTokenEntity accessToken = clearExpiredAccessToken(tokenRepository.getAccessTokenByValue(accessTokenValue)); OAuth2AccessTokenEntity accessToken = clearExpiredAccessToken(tokenRepository.getAccessTokenByValue(accessTokenValue));
if (accessToken == null) { if (accessToken == null) {
@ -481,18 +453,11 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
tokenRepository.removeAccessToken(accessToken); tokenRepository.removeAccessToken(accessToken);
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/
@Override @Override
public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) { public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) {
return tokenRepository.getAccessTokensForClient(client); return tokenRepository.getAccessTokensForClient(client);
} }
/* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/
@Override @Override
public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) { public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) {
return tokenRepository.getRefreshTokensForClient(client); return tokenRepository.getRefreshTokensForClient(client);
@ -595,7 +560,4 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
return null; return null;
} }
} }

View File

@ -0,0 +1,96 @@
package org.mitre.oauth2.repository.impl;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
public class TestDatabaseConfiguration {
@Autowired
private JpaVendorAdapter jpaAdapter;
@Autowired
private DataSource dataSource;
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public JpaOAuth2TokenRepository repository() {
return new JpaOAuth2TokenRepository();
}
@Bean(name = "defaultPersistenceUnit")
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPackagesToScan("org.mitre", "org.mitre");
factory.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class);
factory.setPersistenceUnitName("test" + System.currentTimeMillis());
factory.setDataSource(dataSource);
factory.setJpaVendorAdapter(jpaAdapter);
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.level", "INFO");
jpaProperties.put("eclipselink.logging.level.sql", "INFO");
jpaProperties.put("eclipselink.cache.shared.default", "false");
factory.setJpaPropertyMap(jpaProperties);
return factory;
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder(new DefaultResourceLoader() {
@Override
public Resource getResource(String location) {
String sql;
try {
sql = new String(Files.readAllBytes(Paths.get("..", "openid-connect-server-webapp", "src", "main",
"resources", "db", "hsql", location)), UTF_8);
} catch (IOException e) {
throw new RuntimeException("Failed to read sql-script " + location, e);
}
return new ByteArrayResource(sql.getBytes(UTF_8));
}
}).generateUniqueName(true).setScriptEncoding(UTF_8.name()).setType(EmbeddedDatabaseType.HSQL)
.addScripts("hsql_database_tables.sql").build();
}
@Bean
public JpaVendorAdapter jpaAdapter() {
EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter();
adapter.setDatabase(Database.HSQL);
adapter.setShowSql(true);
return adapter;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager platformTransactionManager = new JpaTransactionManager();
platformTransactionManager.setEntityManagerFactory(entityManagerFactory);
return platformTransactionManager;
}
}

View File

@ -0,0 +1,107 @@
package org.mitre.oauth2.repository.impl;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mitre.oauth2.model.AuthenticationHolderEntity;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
import org.mitre.oauth2.model.SavedUserAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { TestDatabaseConfiguration.class })
@Transactional
public class TestJpaOAuth2TokenRepository {
@Autowired
private JpaOAuth2TokenRepository repository;
@PersistenceContext
private EntityManager entityManager;
@Before
public void setUp(){
createAccessToken("user1");
createAccessToken("user1");
createAccessToken("user2");
createAccessToken("user2");
createRefreshToken("user1");
createRefreshToken("user1");
createRefreshToken("user2");
createRefreshToken("user2");
createRefreshToken("user2");
}
@Test
public void testGetAccessTokensByUserName() {
Set<OAuth2AccessTokenEntity> tokens = repository.getAccessTokensByUserName("user1");
assertEquals(2, tokens.size());
assertEquals("user1", tokens.iterator().next().getAuthenticationHolder().getUserAuth().getName());
}
@Test
public void testGetRefreshTokensByUserName() {
Set<OAuth2RefreshTokenEntity> tokens = repository.getRefreshTokensByUserName("user2");
assertEquals(3, tokens.size());
assertEquals("user2", tokens.iterator().next().getAuthenticationHolder().getUserAuth().getName());
}
@Test
public void testGetAllAccessTokens(){
Set<OAuth2AccessTokenEntity> tokens = repository.getAllAccessTokens();
assertEquals(4, tokens.size());
}
@Test
public void testGetAllRefreshTokens(){
Set<OAuth2RefreshTokenEntity> tokens = repository.getAllRefreshTokens();
assertEquals(5, tokens.size());
}
private OAuth2AccessTokenEntity createAccessToken(String name) {
SavedUserAuthentication userAuth = new SavedUserAuthentication();
userAuth.setName(name);
userAuth = entityManager.merge(userAuth);
AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
authHolder.setUserAuth(userAuth);
authHolder = entityManager.merge(authHolder);
OAuth2AccessTokenEntity accessToken = new OAuth2AccessTokenEntity();
accessToken.setAuthenticationHolder(authHolder);
accessToken = entityManager.merge(accessToken);
return accessToken;
}
private OAuth2RefreshTokenEntity createRefreshToken(String name) {
SavedUserAuthentication userAuth = new SavedUserAuthentication();
userAuth.setName(name);
userAuth = entityManager.merge(userAuth);
AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
authHolder.setUserAuth(userAuth);
authHolder = entityManager.merge(authHolder);
OAuth2RefreshTokenEntity refreshToken = new OAuth2RefreshTokenEntity();
refreshToken.setAuthenticationHolder(authHolder);
refreshToken = entityManager.merge(refreshToken);
return refreshToken;
}
}

View File

@ -33,7 +33,6 @@ import org.mitre.oauth2.repository.AuthenticationHolderRepository;
import org.mitre.oauth2.repository.OAuth2TokenRepository; import org.mitre.oauth2.repository.OAuth2TokenRepository;
import org.mitre.oauth2.service.ClientDetailsEntityService; import org.mitre.oauth2.service.ClientDetailsEntityService;
import org.mitre.oauth2.service.SystemScopeService; import org.mitre.oauth2.service.SystemScopeService;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Matchers; import org.mockito.Matchers;
import org.mockito.Mock; import org.mockito.Mock;
@ -50,17 +49,23 @@ import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest; import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import com.google.common.collect.Sets; import static com.google.common.collect.Sets.newHashSet;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anySet;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -81,9 +86,11 @@ public class TestDefaultOAuth2ProviderTokenService {
private ClientDetailsEntity badClient; private ClientDetailsEntity badClient;
private String clientId = "test_client"; private String clientId = "test_client";
private String badClientId = "bad_client"; private String badClientId = "bad_client";
private Set<String> scope = Sets.newHashSet("openid", "profile", "email", "offline_access"); private Set<String> scope = newHashSet("openid", "profile", "email", "offline_access");
private OAuth2RefreshTokenEntity refreshToken; private OAuth2RefreshTokenEntity refreshToken;
private OAuth2AccessTokenEntity accessToken;
private String refreshTokenValue = "refresh_token_value"; private String refreshTokenValue = "refresh_token_value";
private String userName = "6a50ac11786d402a9591d3e592ac770f";
private TokenRequest tokenRequest; private TokenRequest tokenRequest;
// for use when refreshing access tokens // for use when refreshing access tokens
@ -115,48 +122,48 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Before @Before
public void prepare() { public void prepare() {
Mockito.reset(tokenRepository, authenticationHolderRepository, clientDetailsService, tokenEnhancer); reset(tokenRepository, authenticationHolderRepository, clientDetailsService, tokenEnhancer);
authentication = Mockito.mock(OAuth2Authentication.class); authentication = Mockito.mock(OAuth2Authentication.class);
OAuth2Request clientAuth = new OAuth2Request(null, clientId, null, true, scope, null, null, null, null); OAuth2Request clientAuth = new OAuth2Request(null, clientId, null, true, scope, null, null, null, null);
Mockito.when(authentication.getOAuth2Request()).thenReturn(clientAuth); when(authentication.getOAuth2Request()).thenReturn(clientAuth);
client = Mockito.mock(ClientDetailsEntity.class); client = Mockito.mock(ClientDetailsEntity.class);
Mockito.when(client.getClientId()).thenReturn(clientId); when(client.getClientId()).thenReturn(clientId);
Mockito.when(clientDetailsService.loadClientByClientId(clientId)).thenReturn(client); when(clientDetailsService.loadClientByClientId(clientId)).thenReturn(client);
Mockito.when(client.isReuseRefreshToken()).thenReturn(true); when(client.isReuseRefreshToken()).thenReturn(true);
// by default in tests, allow refresh tokens // by default in tests, allow refresh tokens
Mockito.when(client.isAllowRefresh()).thenReturn(true); when(client.isAllowRefresh()).thenReturn(true);
// by default, clear access tokens on refresh // by default, clear access tokens on refresh
Mockito.when(client.isClearAccessTokensOnRefresh()).thenReturn(true); when(client.isClearAccessTokensOnRefresh()).thenReturn(true);
badClient = Mockito.mock(ClientDetailsEntity.class); badClient = Mockito.mock(ClientDetailsEntity.class);
Mockito.when(badClient.getClientId()).thenReturn(badClientId); when(badClient.getClientId()).thenReturn(badClientId);
Mockito.when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient); when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient);
refreshToken = Mockito.mock(OAuth2RefreshTokenEntity.class); refreshToken = Mockito.mock(OAuth2RefreshTokenEntity.class);
Mockito.when(tokenRepository.getRefreshTokenByValue(refreshTokenValue)).thenReturn(refreshToken); when(tokenRepository.getRefreshTokenByValue(refreshTokenValue)).thenReturn(refreshToken);
Mockito.when(refreshToken.getClient()).thenReturn(client); when(refreshToken.getClient()).thenReturn(client);
Mockito.when(refreshToken.isExpired()).thenReturn(false); when(refreshToken.isExpired()).thenReturn(false);
accessToken = Mockito.mock(OAuth2AccessTokenEntity.class);
tokenRequest = new TokenRequest(null, clientId, null, null); tokenRequest = new TokenRequest(null, clientId, null, null);
storedAuthentication = authentication; storedAuthentication = authentication;
storedAuthRequest = clientAuth; storedAuthRequest = clientAuth;
storedAuthHolder = Mockito.mock(AuthenticationHolderEntity.class); storedAuthHolder = mock(AuthenticationHolderEntity.class);
storedScope = Sets.newHashSet(scope); storedScope = newHashSet(scope);
Mockito.when(refreshToken.getAuthenticationHolder()).thenReturn(storedAuthHolder); when(refreshToken.getAuthenticationHolder()).thenReturn(storedAuthHolder);
Mockito.when(storedAuthHolder.getAuthentication()).thenReturn(storedAuthentication); when(storedAuthHolder.getAuthentication()).thenReturn(storedAuthentication);
Mockito.when(storedAuthentication.getOAuth2Request()).thenReturn(storedAuthRequest); when(storedAuthentication.getOAuth2Request()).thenReturn(storedAuthRequest);
Mockito.when(authenticationHolderRepository.save(Matchers.any(AuthenticationHolderEntity.class))).thenReturn(storedAuthHolder); when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))).thenReturn(storedAuthHolder);
Mockito.when(scopeService.fromStrings(Matchers.anySet())).thenAnswer(new Answer<Set<SystemScope>>() { when(scopeService.fromStrings(anySet())).thenAnswer(new Answer<Set<SystemScope>>() {
@Override @Override
public Set<SystemScope> answer(InvocationOnMock invocation) throws Throwable { public Set<SystemScope> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments(); Object[] args = invocation.getArguments();
@ -169,7 +176,7 @@ public class TestDefaultOAuth2ProviderTokenService {
} }
}); });
Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer<Set<String>>() { when(scopeService.toStrings(anySet())).thenAnswer(new Answer<Set<String>>() {
@Override @Override
public Set<String> answer(InvocationOnMock invocation) throws Throwable { public Set<String> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments(); Object[] args = invocation.getArguments();
@ -183,10 +190,10 @@ public class TestDefaultOAuth2ProviderTokenService {
}); });
// we're not testing restricted or reserved scopes here, just pass through // we're not testing restricted or reserved scopes here, just pass through
Mockito.when(scopeService.removeReservedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); when(scopeService.removeReservedScopes(anySet())).then(returnsFirstArg());
Mockito.when(scopeService.removeRestrictedAndReservedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); when(scopeService.removeRestrictedAndReservedScopes(anySet())).then(returnsFirstArg());
Mockito.when(tokenEnhancer.enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.any(OAuth2Authentication.class))) when(tokenEnhancer.enhance(any(OAuth2AccessTokenEntity.class), any(OAuth2Authentication.class)))
.thenAnswer(new Answer<OAuth2AccessTokenEntity>(){ .thenAnswer(new Answer<OAuth2AccessTokenEntity>(){
@Override @Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
@ -195,7 +202,7 @@ public class TestDefaultOAuth2ProviderTokenService {
} }
}); });
Mockito.when(tokenRepository.saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class))) when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class)))
.thenAnswer(new Answer<OAuth2AccessTokenEntity>() { .thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
@Override @Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
@ -205,7 +212,7 @@ public class TestDefaultOAuth2ProviderTokenService {
}); });
Mockito.when(tokenRepository.saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class))) when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class)))
.thenAnswer(new Answer<OAuth2RefreshTokenEntity>() { .thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
@Override @Override
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
@ -221,8 +228,7 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test @Test
public void createAccessToken_nullAuth() { public void createAccessToken_nullAuth() {
when(authentication.getOAuth2Request()).thenReturn(null);
Mockito.when(authentication.getOAuth2Request()).thenReturn(null);
try { try {
service.createAccessToken(null); service.createAccessToken(null);
@ -244,8 +250,7 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test(expected = InvalidClientException.class) @Test(expected = InvalidClientException.class)
public void createAccessToken_nullClient() { public void createAccessToken_nullClient() {
when(clientDetailsService.loadClientByClientId(anyString())).thenReturn(null);
Mockito.when(clientDetailsService.loadClientByClientId(Matchers.anyString())).thenReturn(null);
service.createAccessToken(authentication); service.createAccessToken(authentication);
} }
@ -255,18 +260,17 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test @Test
public void createAccessToken_noRefresh() { public void createAccessToken_noRefresh() {
when(client.isAllowRefresh()).thenReturn(false);
Mockito.when(client.isAllowRefresh()).thenReturn(false);
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
Mockito.verify(clientDetailsService).loadClientByClientId(Matchers.anyString()); verify(clientDetailsService).loadClientByClientId(anyString());
Mockito.verify(authenticationHolderRepository).save(Matchers.any(AuthenticationHolderEntity.class)); verify(authenticationHolderRepository).save(any(AuthenticationHolderEntity.class));
Mockito.verify(tokenEnhancer).enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.eq(authentication)); verify(tokenEnhancer).enhance(any(OAuth2AccessTokenEntity.class), Matchers.eq(authentication));
Mockito.verify(tokenRepository).saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class)); verify(tokenRepository).saveAccessToken(any(OAuth2AccessTokenEntity.class));
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
Mockito.verify(tokenRepository, Mockito.never()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class)); verify(tokenRepository, Mockito.never()).saveRefreshToken(any(OAuth2RefreshTokenEntity.class));
assertThat(token.getRefreshToken(), is(nullValue())); assertThat(token.getRefreshToken(), is(nullValue()));
} }
@ -276,19 +280,17 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test @Test
public void createAccessToken_yesRefresh() { public void createAccessToken_yesRefresh() {
OAuth2Request clientAuth = new OAuth2Request(null, clientId, null, true, newHashSet(SystemScopeService.OFFLINE_ACCESS), null, null, null, null);
OAuth2Request clientAuth = new OAuth2Request(null, clientId, null, true, Sets.newHashSet(SystemScopeService.OFFLINE_ACCESS), null, null, null, null); when(authentication.getOAuth2Request()).thenReturn(clientAuth);
Mockito.when(authentication.getOAuth2Request()).thenReturn(clientAuth); when(client.isAllowRefresh()).thenReturn(true);
Mockito.when(client.isAllowRefresh()).thenReturn(true);
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
// Note: a refactor may be appropriate to only save refresh tokens once to the repository during creation. // Note: a refactor may be appropriate to only save refresh tokens once to the repository during creation.
Mockito.verify(tokenRepository, Mockito.atLeastOnce()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class)); verify(tokenRepository, atLeastOnce()).saveRefreshToken(any(OAuth2RefreshTokenEntity.class));
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getRefreshToken(), is(notNullValue())); assertThat(token.getRefreshToken(), is(notNullValue()));
} }
/** /**
@ -296,12 +298,11 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test @Test
public void createAccessToken_expiration() { public void createAccessToken_expiration() {
Integer accessTokenValiditySeconds = 3600; Integer accessTokenValiditySeconds = 3600;
Integer refreshTokenValiditySeconds = 600; Integer refreshTokenValiditySeconds = 600;
Mockito.when(client.getAccessTokenValiditySeconds()).thenReturn(accessTokenValiditySeconds); when(client.getAccessTokenValiditySeconds()).thenReturn(accessTokenValiditySeconds);
Mockito.when(client.getRefreshTokenValiditySeconds()).thenReturn(refreshTokenValiditySeconds); when(client.getRefreshTokenValiditySeconds()).thenReturn(refreshTokenValiditySeconds);
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
@ -313,7 +314,7 @@ public class TestDefaultOAuth2ProviderTokenService {
Date lowerBoundRefreshTokens = new Date(start + (refreshTokenValiditySeconds * 1000L) - DELTA); Date lowerBoundRefreshTokens = new Date(start + (refreshTokenValiditySeconds * 1000L) - DELTA);
Date upperBoundRefreshTokens = new Date(end + (refreshTokenValiditySeconds * 1000L) + DELTA); Date upperBoundRefreshTokens = new Date(end + (refreshTokenValiditySeconds * 1000L) + DELTA);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens)); assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens));
assertTrue(token.getRefreshToken().getExpiration().after(lowerBoundRefreshTokens) && token.getRefreshToken().getExpiration().before(upperBoundRefreshTokens)); assertTrue(token.getRefreshToken().getExpiration().after(lowerBoundRefreshTokens) && token.getRefreshToken().getExpiration().before(upperBoundRefreshTokens));
@ -321,59 +322,52 @@ public class TestDefaultOAuth2ProviderTokenService {
@Test @Test
public void createAccessToken_checkClient() { public void createAccessToken_checkClient() {
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getClient().getClientId(), equalTo(clientId)); assertThat(token.getClient().getClientId(), equalTo(clientId));
} }
@Test @Test
public void createAccessToken_checkScopes() { public void createAccessToken_checkScopes() {
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(scope)); assertThat(token.getScope(), equalTo(scope));
} }
@Test @Test
public void createAccessToken_checkAttachedAuthentication() { public void createAccessToken_checkAttachedAuthentication() {
AuthenticationHolderEntity authHolder = mock(AuthenticationHolderEntity.class);
when(authHolder.getAuthentication()).thenReturn(authentication);
AuthenticationHolderEntity authHolder = Mockito.mock(AuthenticationHolderEntity.class); when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))).thenReturn(authHolder);
Mockito.when(authHolder.getAuthentication()).thenReturn(authentication);
Mockito.when(authenticationHolderRepository.save(Matchers.any(AuthenticationHolderEntity.class))).thenReturn(authHolder);
OAuth2AccessTokenEntity token = service.createAccessToken(authentication); OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
assertThat(token.getAuthenticationHolder().getAuthentication(), equalTo(authentication)); assertThat(token.getAuthenticationHolder().getAuthentication(), equalTo(authentication));
Mockito.verify(authenticationHolderRepository).save(Matchers.any(AuthenticationHolderEntity.class)); verify(authenticationHolderRepository).save(any(AuthenticationHolderEntity.class));
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
} }
@Test(expected = InvalidTokenException.class) @Test(expected = InvalidTokenException.class)
public void refreshAccessToken_noRefreshToken() { public void refreshAccessToken_noRefreshToken() {
when(tokenRepository.getRefreshTokenByValue(anyString())).thenReturn(null);
Mockito.when(tokenRepository.getRefreshTokenByValue(Matchers.anyString())).thenReturn(null);
service.refreshAccessToken(refreshTokenValue, tokenRequest); service.refreshAccessToken(refreshTokenValue, tokenRequest);
} }
@Test(expected = InvalidClientException.class) @Test(expected = InvalidClientException.class)
public void refreshAccessToken_notAllowRefresh() { public void refreshAccessToken_notAllowRefresh() {
when(client.isAllowRefresh()).thenReturn(false);
Mockito.when(client.isAllowRefresh()).thenReturn(false);
service.refreshAccessToken(refreshTokenValue, tokenRequest); service.refreshAccessToken(refreshTokenValue, tokenRequest);
} }
@Test(expected = InvalidClientException.class) @Test(expected = InvalidClientException.class)
public void refreshAccessToken_clientMismatch() { public void refreshAccessToken_clientMismatch() {
tokenRequest = new TokenRequest(null, badClientId, null, null); tokenRequest = new TokenRequest(null, badClientId, null, null);
service.refreshAccessToken(refreshTokenValue, tokenRequest); service.refreshAccessToken(refreshTokenValue, tokenRequest);
@ -381,96 +375,89 @@ public class TestDefaultOAuth2ProviderTokenService {
@Test(expected = InvalidTokenException.class) @Test(expected = InvalidTokenException.class)
public void refreshAccessToken_expired() { public void refreshAccessToken_expired() {
when(refreshToken.isExpired()).thenReturn(true);
Mockito.when(refreshToken.isExpired()).thenReturn(true);
service.refreshAccessToken(refreshTokenValue, tokenRequest); service.refreshAccessToken(refreshTokenValue, tokenRequest);
} }
@Test @Test
public void refreshAccessToken_verifyAcessToken() { public void refreshAccessToken_verifyAcessToken() {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken); verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken);
assertThat(token.getClient(), equalTo(client)); assertThat(token.getClient(), equalTo(client));
assertThat(token.getRefreshToken(), equalTo(refreshToken)); assertThat(token.getRefreshToken(), equalTo(refreshToken));
assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder));
Mockito.verify(tokenEnhancer).enhance(token, storedAuthentication); verify(tokenEnhancer).enhance(token, storedAuthentication);
Mockito.verify(tokenRepository).saveAccessToken(token); verify(tokenRepository).saveAccessToken(token);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
} }
@Test @Test
public void refreshAccessToken_rotateRefreshToken() { public void refreshAccessToken_rotateRefreshToken() {
when(client.isReuseRefreshToken()).thenReturn(false); when(client.isReuseRefreshToken()).thenReturn(false);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken); verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken);
assertThat(token.getClient(), equalTo(client)); assertThat(token.getClient(), equalTo(client));
assertThat(token.getRefreshToken(), not(equalTo(refreshToken))); assertThat(token.getRefreshToken(), not(equalTo(refreshToken)));
assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder));
Mockito.verify(tokenEnhancer).enhance(token, storedAuthentication); verify(tokenEnhancer).enhance(token, storedAuthentication);
Mockito.verify(tokenRepository).saveAccessToken(token); verify(tokenRepository).saveAccessToken(token);
Mockito.verify(tokenRepository).removeRefreshToken(refreshToken); verify(tokenRepository).removeRefreshToken(refreshToken);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
} }
@Test @Test
public void refreshAccessToken_keepAccessTokens() { public void refreshAccessToken_keepAccessTokens() {
when(client.isClearAccessTokensOnRefresh()).thenReturn(false); when(client.isClearAccessTokensOnRefresh()).thenReturn(false);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(tokenRepository, never()).clearAccessTokensForRefreshToken(refreshToken); verify(tokenRepository, never()).clearAccessTokensForRefreshToken(refreshToken);
assertThat(token.getClient(), equalTo(client)); assertThat(token.getClient(), equalTo(client));
assertThat(token.getRefreshToken(), equalTo(refreshToken)); assertThat(token.getRefreshToken(), equalTo(refreshToken));
assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder));
Mockito.verify(tokenEnhancer).enhance(token, storedAuthentication); verify(tokenEnhancer).enhance(token, storedAuthentication);
Mockito.verify(tokenRepository).saveAccessToken(token); verify(tokenRepository).saveAccessToken(token);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
} }
@Test @Test
public void refreshAccessToken_requestingSameScope() { public void refreshAccessToken_requestingSameScope() {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(storedScope)); assertThat(token.getScope(), equalTo(storedScope));
} }
@Test @Test
public void refreshAccessToken_requestingLessScope() { public void refreshAccessToken_requestingLessScope() {
Set<String> lessScope = newHashSet("openid", "profile");
Set<String> lessScope = Sets.newHashSet("openid", "profile");
tokenRequest.setScope(lessScope); tokenRequest.setScope(lessScope);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(lessScope)); assertThat(token.getScope(), equalTo(lessScope));
} }
@Test(expected = InvalidScopeException.class) @Test(expected = InvalidScopeException.class)
public void refreshAccessToken_requestingMoreScope() { public void refreshAccessToken_requestingMoreScope() {
Set<String> moreScope = newHashSet(storedScope);
Set<String> moreScope = Sets.newHashSet(storedScope);
moreScope.add("address"); moreScope.add("address");
moreScope.add("phone"); moreScope.add("phone");
@ -485,8 +472,7 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test(expected = InvalidScopeException.class) @Test(expected = InvalidScopeException.class)
public void refreshAccessToken_requestingMixedScope() { public void refreshAccessToken_requestingMixedScope() {
Set<String> mixedScope = newHashSet("openid", "profile", "address", "phone"); // no email or offline_access
Set<String> mixedScope = Sets.newHashSet("openid", "profile", "address", "phone"); // no email or offline_access
tokenRequest.setScope(mixedScope); tokenRequest.setScope(mixedScope);
@ -495,26 +481,24 @@ public class TestDefaultOAuth2ProviderTokenService {
@Test @Test
public void refreshAccessToken_requestingEmptyScope() { public void refreshAccessToken_requestingEmptyScope() {
Set<String> emptyScope = newHashSet();
Set<String> emptyScope = Sets.newHashSet();
tokenRequest.setScope(emptyScope); tokenRequest.setScope(emptyScope);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(storedScope)); assertThat(token.getScope(), equalTo(storedScope));
} }
@Test @Test
public void refreshAccessToken_requestingNullScope() { public void refreshAccessToken_requestingNullScope() {
tokenRequest.setScope(null); tokenRequest.setScope(null);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(storedScope)); assertThat(token.getScope(), equalTo(storedScope));
@ -525,10 +509,9 @@ public class TestDefaultOAuth2ProviderTokenService {
*/ */
@Test @Test
public void refreshAccessToken_expiration() { public void refreshAccessToken_expiration() {
Integer accessTokenValiditySeconds = 3600; Integer accessTokenValiditySeconds = 3600;
Mockito.when(client.getAccessTokenValiditySeconds()).thenReturn(accessTokenValiditySeconds); when(client.getAccessTokenValiditySeconds()).thenReturn(accessTokenValiditySeconds);
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
@ -538,9 +521,26 @@ public class TestDefaultOAuth2ProviderTokenService {
Date lowerBoundAccessTokens = new Date(start + (accessTokenValiditySeconds * 1000L) - DELTA); Date lowerBoundAccessTokens = new Date(start + (accessTokenValiditySeconds * 1000L) - DELTA);
Date upperBoundAccessTokens = new Date(end + (accessTokenValiditySeconds * 1000L) + DELTA); Date upperBoundAccessTokens = new Date(end + (accessTokenValiditySeconds * 1000L) + DELTA);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens)); assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens));
} }
@Test
public void getAllAccessTokensForUser(){
when(tokenRepository.getAccessTokensByUserName(userName)).thenReturn(newHashSet(accessToken));
Set<OAuth2AccessTokenEntity> tokens = service.getAllAccessTokensForUser(userName);
assertEquals(1, tokens.size());
assertTrue(tokens.contains(accessToken));
}
@Test
public void getAllRefreshTokensForUser(){
when(tokenRepository.getRefreshTokensByUserName(userName)).thenReturn(newHashSet(refreshToken));
Set<OAuth2RefreshTokenEntity> tokens = service.getAllRefreshTokensForUser(userName);
assertEquals(1, tokens.size());
assertTrue(tokens.contains(refreshToken));
}
} }