Search in sources :

Example 1 with OrcidOauth2TokenDetail

use of org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail in project ORCID-Source by ORCID.

the class OrcidRefreshTokenChecker method validateRequest.

public void validateRequest(String grantType, TokenRequest tokenRequest, Long requestTimeInMillis) {
    String authorization = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
    String clientId = tokenRequest.getClientId();
    String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    Long expireIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
    String refreshToken = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REFRESH_TOKEN);
    OrcidOauth2TokenDetail token = orcidOauth2TokenDetailDao.findByTokenValue(authorization);
    // Verify the token belongs to this client
    if (!clientId.equals(token.getClientDetailsId())) {
        throw new IllegalArgumentException("This token doesnt belong to the given client");
    }
    // Verify client is enabled
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    // Verify the token is not expired
    if (token.getTokenExpiration() != null) {
        if (token.getTokenExpiration().before(new Date())) {
            throw new InvalidTokenException("Access token expired: " + authorization);
        }
    }
    // Verify access token and refresh token are linked
    if (!refreshToken.equals(token.getRefreshTokenValue())) {
        throw new InvalidTokenException("Token and refresh token does not match");
    }
    // Verify the token is not disabled
    if (token.getTokenDisabled() != null && token.getTokenDisabled()) {
        throw new InvalidTokenException("Parent token is disabled");
    }
    // Verify scopes are not wider than the token scopes
    if (PojoUtil.isEmpty(scopes)) {
        scopes = token.getScope();
    } else {
        Set<ScopePathType> requiredScopes = ScopePathType.getScopesFromSpaceSeparatedString(scopes);
        Set<ScopePathType> simpleTokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
        // This collection contains all tokens that should be allowed given
        // the scopes that the parent token contains
        Set<ScopePathType> combinedTokenScopes = new HashSet<ScopePathType>();
        for (ScopePathType scope : simpleTokenScopes) {
            combinedTokenScopes.addAll(scope.combined());
        }
        // combinedTokenScopes
        for (ScopePathType scope : requiredScopes) {
            if (!combinedTokenScopes.contains(scope)) {
                throw new InvalidScopeException("The given scope '" + scope.value() + "' is not allowed for the parent token");
            }
        }
    }
    // Validate the expiration for the new token is no later than the parent
    // token expiration.
    long parentTokenExpiration = token.getTokenExpiration() == null ? System.currentTimeMillis() : token.getTokenExpiration().getTime();
    if (expireIn > parentTokenExpiration) {
        throw new IllegalArgumentException("Token expiration can't be after " + token.getTokenExpiration());
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Date(java.util.Date) HashSet(java.util.HashSet)

Example 2 with OrcidOauth2TokenDetail

use of org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail in project ORCID-Source by ORCID.

the class OrcidOauth2TokenDetailServiceImpl method disableAccessToken.

/**
     * This should NOT delete the row, but merely set it as disabled
     * 
     * @param tokenId
     *            the id of the token that should be disabled
     * @param userOrcid
     *            the id of the user owner of the token
     */
@Override
public void disableAccessToken(Long tokenId, String userOrcid) {
    if (PojoUtil.isEmpty(userOrcid) || tokenId == null) {
        throw new IllegalArgumentException("One of the provided params is empty: userOrcid='" + userOrcid + "' tokenId='" + String.valueOf(tokenId) + "'");
    }
    //Iterate over all tokens that belongs to this user and client, to remove all the ones that have the same scopes
    OrcidOauth2TokenDetail tokenToDisable = orcidOauth2TokenDetailDao.find(tokenId);
    String scopesToDisableString = tokenToDisable.getScope();
    Set<ScopePathType> scopesToDisable = ScopePathType.getScopesFromSpaceSeparatedString(scopesToDisableString);
    List<OrcidOauth2TokenDetail> allTokens = orcidOauth2TokenDetailDao.findByClientIdAndUserName(tokenToDisable.getClientDetailsId(), userOrcid);
    //Iterate over all tokens and verify we disable all the ones that have the same scopes
    for (OrcidOauth2TokenDetail token : allTokens) {
        if (token.getTokenDisabled() == null || !token.getTokenDisabled()) {
            if (!PojoUtil.isEmpty(token.getScope())) {
                Set<ScopePathType> tokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
                if (scopesToDisable.equals(tokenScopes)) {
                    orcidOauth2TokenDetailDao.disableAccessTokenById(token.getId(), userOrcid);
                }
            }
        }
    }
}
Also used : ScopePathType(org.orcid.jaxb.model.message.ScopePathType) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)

Example 3 with OrcidOauth2TokenDetail

use of org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail in project ORCID-Source by ORCID.

the class OrcidOauth2TokenDetailServiceImpl method doesClientKnowUser.

@Override
public boolean doesClientKnowUser(String clientId, String userOrcid) {
    List<OrcidOauth2TokenDetail> existingTokens = orcidOauth2TokenDetailDao.findByClientIdAndUserName(clientId, userOrcid);
    if (existingTokens == null || existingTokens.isEmpty()) {
        return false;
    }
    Date now = new Date();
    for (OrcidOauth2TokenDetail token : existingTokens) {
        if (token.getTokenExpiration() != null && token.getTokenExpiration().after(now)) {
            return true;
        }
    }
    return false;
}
Also used : OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Date(java.util.Date)

