use of com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity in project oauth2-server by gw2auth.
the class OAuth2ServerTest method consentSubmitWithLaterRemovedRootApiTokens.
@WithGw2AuthLogin
public void consentSubmitWithLaterRemovedRootApiTokens(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final ClientRegistrationCreation clientRegistrationCreation = createClientRegistration();
final ClientRegistration clientRegistration = clientRegistrationCreation.clientRegistration();
// perform authorization request (which should redirect to the consent page)
MvcResult result = performAuthorizeWithClient(session, clientRegistration, List.of(Gw2ApiPermission.ACCOUNT.oauth2())).andReturn();
// submit the consent
final String tokenA = TestHelper.randomRootToken();
final String tokenB = TestHelper.randomRootToken();
final String tokenC = TestHelper.randomRootToken();
result = performSubmitConsent(session, clientRegistration, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), tokenA, tokenB, tokenC).andReturn();
// verify the consent has been saved
final ClientConsentEntity clientConsentEntity = this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientRegistration.id()).orElse(null);
assertNotNull(clientConsentEntity);
assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2()), clientConsentEntity.authorizedScopes());
// verify the authorization has been saved
final List<ClientAuthorizationEntity> authorizations = this.clientAuthorizationRepository.findAllByAccountIdAndClientRegistrationId(accountId, clientConsentEntity.clientRegistrationId());
assertEquals(1, authorizations.size());
final ClientAuthorizationEntity clientAuthorization = authorizations.get(0);
assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2()), clientAuthorization.authorizedScopes());
List<ClientAuthorizationTokenEntity> clientAuthorizationTokenEntities = this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, clientAuthorization.id());
assertEquals(2, clientAuthorizationTokenEntities.size());
// set testing clock to token customizer
Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
this.oAuth2TokenCustomizerService.setClock(testingClock);
// retrieve the initial access and refresh token
final String[] dummySubtokenA = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId1st, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
final String[] dummySubtokenB = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId2nd, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
result = performRetrieveTokenByCodeAndExpectValid(clientRegistrationCreation, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), Map.of(tokenA, dummySubtokenA[0], tokenB, dummySubtokenB[0])).andReturn();
// verify the subtokens have been updated
clientAuthorizationTokenEntities = this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, clientAuthorization.id());
assertEquals(2, clientAuthorizationTokenEntities.size());
Set<String> savedSubtokens = this.apiSubTokenRepository.findAllByAccountIdGw2AccountIdsAndGw2ApiPermissionsBitSet(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd), Gw2ApiPermission.toBitSet(Set.of(Gw2ApiPermission.ACCOUNT))).stream().map(ApiSubTokenEntity::gw2ApiSubtoken).collect(Collectors.toSet());
assertEquals(2, savedSubtokens.size());
assertTrue(savedSubtokens.contains(dummySubtokenA[0]));
assertTrue(savedSubtokens.contains(dummySubtokenB[0]));
// verify the validity status has been saved
final List<ApiTokenEntity> apiTokenEntities = this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd));
assertEquals(2, apiTokenEntities.size());
assertTrue(apiTokenEntities.get(0).isValid());
assertInstantEquals(testingClock.instant(), apiTokenEntities.get(0).lastValidCheckTime());
assertTrue(apiTokenEntities.get(1).isValid());
assertInstantEquals(testingClock.instant(), apiTokenEntities.get(1).lastValidCheckTime());
// verify the access token
JsonNode tokenResponse = assertTokenResponse(result, () -> Map.of(this.gw2AccountId1st, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "First", "token", dummySubtokenA[0])), this.gw2AccountId2nd, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "Second", "token", dummySubtokenB[0]))));
// remove all Root-Tokens for this authorization
for (ClientAuthorizationTokenEntity clientAuthorizationTokenEntity : clientAuthorizationTokenEntities) {
this.apiTokenRepository.deleteByAccountIdAndGw2AccountId(clientAuthorizationTokenEntity.accountId(), clientAuthorizationTokenEntity.gw2AccountId());
}
// retrieve a new access token using the refresh token
testingClock = Clock.offset(testingClock, Duration.ofMinutes(31L));
this.oAuth2TokenCustomizerService.setClock(testingClock);
final String refreshToken = tokenResponse.get("refresh_token").textValue();
performRetrieveTokensByRefreshToken(clientRegistrationCreation, refreshToken).andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").isString()).andExpect(jsonPath("$.access_token").doesNotExist()).andExpect(jsonPath("$.refresh_token").doesNotExist()).andReturn();
}
use of com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity in project oauth2-server by gw2auth.
the class OAuth2ServerTest method consentSubmitWithGw2AuthVerifiedScope.
@WithGw2AuthLogin
public void consentSubmitWithGw2AuthVerifiedScope(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final ClientRegistrationCreation clientRegistrationCreation = createClientRegistration();
final ClientRegistration clientRegistration = clientRegistrationCreation.clientRegistration();
// perform authorization request (which should redirect to the consent page)
MvcResult result = performAuthorizeWithClient(session, clientRegistration, List.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
// submit the consent
final String tokenA = TestHelper.randomRootToken();
final String tokenB = TestHelper.randomRootToken();
final String tokenC = TestHelper.randomRootToken();
result = performSubmitConsent(session, clientRegistration, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), tokenA, tokenB, tokenC).andReturn();
// verify the consent has been saved
final ClientConsentEntity clientConsentEntity = this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientRegistration.id()).orElse(null);
assertNotNull(clientConsentEntity);
assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE), clientConsentEntity.authorizedScopes());
// verify the authorization has been saved
final List<ClientAuthorizationEntity> authorizations = this.clientAuthorizationRepository.findAllByAccountIdAndClientRegistrationId(accountId, clientConsentEntity.clientRegistrationId());
assertEquals(1, authorizations.size());
final ClientAuthorizationEntity clientAuthorization = authorizations.get(0);
assertEquals(Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE), clientAuthorization.authorizedScopes());
List<ClientAuthorizationTokenEntity> clientAuthorizationTokenEntities = this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, clientAuthorization.id());
assertEquals(2, clientAuthorizationTokenEntities.size());
// save account verification for one account
this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(this.gw2AccountId1st, accountId));
// set testing clock to token customizer
Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
this.oAuth2TokenCustomizerService.setClock(testingClock);
// retrieve the initial access and refresh token
final String[] dummySubtokenA = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId1st, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
final String[] dummySubtokenB = new String[] { TestHelper.createSubtokenJWT(this.gw2AccountId2nd, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(30L)) };
result = performRetrieveTokenByCode(clientRegistrationCreation, URI.create(Objects.requireNonNull(result.getResponse().getRedirectedUrl())), Map.of(tokenA, dummySubtokenA[0], tokenB, dummySubtokenB[0]), Set.of(Gw2ApiPermission.ACCOUNT)).andExpectAll(expectValidTokenResponse(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
// verify the authorized tokens have been updated
Set<String> savedSubtokens = this.apiSubTokenRepository.findAllByAccountIdGw2AccountIdsAndGw2ApiPermissionsBitSet(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd), Gw2ApiPermission.toBitSet(Set.of(Gw2ApiPermission.ACCOUNT))).stream().map(ApiSubTokenEntity::gw2ApiSubtoken).collect(Collectors.toSet());
assertEquals(2, savedSubtokens.size());
assertTrue(savedSubtokens.contains(dummySubtokenA[0]));
assertTrue(savedSubtokens.contains(dummySubtokenB[0]));
// verify the validity status has been saved
final List<ApiTokenEntity> apiTokenEntities = this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(this.gw2AccountId1st, this.gw2AccountId2nd));
assertEquals(2, apiTokenEntities.size());
assertTrue(apiTokenEntities.get(0).isValid());
assertInstantEquals(testingClock.instant(), apiTokenEntities.get(0).lastValidCheckTime());
assertTrue(apiTokenEntities.get(1).isValid());
assertInstantEquals(testingClock.instant(), apiTokenEntities.get(1).lastValidCheckTime());
// verify the access token
JsonNode tokenResponse = assertTokenResponse(result, () -> Map.of(this.gw2AccountId1st, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "First", "token", dummySubtokenA[0], "verified", true)), this.gw2AccountId2nd, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "Second", "token", dummySubtokenB[0], "verified", false))));
// remove the verification for the first account and save one for the second
this.gw2AccountVerificationRepository.deleteById(this.gw2AccountId1st);
this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(this.gw2AccountId2nd, accountId));
// retrieve a new access token using the refresh token
final String refreshToken = tokenResponse.get("refresh_token").textValue();
result = performRetrieveTokensByRefreshToken(clientRegistrationCreation, refreshToken).andExpectAll(expectValidTokenResponse(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE)).andReturn();
tokenResponse = assertTokenResponse(result, () -> Map.of(this.gw2AccountId1st, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "First", "token", dummySubtokenA[0], "verified", false)), this.gw2AccountId2nd, new com.nimbusds.jose.shaded.json.JSONObject(Map.of("name", "Second", "token", dummySubtokenB[0], "verified", true))));
}
use of com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity in project oauth2-server by gw2auth.
the class ApiTokenServiceImpl method addApiToken.
@Override
@Transactional(noRollbackFor = ApiTokenOwnershipMismatchException.class)
public ApiToken addApiToken(long accountId, String gw2ApiToken) {
final Gw2TokenInfo gw2TokenInfo = this.gw2ApiService.getTokenInfo(gw2ApiToken);
if (!gw2TokenInfo.permissions().contains(Gw2ApiPermission.ACCOUNT)) {
throw new ApiTokenServiceException(ApiTokenServiceException.MISSING_ACCOUNT_PERMISSION, HttpStatus.BAD_REQUEST);
}
final Gw2Account gw2Account = this.gw2ApiService.getAccount(gw2ApiToken);
final Optional<ApiTokenEntity> optionalGw2ApiTokenEntity = this.apiTokenRepository.findByAccountIdAndGw2AccountId(accountId, gw2Account.id());
if (optionalGw2ApiTokenEntity.isPresent()) {
throw new ApiTokenServiceException(ApiTokenServiceException.API_TOKEN_ALREADY_EXISTS, HttpStatus.BAD_REQUEST);
}
final OptionalLong optional = this.verificationService.getVerifiedAccountId(gw2Account.id());
if (optional.isPresent() && optional.getAsLong() != accountId) {
this.apiTokenRepository.deleteByAccountIdAndGw2AccountId(accountId, gw2Account.id());
throw new ApiTokenOwnershipMismatchException();
}
final Instant now = this.clock.instant();
return ApiToken.fromEntity(this.apiTokenRepository.save(new ApiTokenEntity(accountId, gw2Account.id(), now, gw2ApiToken, gw2TokenInfo.permissions().stream().map(Gw2ApiPermission::gw2).collect(Collectors.toSet()), now, true, gw2Account.name())));
}
use of com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity in project oauth2-server by gw2auth.
the class ClientAuthorizationControllerTest method deleteClientAuthorization.
@WithGw2AuthLogin
public void deleteClientAuthorization(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
// create client
final ClientRegistrationEntity client = this.testHelper.createClientRegistration(accountId, "Client");
// create consent
this.testHelper.createClientConsent(accountId, client.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE));
// create 2 authorizations
final ClientAuthorizationEntity authorization1 = this.testHelper.createClientAuthorization(accountId, client.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2()));
final ClientAuthorizationEntity authorization2 = this.testHelper.createClientAuthorization(accountId, client.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE));
// insert tokens for these authorizations
final ApiTokenEntity tokenA = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "Token A");
final ApiTokenEntity tokenB = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "Token B");
final ApiTokenEntity tokenC = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "Token C");
final ApiTokenEntity tokenD = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "Token D");
this.testHelper.createClientAuthorizationTokens(accountId, authorization1.id(), tokenA.gw2AccountId(), tokenD.gw2AccountId());
this.testHelper.createClientAuthorizationTokens(accountId, authorization2.id(), tokenA.gw2AccountId(), tokenB.gw2AccountId(), tokenC.gw2AccountId());
// delete second authorization
this.mockMvc.perform(delete("/api/client/authorization/_/{clientAuthorizationId}", authorization2.id()).with(csrf()).session(session)).andExpect(status().isOk());
// verify the authorization has been deleted
assertTrue(this.clientAuthorizationRepository.findByAccountIdAndId(accountId, authorization2.id()).isEmpty());
// verify the first authorization is still present
assertTrue(this.clientAuthorizationRepository.findByAccountIdAndId(accountId, authorization1.id()).isPresent());
}
use of com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity in project oauth2-server by gw2auth.
the class ApiTokenControllerTest method getApiTokens.
@WithGw2AuthLogin
public void getApiTokens(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final ApiTokenEntity apiTokenA = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Set.of(Gw2ApiPermission.ACCOUNT, Gw2ApiPermission.GUILDS), "TokenA");
final ApiTokenEntity apiTokenB = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Set.of(Gw2ApiPermission.TRADINGPOST), "TokenB");
final ApiTokenEntity apiTokenC = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Set.of(Gw2ApiPermission.BUILDS, Gw2ApiPermission.PROGRESSION), "TokenC");
this.testHelper.createAccountVerification(accountId, apiTokenB.gw2AccountId());
final ClientRegistrationEntity clientRegistrationA = this.testHelper.createClientRegistration(accountId, "ClientA");
final ClientRegistrationEntity clientRegistrationB = this.testHelper.createClientRegistration(accountId, "ClientB");
final ClientConsentEntity clientConsentA = this.testHelper.createClientConsent(accountId, clientRegistrationA.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2()));
final ClientConsentEntity clientConsentB = this.testHelper.createClientConsent(accountId, clientRegistrationB.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2()));
final String authorizationIdA = this.testHelper.createClientAuthorization(accountId, clientConsentA.clientRegistrationId(), clientConsentA.authorizedScopes()).id();
final String authorizationIdB = this.testHelper.createClientAuthorization(accountId, clientConsentB.clientRegistrationId(), clientConsentB.authorizedScopes()).id();
this.testHelper.createClientAuthorizationTokens(accountId, authorizationIdA, apiTokenB.gw2AccountId(), apiTokenC.gw2AccountId());
this.testHelper.createClientAuthorizationTokens(accountId, authorizationIdB, apiTokenC.gw2AccountId());
final String responseJson = this.mockMvc.perform(get("/api/token").session(session)).andExpect(status().isOk()).andExpect(jsonPath("$.length()").value("3")).andReturn().getResponse().getContentAsString();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode responseNode = mapper.readTree(responseJson);
assertTrue(responseNode.isArray());
final Map<UUID, ExpectedApiToken> expectedApiTokens = new HashMap<>(Map.of(apiTokenA.gw2AccountId(), new ExpectedApiToken(apiTokenA, false, List.of()), apiTokenB.gw2AccountId(), new ExpectedApiToken(apiTokenB, true, List.of(clientRegistrationA)), apiTokenC.gw2AccountId(), new ExpectedApiToken(apiTokenC, false, List.of(clientRegistrationA, clientRegistrationB))));
for (int i = 0; i < responseNode.size(); i++) {
final JsonNode tokenNode = responseNode.get(i);
final UUID gw2AccountId = UUID.fromString(tokenNode.get("gw2AccountId").textValue());
final ExpectedApiToken expectedApiToken = expectedApiTokens.remove(gw2AccountId);
assertExpectedApiToken(expectedApiToken, tokenNode);
}
assertTrue(expectedApiTokens.isEmpty());
}
Aggregations