Search in sources :

Example 6 with Gw2ApiPermission

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());
}
Also used : ClientRegistrationEntity(com.gw2auth.oauth2.server.repository.client.registration.ClientRegistrationEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 7 with Gw2ApiPermission

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;
    });
}
Also used : Gw2ApiPermission(com.gw2auth.oauth2.server.service.Gw2ApiPermission) StringStartsWith(org.hamcrest.core.StringStartsWith) JSONObject(org.json.JSONObject) MockClientHttpResponse(org.springframework.mock.http.client.MockClientHttpResponse)

Example 8 with Gw2ApiPermission

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);
}
Also used : Gw2ApiPermission(com.gw2auth.oauth2.server.service.Gw2ApiPermission) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) JWT(com.nimbusds.jwt.JWT) ParseException(java.text.ParseException)

Example 9 with Gw2ApiPermission

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())));
}
Also used : ApiTokenEntity(com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity) Gw2ApiPermission(com.gw2auth.oauth2.server.service.Gw2ApiPermission) Instant(java.time.Instant) Transactional(org.springframework.transaction.annotation.Transactional)

Example 10 with Gw2ApiPermission

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);
}
Also used : OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RequestParam(org.springframework.web.bind.annotation.RequestParam) Autowired(org.springframework.beans.factory.annotation.Autowired) ClientRegistrationService(com.gw2auth.oauth2.server.service.client.registration.ClientRegistrationService) ArrayList(java.util.ArrayList) Utils(com.gw2auth.oauth2.server.util.Utils) GetMapping(org.springframework.web.bind.annotation.GetMapping) URI(java.net.URI) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) Gw2AuthUser(com.gw2auth.oauth2.server.service.user.Gw2AuthUser) AbstractRestController(com.gw2auth.oauth2.server.web.AbstractRestController) ApiTokenService(com.gw2auth.oauth2.server.service.apitoken.ApiTokenService) ClientAuthorizationService(com.gw2auth.oauth2.server.service.client.authorization.ClientAuthorizationService) MediaType(org.springframework.http.MediaType) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MultiValueMap(org.springframework.util.MultiValueMap) Set(java.util.Set) UUID(java.util.UUID) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) VerificationService(com.gw2auth.oauth2.server.service.verification.VerificationService) OAuth2AuthorizationService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService) HttpStatus(org.springframework.http.HttpStatus) ClientConsentService(com.gw2auth.oauth2.server.service.client.consent.ClientConsentService) List(java.util.List) ApiToken(com.gw2auth.oauth2.server.service.apitoken.ApiToken) OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) Gw2ApiPermission(com.gw2auth.oauth2.server.service.Gw2ApiPermission) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) ClientRegistration(com.gw2auth.oauth2.server.service.client.registration.ClientRegistration) ResponseEntity(org.springframework.http.ResponseEntity) ClientAuthorization(com.gw2auth.oauth2.server.service.client.authorization.ClientAuthorization) ClientRegistrationPublicResponse(com.gw2auth.oauth2.server.web.client.consent.ClientRegistrationPublicResponse) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Gw2ApiPermission(com.gw2auth.oauth2.server.service.Gw2ApiPermission) Set(java.util.Set) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ArrayList(java.util.ArrayList) ClientRegistration(com.gw2auth.oauth2.server.service.client.registration.ClientRegistration) ApiToken(com.gw2auth.oauth2.server.service.apitoken.ApiToken) UUID(java.util.UUID) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

Gw2ApiPermission (com.gw2auth.oauth2.server.service.Gw2ApiPermission)8 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 ApiTokenEntity (com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity)3 ClientRegistrationEntity (com.gw2auth.oauth2.server.repository.client.registration.ClientRegistrationEntity)3 Transactional (org.springframework.transaction.annotation.Transactional)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ApiToken (com.gw2auth.oauth2.server.service.apitoken.ApiToken)2 ApiTokenService (com.gw2auth.oauth2.server.service.apitoken.ApiTokenService)2 ClientAuthorization (com.gw2auth.oauth2.server.service.client.authorization.ClientAuthorization)2 ClientAuthorizationService (com.gw2auth.oauth2.server.service.client.authorization.ClientAuthorizationService)2 ClientConsentService (com.gw2auth.oauth2.server.service.client.consent.ClientConsentService)2 Gw2AuthUser (com.gw2auth.oauth2.server.service.user.Gw2AuthUser)2 VerificationService (com.gw2auth.oauth2.server.service.verification.VerificationService)2 Instant (java.time.Instant)2 Collectors (java.util.stream.Collectors)2 StringStartsWith (org.hamcrest.core.StringStartsWith)2 JSONObject (org.json.JSONObject)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 MockClientHttpResponse (org.springframework.mock.http.client.MockClientHttpResponse)2 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)2