use of com.gw2auth.oauth2.server.service.client.consent.ClientConsent in project oauth2-server by gw2auth.
the class OAuth2TokenCustomizerService method customize.
private void customize(JwtEncodingContext ctx, String clientAuthorizationId, long accountId, long clientRegistrationId) {
final ClientAuthorization clientAuthorization = this.clientAuthorizationService.getClientAuthorization(accountId, clientAuthorizationId).orElse(null);
final ClientConsent clientConsent = this.clientConsentService.getClientConsent(accountId, clientRegistrationId).orElse(null);
if (clientAuthorization == null || clientConsent == null) {
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED));
}
try (ClientConsentService.LoggingContext logging = this.clientConsentService.log(accountId, clientRegistrationId, ClientConsentService.LogType.ACCESS_TOKEN)) {
final Set<String> effectiveAuthorizedScopes = new HashSet<>(clientConsent.authorizedScopes());
effectiveAuthorizedScopes.retainAll(clientAuthorization.authorizedScopes());
final Set<UUID> authorizedGw2AccountIds = clientAuthorization.gw2AccountIds();
final Set<Gw2ApiPermission> authorizedGw2ApiPermissions = effectiveAuthorizedScopes.stream().flatMap((scope) -> Gw2ApiPermission.fromOAuth2(scope).stream()).collect(Collectors.toSet());
if (authorizedGw2ApiPermissions.isEmpty() || authorizedGw2AccountIds.isEmpty()) {
logging.log("The Consent has been removed: responding with ACCESS_DENIED");
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED));
}
final List<ApiToken> authorizedRootTokens = this.apiTokenService.getApiTokens(accountId, authorizedGw2AccountIds);
// in theory, this should not happen since authorized-tokens and root-tokens are related via foreign key
if (authorizedRootTokens.isEmpty()) {
logging.log("All linked Root-API-Tokens have been removed: responding with ACCESS_DENIED");
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED));
}
final Set<UUID> verifiedGw2AccountIds;
final boolean hasGw2AuthVerifiedScope = effectiveAuthorizedScopes.contains(ClientConsentService.GW2AUTH_VERIFIED_SCOPE);
if (hasGw2AuthVerifiedScope) {
verifiedGw2AccountIds = this.verificationService.getVerifiedGw2AccountIds(accountId);
} else {
verifiedGw2AccountIds = Set.of();
}
final int gw2ApiPermissionsBitSet = Gw2ApiPermission.toBitSet(authorizedGw2ApiPermissions);
final List<ApiSubTokenEntity> savedSubTokens = this.apiSubTokenRepository.findAllByAccountIdGw2AccountIdsAndGw2ApiPermissionsBitSet(accountId, authorizedGw2AccountIds, gw2ApiPermissionsBitSet);
final Instant atLeastValidUntil = this.clock.instant().plus(AUTHORIZED_TOKEN_MIN_EXCESS_TIME);
final Map<UUID, ApiSubTokenEntity> savedSubTokenByGw2AccountId = new HashMap<>(savedSubTokens.size());
final Map<Instant, Integer> savedSubTokenCountByExpirationTime = new HashMap<>(savedSubTokens.size());
Instant expirationTimeWithMostSavedSubTokens = null;
for (ApiSubTokenEntity savedSubToken : savedSubTokens) {
if (savedSubToken.expirationTime().isAfter(atLeastValidUntil)) {
savedSubTokenByGw2AccountId.put(savedSubToken.gw2AccountId(), savedSubToken);
final int groupCount = savedSubTokenCountByExpirationTime.merge(savedSubToken.expirationTime(), 1, Integer::sum);
if (expirationTimeWithMostSavedSubTokens == null || groupCount > savedSubTokenCountByExpirationTime.get(expirationTimeWithMostSavedSubTokens)) {
expirationTimeWithMostSavedSubTokens = savedSubToken.expirationTime();
}
}
}
final Instant expirationTime;
if (expirationTimeWithMostSavedSubTokens != null) {
// if existing subtokens which are still valid for at least AUTHORIZED_TOKEN_MIN_EXCESS_TIME could be found, use this expiration time
ctx.getClaims().expiresAt(expirationTimeWithMostSavedSubTokens);
expirationTime = expirationTimeWithMostSavedSubTokens;
} else {
expirationTime = ctx.getClaims().build().getExpiresAt();
}
final Map<UUID, Map<String, Object>> tokensForJWT = new LinkedHashMap<>(authorizedGw2AccountIds.size());
final Batch.Builder<Map<UUID, Pair<ApiToken, Gw2SubToken>>> batch = Batch.builder();
for (ApiToken authorizedRootToken : authorizedRootTokens) {
final Map<String, Object> tokenForJWT = new HashMap<>(3);
final UUID gw2AccountId = authorizedRootToken.gw2AccountId();
final String displayName = authorizedRootToken.displayName();
final ApiSubTokenEntity potentialExistingSubToken = savedSubTokenByGw2AccountId.get(gw2AccountId);
tokenForJWT.put("name", displayName);
if (potentialExistingSubToken != null && potentialExistingSubToken.expirationTime().equals(expirationTime)) {
tokenForJWT.put("token", potentialExistingSubToken.gw2ApiSubtoken());
logging.log("Using existing and valid Subtoken for the Root-API-Token named '%s'", displayName);
} else {
if (authorizedRootToken.gw2ApiPermissions().containsAll(authorizedGw2ApiPermissions)) {
final String gw2ApiToken = authorizedRootToken.gw2ApiToken();
batch.add((timeout) -> this.gw2APIService.withTimeout(timeout, () -> this.gw2APIService.createSubToken(gw2ApiToken, authorizedGw2ApiPermissions, expirationTime)), (accumulator, context) -> {
try {
accumulator.put(gw2AccountId, new Pair<>(authorizedRootToken, context.get()));
} catch (ExecutionException | TimeoutException e) {
accumulator.put(gw2AccountId, new Pair<>(authorizedRootToken, null));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
accumulator.put(gw2AccountId, new Pair<>(authorizedRootToken, null));
}
return accumulator;
});
} else {
logging.log("The Root-API-Token named '%s' has less permissions than the authorization", displayName);
}
}
if (hasGw2AuthVerifiedScope) {
final boolean isVerified = verifiedGw2AccountIds.contains(gw2AccountId);
tokenForJWT.put("verified", isVerified);
logging.log("Including verified=%s for the Root-API-Token named '%s'", isVerified, displayName);
}
tokensForJWT.put(gw2AccountId, tokenForJWT);
}
final Map<UUID, Pair<ApiToken, Gw2SubToken>> result = batch.build().execute(this.gw2ApiClientExecutorService, HashMap::new, 10L, TimeUnit.SECONDS);
final List<ApiTokenValidityUpdate> apiTokenValidityUpdates = new ArrayList<>(result.size());
final List<ApiSubTokenEntity> apiSubTokenEntitiesToSave = new ArrayList<>(result.size());
for (Map.Entry<UUID, Pair<ApiToken, Gw2SubToken>> entry : result.entrySet()) {
final UUID gw2AccountId = entry.getKey();
final Map<String, Object> tokenForJWT = tokensForJWT.get(gw2AccountId);
final String displayName = entry.getValue().v1().displayName();
final Gw2SubToken gw2SubToken = entry.getValue().v2();
if (gw2SubToken != null) {
if (gw2SubToken.permissions().equals(authorizedGw2ApiPermissions)) {
apiSubTokenEntitiesToSave.add(new ApiSubTokenEntity(accountId, gw2AccountId, gw2ApiPermissionsBitSet, gw2SubToken.value(), expirationTime));
tokenForJWT.put("token", gw2SubToken.value());
logging.log("Added Subtoken for the Root-API-Token named '%s'", displayName);
} else {
tokenForJWT.put("error", "Failed to obtain new subtoken");
logging.log("The retrieved Subtoken for the Root-API-Token named '%s' appears to have less permissions than the authorization", displayName);
}
apiTokenValidityUpdates.add(new ApiTokenValidityUpdate(accountId, gw2AccountId, true));
} else {
tokenForJWT.put("error", "Failed to obtain new subtoken");
logging.log("Failed to retrieve a new Subtoken for the Root-API-Token named '%s' from the GW2-API", displayName);
}
}
this.apiTokenService.updateApiTokensValid(this.clock.instant(), apiTokenValidityUpdates);
this.apiSubTokenRepository.saveAll(apiSubTokenEntitiesToSave);
customize(ctx, clientConsent.accountSub(), authorizedGw2ApiPermissions, tokensForJWT);
}
}
use of com.gw2auth.oauth2.server.service.client.consent.ClientConsent in project oauth2-server by gw2auth.
the class ClientConsentController method getClientConsents.
@GetMapping(value = "/api/client/consent", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ClientConsentResponse> getClientConsents(@AuthenticationPrincipal Gw2AuthUser user) {
final List<ClientConsent> clientConsents = this.clientConsentService.getClientConsents(user.getAccountId());
// get all client registration ids for batch lookup
final Set<Long> clientRegistrationIds = clientConsents.stream().map(ClientConsent::clientRegistrationId).collect(Collectors.toSet());
final Map<Long, ClientRegistration> clientRegistrationById = this.clientRegistrationService.getClientRegistrations(clientRegistrationIds).stream().collect(Collectors.toMap(ClientRegistration::id, Function.identity()));
final List<ClientConsentResponse> result = new ArrayList<>(clientConsents.size());
for (ClientConsent clientConsent : clientConsents) {
final ClientRegistration clientRegistration = clientRegistrationById.get(clientConsent.clientRegistrationId());
// only happens if theres a race, but dont want to add locks here
if (clientRegistration != null) {
result.add(ClientConsentResponse.create(clientConsent, clientRegistration));
}
}
return result;
}
use of com.gw2auth.oauth2.server.service.client.consent.ClientConsent in project oauth2-server by gw2auth.
the class ClientConsentControllerTest method getClientConsents.
@WithGw2AuthLogin
public void getClientConsents(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final ClientRegistrationEntity clientRegistrationA = this.testHelper.createClientRegistration(accountId, "Name");
final ClientRegistrationEntity clientRegistrationC = this.testHelper.createClientRegistration(accountId, "Name");
final ClientConsentEntity clientConsentA = this.testHelper.createClientConsent(accountId, clientRegistrationA.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), ClientConsentService.GW2AUTH_VERIFIED_SCOPE));
final ClientConsentEntity clientConsentB = this.testHelper.createClientConsent(accountId, clientRegistrationC.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2(), Gw2ApiPermission.GUILDS.oauth2()));
final String jsonResponse = this.mockMvc.perform(get("/api/client/consent").session(session)).andExpect(status().isOk()).andExpect(jsonPath("$.length()").value(2)).andReturn().getResponse().getContentAsString();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(jsonResponse);
assertTrue(node.isArray());
boolean foundAuthorizationA = false;
boolean foundAuthorizationC = false;
for (int i = 0; i < node.size(); i++) {
final JsonNode element = node.get(i);
final JsonNode clientRegistrationNode = element.get("clientRegistration");
final ClientRegistrationEntity clientRegistration;
final ClientConsentEntity clientConsent;
if (clientRegistrationNode.get("clientId").textValue().equals(clientRegistrationA.clientId().toString())) {
if (foundAuthorizationA) {
fail("authorization A appeared at least twice in the response");
return;
} else {
foundAuthorizationA = true;
clientRegistration = clientRegistrationA;
clientConsent = clientConsentA;
}
} else if (clientRegistrationNode.get("clientId").textValue().equals(clientRegistrationC.clientId().toString())) {
if (foundAuthorizationC) {
fail("authorization C appeared at least twice in the response");
return;
} else {
foundAuthorizationC = true;
clientRegistration = clientRegistrationC;
clientConsent = clientConsentB;
}
} else {
fail("unknown authorization appeared in response");
return;
}
// registration
assertInstantEquals(clientRegistration.creationTime(), clientRegistrationNode.get("creationTime").textValue());
assertEquals(clientRegistration.displayName(), clientRegistrationNode.get("displayName").textValue());
// accountsub
assertEquals(clientConsent.accountSub().toString(), element.get("accountSub").textValue());
// authorized scopes
final Set<String> expectedScopes = new HashSet<>(clientConsent.authorizedScopes());
final JsonNode authorizedGw2ApiPermissionsNode = element.get("authorizedGw2ApiPermissions");
assertTrue(authorizedGw2ApiPermissionsNode.isArray());
for (int j = 0; j < authorizedGw2ApiPermissionsNode.size(); j++) {
final Gw2ApiPermission gw2ApiPermission = Gw2ApiPermission.fromGw2(authorizedGw2ApiPermissionsNode.get(j).textValue()).orElseThrow();
if (!expectedScopes.remove(gw2ApiPermission.oauth2())) {
fail("got unexpected scope in authorization");
}
}
if (element.get("authorizedVerifiedInformation").booleanValue()) {
if (!expectedScopes.remove(ClientConsentService.GW2AUTH_VERIFIED_SCOPE)) {
fail("got unexpected scope in authorization");
}
}
assertTrue(expectedScopes.isEmpty());
}
assertTrue(foundAuthorizationA);
assertTrue(foundAuthorizationC);
}
use of com.gw2auth.oauth2.server.service.client.consent.ClientConsent in project oauth2-server by gw2auth.
the class ClientConsentControllerTest method deleteClientConsent.
@WithGw2AuthLogin
public void deleteClientConsent(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final ClientRegistrationEntity clientRegistrationA = this.testHelper.createClientRegistration(accountId, "Name");
final ClientRegistrationEntity clientRegistrationB = this.testHelper.createClientRegistration(accountId, "Name");
final ApiTokenEntity apiTokenA = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "TokenNameA");
final ApiTokenEntity apiTokenB = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "TokenNameB");
final ApiTokenEntity apiTokenC = this.testHelper.createApiToken(accountId, UUID.randomUUID(), Gw2ApiPermission.all(), "TokenNameC");
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(), Gw2ApiPermission.GUILDS.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();
// tokens for authorization A
this.testHelper.createClientAuthorizationTokens(accountId, authorizationIdA, apiTokenA.gw2AccountId(), apiTokenC.gw2AccountId());
// tokens for authorization B
this.testHelper.createClientAuthorizationTokens(accountId, authorizationIdB, apiTokenB.gw2AccountId());
// logs for authorization A
this.testHelper.createClientLog(accountId, clientConsentA.clientRegistrationId(), "SomeTypeA", List.of());
this.testHelper.createClientLog(accountId, clientConsentA.clientRegistrationId(), "SomeTypeA", List.of());
// logs for authorization B
this.testHelper.createClientLog(accountId, clientConsentB.clientRegistrationId(), "SomeTypeA", List.of());
// delete authorization A
this.mockMvc.perform(delete("/api/client/consent/{clientId}", clientRegistrationA.clientId()).session(session).with(csrf())).andExpect(status().isOk());
// entity should still be there
ClientConsentEntity clientConsent = this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientConsentA.clientRegistrationId()).orElse(null);
assertNotNull(clientConsent);
assertNotEquals(clientConsentA, clientConsent);
assertTrue(clientConsent.authorizedScopes().isEmpty());
assertEquals(clientConsentA.accountSub(), clientConsent.accountSub());
// logs and tokens should be deleted
assertTrue(this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, authorizationIdA).isEmpty());
assertTrue(this.clientConsentLogRepository.findByAccountIdAndClientId(accountId, clientRegistrationA.clientId(), 0, 10).findAny().isEmpty());
// authorization B should still be there (and unchanged)
clientConsent = this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientConsentB.clientRegistrationId()).orElse(null);
assertEquals(clientConsentB, clientConsent);
// logs and tokens of B should still be there
assertEquals(1, this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, authorizationIdB).size());
assertEquals(1L, this.clientConsentLogRepository.findByAccountIdAndClientId(accountId, clientRegistrationB.clientId(), 0, 10).count());
}
use of com.gw2auth.oauth2.server.service.client.consent.ClientConsent in project oauth2-server by gw2auth.
the class ApiTokenControllerTest method deleteApiToken.
@WithGw2AuthLogin
public void deleteApiToken(MockHttpSession session) throws Exception {
final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
final UUID gw2AccountId = UUID.randomUUID();
this.testHelper.createApiToken(accountId, gw2AccountId, Set.of(Gw2ApiPermission.ACCOUNT, Gw2ApiPermission.GUILDS), "TokenA");
// verified
this.testHelper.createAccountVerification(accountId, gw2AccountId);
// register a client
final ClientRegistrationEntity clientRegistration = this.testHelper.createClientRegistration(accountId, "ClientA");
// authorize the client
final ClientConsentEntity clientConsent = this.testHelper.createClientConsent(accountId, clientRegistration.id(), Set.of(Gw2ApiPermission.ACCOUNT.oauth2()));
final String authorizationId = this.testHelper.createClientAuthorization(accountId, clientConsent.clientRegistrationId(), clientConsent.authorizedScopes()).id();
// use this token to the authorization
this.testHelper.createClientAuthorizationToken(accountId, authorizationId, gw2AccountId);
this.mockMvc.perform(delete("/api/token/{gw2AccountId}", gw2AccountId).session(session).with(csrf())).andExpect(status().isOk());
// the token should be deleted
assertTrue(this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(gw2AccountId)).isEmpty());
// the verification should still be there
assertTrue(this.gw2AccountVerificationRepository.findById(gw2AccountId).isPresent());
// the token should no longer be in the authorization
assertTrue(this.clientAuthorizationTokenRepository.findAllByAccountIdAndClientAuthorizationId(accountId, authorizationId).isEmpty());
// the authorization should still be there
assertTrue(this.clientConsentRepository.findByAccountIdAndClientRegistrationId(accountId, clientConsent.clientRegistrationId()).isPresent());
}
Aggregations