Search in sources :

Example 6 with Account

use of com.gw2auth.oauth2.server.service.account.Account in project oauth2-server by gw2auth.

the class ApiTokenControllerTest method updateApiTokenThatHasBeenVerifiedByAnotherAccount.

@WithGw2AuthLogin
public void updateApiTokenThatHasBeenVerifiedByAnotherAccount(MockHttpSession session) throws Exception {
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    final UUID gw2AccountId = UUID.randomUUID();
    // save key for the same gw2 account id on both accounts
    this.testHelper.createApiToken(accountId, gw2AccountId, Set.of(), "Name A");
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name B");
    // save verification for the other account
    this.gw2AccountVerificationRepository.save(new Gw2AccountVerificationEntity(gw2AccountId, otherUserAccountId));
    this.mockMvc.perform(patch("/api/token/{gw2AccountId}", gw2AccountId).session(session).with(csrf()).queryParam("displayName", "Hello World")).andExpect(status().isNotAcceptable());
    // api token should be deleted now
    assertTrue(this.apiTokenRepository.findAllByAccountIdAndGw2AccountIds(accountId, Set.of(gw2AccountId)).isEmpty());
}
Also used : Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Example 7 with Account

use of com.gw2auth.oauth2.server.service.account.Account 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))));
}
Also used : ApiTokenEntity(com.gw2auth.oauth2.server.repository.apitoken.ApiTokenEntity) JsonNode(com.fasterxml.jackson.databind.JsonNode) MvcResult(org.springframework.test.web.servlet.MvcResult) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) ClientRegistrationCreation(com.gw2auth.oauth2.server.service.client.registration.ClientRegistrationCreation) ClientAuthorizationEntity(com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationEntity) ClientRegistration(com.gw2auth.oauth2.server.service.client.registration.ClientRegistration) JSONObject(org.json.JSONObject) ClientAuthorizationTokenEntity(com.gw2auth.oauth2.server.repository.client.authorization.ClientAuthorizationTokenEntity) ClientConsentEntity(com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity)

Example 8 with Account

use of com.gw2auth.oauth2.server.service.account.Account in project oauth2-server by gw2auth.

the class VerificationControllerTest method startAndSubmitApiTokenNameChallengeLaterFulfilled.

@WithGw2AuthLogin
public void startAndSubmitApiTokenNameChallengeLaterFulfilled(MockHttpSession session) throws Exception {
    final UUID gw2AccountId = UUID.randomUUID();
    // insert an api token for another account but for the same gw2 account id
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name");
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    // prepare the testing clock
    Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    this.verificationService.setClock(testingClock);
    final String gw2ApiToken = TestHelper.randomRootToken();
    final String gw2ApiSubtoken = TestHelper.createSubtokenJWT(UUID.randomUUID(), Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(90L));
    // prepare the gw2 api
    this.gw2RestServer.reset();
    preparedGw2RestServerForCreateSubtoken(gw2ApiToken, gw2ApiSubtoken, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant().plus(Duration.ofMinutes(90L)));
    preparedGw2RestServerForAccountRequest(gw2AccountId, gw2ApiSubtoken);
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, "Not the name that was requested", Set.of(Gw2ApiPermission.ACCOUNT));
    // start the challenge
    final VerificationChallengeStart challengeStart = this.verificationService.startChallenge(accountId, 1L);
    // submit the challenge
    this.mockMvc.perform(post("/api/verification/pending").session(session).with(csrf()).queryParam("token", gw2ApiToken)).andExpect(status().isOk()).andExpect(jsonPath("$.isSuccess").value("false")).andExpect(jsonPath("$.pending").isMap());
    // started challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, "").isEmpty());
    // pending challenge should be inserted
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isPresent());
    // let 15 minutes pass
    testingClock = Clock.offset(testingClock, Duration.ofMinutes(15L));
    this.verificationService.setClock(testingClock);
    // prepare the api again and now set the name to the requested one
    this.gw2RestServer.reset();
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, challengeStart.message().get("apiTokenName").toString(), Set.of(Gw2ApiPermission.ACCOUNT));
    // simulate scheduled check
    this.verificationService.tryVerifyAllPending();
    // pending challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isEmpty());
    // account should now be verified
    final Gw2AccountVerificationEntity accountVerification = this.gw2AccountVerificationRepository.findById(gw2AccountId).orElse(null);
    assertNotNull(accountVerification);
    assertEquals(accountId, accountVerification.accountId());
    // the other users api token should be removed
    assertTrue(this.apiTokenRepository.findByAccountIdAndGw2AccountId(otherUserAccountId, gw2AccountId).isEmpty());
}
Also used : VerificationChallengeStart(com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart) UUID(java.util.UUID) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Example 9 with Account

use of com.gw2auth.oauth2.server.service.account.Account in project oauth2-server by gw2auth.

the class VerificationControllerTest method startAndSubmitApiTokenNameChallengeDirectlyFulfilled.