Example 4 with OrcidOauth2TokenDetail

use of org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail in project ORCID-Source by ORCID.

the class OrcidOauth2TokenDetailServiceTest method dontRemoveOtherClientScopesTest.

@Test
public void dontRemoveOtherClientScopesTest() {
    //Delete
    Long token1Id = createToken(CLIENT_ID_1, "token-1", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/read-limited", false).getId();
    Long token2Id = createToken(CLIENT_ID_1, "token-2", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/activities/update", false).getId();
    Long token3Id = createToken(CLIENT_ID_1, "token-3", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/activities/update /read-limited", false).getId();
    //Delete
    Long token4Id = createToken(CLIENT_ID_1, "token-4", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/read-limited", false).getId();
    Long token5Id = createToken(CLIENT_ID_2, "token-5", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/read-limited", false).getId();
    Long token6Id = createToken(CLIENT_ID_2, "token-6", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/activities/update", false).getId();
    Long token7Id = createToken(CLIENT_ID_2, "token-7", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/activities/update /read-limited", false).getId();
    Long token8Id = createToken(CLIENT_ID_2, "token-8", USER_ORCID, new Date(System.currentTimeMillis() + 100000), "/read-limited", false).getId();
    List<OrcidOauth2TokenDetail> activeTokens = orcidOauth2TokenDetailService.findByUserName(USER_ORCID);
    assertNotNull(activeTokens);
    assertEquals(8, activeTokens.size());
    orcidOauth2TokenDetailService.disableAccessToken(token1Id, USER_ORCID);
    activeTokens = orcidOauth2TokenDetailService.findByUserName(USER_ORCID);
    assertEquals(6, activeTokens.size());
    for (OrcidOauth2TokenDetail token : activeTokens) {
        assertThat(token.getId(), allOf(not(token1Id), not(token4Id)));
        assertThat(token.getId(), anyOf(is(token2Id), is(token3Id), is(token5Id), is(token6Id), is(token7Id), is(token8Id)));
    }
}
Also used : Date(java.util.Date) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Test(org.junit.Test) DBUnitTest(org.orcid.test.DBUnitTest)

Example 5 with OrcidOauth2TokenDetail

use of org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail in project ORCID-Source by ORCID.

the class DefaultOAuthClientVisibilityTest method testCheckClientPermissionsAllowOnlyPublicAndLimitedVisibility.

@Test
@Transactional
@Rollback
public void testCheckClientPermissionsAllowOnlyPublicAndLimitedVisibility() throws Exception {
    Set<String> resourceIds = new HashSet<String>(Arrays.asList("orcid"));
    HashSet<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>(Arrays.asList(new SimpleGrantedAuthority("ROLE_CLIENT")));
    AuthorizationRequest request = new AuthorizationRequest("4444-4444-4444-4446", Arrays.asList("/orcid-bio/external-identifiers/create"));
    request.setAuthorities(grantedAuthorities);
    request.setResourceIds(resourceIds);
    ProfileEntity entity = new ProfileEntity("4444-4444-4444-4446");
    OrcidOauth2UserAuthentication oauth2UserAuthentication = new OrcidOauth2UserAuthentication(entity, true);
    // we care only that an OAuth client request results in the correct
    // visibilities
    OrcidOAuth2Authentication oAuth2Authentication = new OrcidOAuth2Authentication(request, oauth2UserAuthentication, "made-up-token");
    OrcidOauth2TokenDetail tokenDetail = new OrcidOauth2TokenDetail();
    tokenDetail.setScope("/orcid-bio/external-identifiers/create");
    tokenDetail.setDateCreated(new Date());
    when(orcidOauth2TokenDetailService.findNonDisabledByTokenValue(any(String.class))).thenReturn(tokenDetail);
    ScopePathType scopePathType = ScopePathType.ORCID_BIO_EXTERNAL_IDENTIFIERS_CREATE;
    Set<Visibility> visibilitiesForClient = permissionChecker.obtainVisibilitiesForAuthentication(oAuth2Authentication, scopePathType, getOrcidMessage());
    assertTrue(visibilitiesForClient.size() == 3);
    assertTrue(visibilitiesForClient.contains(Visibility.LIMITED));
    assertTrue(visibilitiesForClient.contains(Visibility.REGISTERED_ONLY));
    assertTrue(visibilitiesForClient.contains(Visibility.PUBLIC));
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) Visibility(org.orcid.jaxb.model.message.Visibility) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) HashSet(java.util.HashSet) Test(org.junit.Test) BaseTest(org.orcid.core.BaseTest) Rollback(org.springframework.test.annotation.Rollback) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)45 Date (java.util.Date)29 Test (org.junit.Test)27 DBUnitTest (org.orcid.test.DBUnitTest)26 Transactional (org.springframework.transaction.annotation.Transactional)13 Rollback (org.springframework.test.annotation.Rollback)12 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)10 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)9 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)8 InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)7 NoResultException (javax.persistence.NoResultException)6 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)5 ArrayList (java.util.ArrayList)4 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)3 ApplicationSummary (org.orcid.pojo.ApplicationSummary)3 HashSet (java.util.HashSet)2 OrcidOauth2UserAuthentication (org.orcid.core.oauth.OrcidOauth2UserAuthentication)2 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)2