use of com.gw2auth.oauth2.server.service.Gw2ApiPermission in project oauth2-server by gw2auth.
the class ApiTokenControllerTest method assertExpectedApiToken.
private void assertExpectedApiToken(ExpectedApiToken expectedApiToken, String expectedDisplayName, String expectedGw2ApiToken, Set<String> expectedGw2ApiPermissions, JsonNode apiTokenNode) {
assertNotNull(expectedApiToken);
assertEquals(expectedApiToken.apiToken().gw2AccountId(), UUID.fromString(apiTokenNode.get("gw2AccountId").textValue()));
assertInstantEquals(expectedApiToken.apiToken().creationTime(), apiTokenNode.get("creationTime").textValue());
assertEquals(expectedGw2ApiToken, apiTokenNode.get("gw2ApiToken").textValue());
assertEquals(expectedDisplayName, apiTokenNode.get("displayName").textValue());
assertTrue(apiTokenNode.get("isValid").booleanValue());
assertEquals(expectedApiToken.isVerified(), apiTokenNode.get("isVerified").booleanValue());
// gw2 api permissions
expectedGw2ApiPermissions = new HashSet<>(expectedGw2ApiPermissions);
final JsonNode gw2ApiPermissionsNode = apiTokenNode.get("gw2ApiPermissions");
assertTrue(gw2ApiPermissionsNode.isArray());
for (int j = 0; j < gw2ApiPermissionsNode.size(); j++) {
if (!expectedGw2ApiPermissions.remove(gw2ApiPermissionsNode.get(j).textValue())) {
fail("Received unexpected gw2ApiPermission");
}
}
assertTrue(expectedGw2ApiPermissions.isEmpty());
// authorizations
final Map<UUID, ClientRegistrationEntity> expectedAuthorizations = expectedApiToken.authorizations().stream().collect(Collectors.toMap(ClientRegistrationEntity::clientId, Function.identity()));
final JsonNode authorizationsNode = apiTokenNode.get("authorizations");
assertTrue(authorizationsNode.isArray());
for (int j = 0; j < authorizationsNode.size(); j++) {
final JsonNode authorizationNode = authorizationsNode.get(j);
final UUID clientId = UUID.fromString(authorizationNode.get("clientId").textValue());
final ClientRegistrationEntity expectedAuthorization = expectedAuthorizations.remove(clientId);
assertNotNull(expectedAuthorization);
assertEquals(expectedAuthorization.displayName(), authorizationNode.get("displayName").textValue());
}
assertTrue(expectedAuthorizations.isEmpty());
}
use of com.gw2auth.oauth2.server.service.Gw2ApiPermission in project oauth2-server by gw2auth.
the class VerificationControllerTest method prepareGw2RestServerForTokenInfoRequest.
private void prepareGw2RestServerForTokenInfoRequest(String gw2ApiToken, String apiTokenName, Set<Gw2ApiPermission> gw2ApiPermissions) {
this.gw2RestServer.expect(requestTo(new StringStartsWith("/v2/tokeninfo"))).andExpect(method(HttpMethod.GET)).andExpect(MockRestRequestMatchers.header("Authorization", new IsEqual<>("Bearer " + gw2ApiToken))).andRespond((request) -> {
final MockClientHttpResponse response = new MockClientHttpResponse(new JSONObject(Map.of("name", apiTokenName, "permissions", gw2ApiPermissions.stream().map(Gw2ApiPermission::gw2).collect(Collectors.toList()))).toString().getBytes(StandardCharsets.UTF_8), HttpStatus.OK);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
}
use of com.gw2auth.oauth2.server.service.Gw2ApiPermission in project oauth2-server by gw2auth.
the class Gw2ApiServiceImpl method createSubToken.
@Override
public Gw2SubToken createSubToken(String token, Set<Gw2ApiPermission> permissions, Instant expirationTime) {
final MultiValueMap<String, String> query = new LinkedMultiValueMap<>();
query.add("permissions", permissions.stream().map(Gw2ApiPermission::gw2).collect(Collectors.joining(",")));
// ISO-8601
query.add("expire", expirationTime.toString());
final String jwtString = getFromAPI("/v2/createsubtoken", query, token, GW2CreateSubToken.class).subtoken();
final Set<Gw2ApiPermission> gw2ApiPermissions;
try {
final JWT jwt = JWTParser.parse(jwtString);
gw2ApiPermissions = Optional.ofNullable(jwt.getJWTClaimsSet().getStringListClaim("permissions")).stream().flatMap(List::stream).flatMap((permission) -> Gw2ApiPermission.fromGw2(permission).stream()).collect(Collectors.toSet());
} catch (ParseException e) {
throw new Gw2ApiServiceException(Gw2ApiServiceException.SUBTOKEN_JWT_PARSING_ERROR);
}
return new Gw2SubToken(jwtString, gw2ApiPermissions);
}
use of com.gw2auth.oauth2.server.service.Gw2ApiPermission 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.service.Gw2ApiPermission in project oauth2-server by gw2auth.
the class OAuth2ConsentController method oauth2ConsentInformation.
@GetMapping(value = "/api/oauth2/consent", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuth2ConsentInfoResponse oauth2ConsentInformation(@AuthenticationPrincipal Gw2AuthUser user, @RequestParam(OAuth2ParameterNames.CLIENT_ID) UUID clientId, @RequestParam(OAuth2ParameterNames.STATE) String state, @RequestParam(OAuth2ParameterNames.SCOPE) String scopes) {
final ClientRegistration clientRegistration = this.clientRegistrationService.getClientRegistration(clientId).orElseThrow();
final Set<String> requestedScopes = Utils.split(scopes, " ").collect(Collectors.toSet());
final Set<Gw2ApiPermission> requestedGw2ApiPermissions = requestedScopes.stream().flatMap((scope) -> Gw2ApiPermission.fromOAuth2(scope).stream()).collect(Collectors.toSet());
final boolean requestedVerifiedInformation = requestedScopes.contains(ClientConsentService.GW2AUTH_VERIFIED_SCOPE);
final List<ApiToken> apiTokens = this.apiTokenService.getApiTokens(user.getAccountId());
final List<OAuth2ConsentInfoResponse.MinimalApiToken> apiTokensWithSufficientPermissionResponses = new ArrayList<>();
final List<OAuth2ConsentInfoResponse.MinimalApiToken> apiTokensWithInsufficientPermissionResponses = new ArrayList<>();
final Set<UUID> verifiedGw2AccountIds;
if (apiTokens.isEmpty() || !requestedVerifiedInformation) {
verifiedGw2AccountIds = Set.of();
} else {
verifiedGw2AccountIds = this.verificationService.getVerifiedGw2AccountIds(user.getAccountId());
}
for (ApiToken apiToken : apiTokens) {
final OAuth2ConsentInfoResponse.MinimalApiToken resultApiToken = OAuth2ConsentInfoResponse.MinimalApiToken.create(apiToken, verifiedGw2AccountIds.contains(apiToken.gw2AccountId()));
if (apiToken.gw2ApiPermissions().containsAll(requestedGw2ApiPermissions)) {
apiTokensWithSufficientPermissionResponses.add(resultApiToken);
} else {
apiTokensWithInsufficientPermissionResponses.add(resultApiToken);
}
}
final Set<UUID> previouslyConsentedGw2AccountIds = this.clientAuthorizationService.getLatestClientAuthorization(user.getAccountId(), clientRegistration.id(), requestedScopes).map(ClientAuthorization::gw2AccountIds).orElseGet(Set::of);
final MultiValueMap<String, String> submitFormParameters = new LinkedMultiValueMap<>();
submitFormParameters.set(OAuth2ParameterNames.CLIENT_ID, clientId.toString());
submitFormParameters.set(OAuth2ParameterNames.STATE, state);
requestedScopes.forEach((scope) -> submitFormParameters.add(OAuth2ParameterNames.SCOPE, scope));
final String cancelUri = UriComponentsBuilder.fromPath("/api/oauth2/consent-deny").replaceQueryParam(OAuth2ParameterNames.CLIENT_ID, clientId).replaceQueryParam(OAuth2ParameterNames.STATE, state).toUriString();
return new OAuth2ConsentInfoResponse(ClientRegistrationPublicResponse.create(clientRegistration), requestedGw2ApiPermissions, requestedVerifiedInformation, "/oauth2/authorize", submitFormParameters, cancelUri, apiTokensWithSufficientPermissionResponses, apiTokensWithInsufficientPermissionResponses, previouslyConsentedGw2AccountIds);
}
Aggregations