@WithGw2AuthLogin
public void startAndSubmitApiTokenNameChallengeDirectlyFulfilled(MockHttpSession session) throws Exception {
    final UUID gw2AccountId = UUID.randomUUID();
    // insert an api token for another account but for the same gw2 account id
    final long otherUserAccountId = this.accountRepository.save(new AccountEntity(null, Instant.now())).id();
    this.testHelper.createApiToken(otherUserAccountId, gw2AccountId, Set.of(), "Name");
    final long accountId = AuthenticationHelper.getUser(session).orElseThrow().getAccountId();
    // prepare the testing clock
    Clock testingClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    this.verificationService.setClock(testingClock);
    final String gw2ApiToken = TestHelper.randomRootToken();
    final String gw2ApiSubtoken = TestHelper.createSubtokenJWT(UUID.randomUUID(), Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant(), Duration.ofMinutes(90L));
    // start the challenge
    final VerificationChallengeStart challengeStart = this.verificationService.startChallenge(accountId, 1L);
    // prepare the gw2 api
    this.gw2RestServer.reset();
    preparedGw2RestServerForCreateSubtoken(gw2ApiToken, gw2ApiSubtoken, Set.of(Gw2ApiPermission.ACCOUNT), testingClock.instant().plus(Duration.ofMinutes(90L)));
    preparedGw2RestServerForAccountRequest(gw2AccountId, gw2ApiSubtoken);
    prepareGw2RestServerForTokenInfoRequest(gw2ApiSubtoken, challengeStart.message().get("apiTokenName").toString(), Set.of(Gw2ApiPermission.ACCOUNT));
    // submit the challenge
    this.mockMvc.perform(post("/api/verification/pending").session(session).with(csrf()).queryParam("token", gw2ApiToken)).andExpect(status().isOk()).andExpect(jsonPath("$.isSuccess").value("true"));
    // started challenge should be removed
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, "").isEmpty());
    // pending challenge should not be present (either removed or never inserted)
    assertTrue(this.gw2AccountVerificationChallengeRepository.findByAccountIdAndGw2AccountId(accountId, gw2AccountId.toString()).isEmpty());
    // account should now be verified
    final Gw2AccountVerificationEntity accountVerification = this.gw2AccountVerificationRepository.findById(gw2AccountId).orElse(null);
    assertNotNull(accountVerification);
    assertEquals(accountId, accountVerification.accountId());
    // the other users api token should be removed
    assertTrue(this.apiTokenRepository.findByAccountIdAndGw2AccountId(otherUserAccountId, gw2AccountId).isEmpty());
}
Also used : VerificationChallengeStart(com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart) UUID(java.util.UUID) Clock(java.time.Clock) Gw2AccountVerificationEntity(com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity) AccountEntity(com.gw2auth.oauth2.server.repository.account.AccountEntity)

Example 10 with Account

use of com.gw2auth.oauth2.server.service.account.Account in project oauth2-server by gw2auth.

the class ClientConsentServiceImpl method deleteInternal.

@Transactional
protected void deleteInternal(ClientConsentEntity entity) {
    // not actually deleting, since we want to keep the client specific account sub
    this.clientConsentRepository.deleteByAccountIdAndClientRegistrationId(entity.accountId(), entity.clientRegistrationId());
    this.clientConsentRepository.save(new ClientConsentEntity(entity.accountId(), entity.clientRegistrationId(), entity.accountSub(), Set.of()));
}
Also used : ClientConsentEntity(com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

AccountEntity (com.gw2auth.oauth2.server.repository.account.AccountEntity)7 Gw2AccountVerificationEntity (com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationEntity)7 AccountFederationEntity (com.gw2auth.oauth2.server.repository.account.AccountFederationEntity)5 Clock (java.time.Clock)5 UUID (java.util.UUID)5 ClientConsentEntity (com.gw2auth.oauth2.server.repository.client.consent.ClientConsentEntity)4 VerificationChallengeStart (com.gw2auth.oauth2.server.service.verification.VerificationChallengeStart)3 Transactional (org.springframework.transaction.annotation.Transactional)3 ClientRegistrationEntity (com.gw2auth.oauth2.server.repository.client.registration.ClientRegistrationEntity)2 Gw2AccountVerificationChallengeEntity (com.gw2auth.oauth2.server.repository.verification.Gw2AccountVerificationChallengeEntity)2 Account (com.gw2auth.oauth2.server.service.account.Account)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 ClientRegistration (com.gw2auth.oauth2.server.service.client.registration.ClientRegistration)2 ClientRegistrationCreation (com.gw2auth.oauth2.server.service.client.registration.ClientRegistrationCreation)2 Gw2AuthUser (com.gw2auth.oauth2.server.service.user.Gw2AuthUser)2 AbstractRestController (com.gw2auth.oauth2.server.web.AbstractRestController)2 java.util (java.util)2