Search in sources :

Example 1 with OrcidOauth2AuthoriziationCodeDetail

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

the class OrcidClientCredentialEndPointDelegatorImpl method generateToken.

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code, String redirectUri, String grantType, String refreshToken, String state, String authorization, boolean revokeOld, Long expiresIn) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();
    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }
    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao.find(code);
        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }
            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE) || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
            //This will pass through to the token generator as a request param.
            if (authorizationCodeEntity.getNonce() != null) {
                authorizationParameters.put(OrcidOauth2Constants.NONCE, authorizationCodeEntity.getNonce());
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    //If it is a refresh token request, set the needed authorization parameters
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        authorizationParameters.put(OrcidOauth2Constants.AUTHORIZATION, authorization);
        authorizationParameters.put(OrcidOauth2Constants.REVOKE_OLD, String.valueOf(revokeOld));
        authorizationParameters.put(OrcidOauth2Constants.EXPIRES_IN, String.valueOf(expiresIn));
        authorizationParameters.put(OrcidOauth2Constants.REFRESH_TOKEN, String.valueOf(refreshToken));
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(authorizationParameters);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);
    //Need to change this to either the DefaultTokenType or start using a different token type.
    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object[] params = { grantType };
    if (token == null) {
        LOGGER.info("Unsupported grant type for OAuth2: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info("OAuth2 access token granted: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}, token={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri, token });
    return token;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)

Example 2 with OrcidOauth2AuthoriziationCodeDetail

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

the class OrcidAuthorizationCodeServiceImpl method getDetailFromAuthorization.

private OrcidOauth2AuthoriziationCodeDetail getDetailFromAuthorization(String code, OAuth2Authentication authentication) {
    OAuth2Request oAuth2Request = authentication.getOAuth2Request();
    OrcidOauth2AuthoriziationCodeDetail detail = new OrcidOauth2AuthoriziationCodeDetail();
    Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
    if (requestParameters != null && !requestParameters.isEmpty()) {
        String clientId = (String) requestParameters.get(CLIENT_ID);
        ClientDetailsEntity clientDetails = getClientDetails(clientId);
        if (clientDetails == null) {
            return null;
        }
        detail.setScopes(OAuth2Utils.parseParameterList((String) requestParameters.get(SCOPE)));
        detail.setState((String) requestParameters.get(STATE));
        detail.setRedirectUri((String) requestParameters.get(REDIRECT_URI));
        detail.setResponseType((String) requestParameters.get(RESPONSE_TYPE));
        detail.setClientDetailsEntity(clientDetails);
        //persist the openID params if present
        if (requestParameters.get(OrcidOauth2Constants.NONCE) != null)
            detail.setNonce((String) requestParameters.get(OrcidOauth2Constants.NONCE));
    }
    detail.setId(code);
    detail.setApproved(authentication.getOAuth2Request().isApproved());
    Authentication userAuthentication = authentication.getUserAuthentication();
    Object principal = userAuthentication.getPrincipal();
    ProfileEntity entity = null;
    if (principal instanceof OrcidProfileUserDetails) {
        OrcidProfileUserDetails userDetails = (OrcidProfileUserDetails) principal;
        String effectiveOrcid = userDetails.getOrcid();
        if (effectiveOrcid != null) {
            entity = profileEntityCacheManager.retrieve(effectiveOrcid);
        }
    }
    if (entity == null) {
        return null;
    }
    detail.setProfileEntity(entity);
    detail.setAuthenticated(userAuthentication.isAuthenticated());
    Set<String> authorities = getStringSetFromGrantedAuthorities(authentication.getAuthorities());
    detail.setAuthorities(authorities);
    Object authenticationDetails = userAuthentication.getDetails();
    if (authenticationDetails instanceof WebAuthenticationDetails) {
        detail.setSessionId(((WebAuthenticationDetails) authenticationDetails).getSessionId());
    }
    boolean isPersistentTokenEnabledByUser = false;
    //Set token version to persistent token
    //TODO: As of Jan 2015 all tokens will be new tokens, so, we will have to remove the token version code and 
    //treat all tokens as new tokens
    detail.setVersion(Long.valueOf(OrcidOauth2Constants.PERSISTENT_TOKEN));
    if (requestParameters.containsKey(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN)) {
        String grantPersitentToken = (String) requestParameters.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN);
        if (Boolean.parseBoolean(grantPersitentToken)) {
            isPersistentTokenEnabledByUser = true;
        }
    }
    detail.setPersistent(isPersistentTokenEnabledByUser);
    return detail;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) OrcidProfileUserDetails(org.orcid.core.oauth.OrcidProfileUserDetails) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity)

Example 3 with OrcidOauth2AuthoriziationCodeDetail

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

the class OrcidOauth2AuthoriziationCodeDetailDaoImpl method isPersistentToken.

@Override
public boolean isPersistentToken(String code) {
    TypedQuery<OrcidOauth2AuthoriziationCodeDetail> query = entityManager.createQuery("from OrcidOauth2AuthoriziationCodeDetail where id=:code", OrcidOauth2AuthoriziationCodeDetail.class);
    query.setParameter("code", code);
    OrcidOauth2AuthoriziationCodeDetail result = query.getSingleResult();
    return result.isPersistent();
}
Also used : OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail)

Example 4 with OrcidOauth2AuthoriziationCodeDetail

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

the class OrcidClientCredentialEndPointDelegatorTest method generateRefreshTokenTest.

@Test
public void generateRefreshTokenTest() {
    //Generate the access token
    SecurityContextTestUtils.setUpSecurityContextForClientOnly(CLIENT_ID_1, ScopePathType.ACTIVITIES_UPDATE, ScopePathType.READ_LIMITED);
    OrcidOauth2AuthoriziationCodeDetail authCode = createAuthorizationCode("code-1", CLIENT_ID_1, "http://www.APP-5555555555555555.com/redirect/oauth", true, "/activities/update");
    MultivaluedMap<String, String> formParams = new MultivaluedMapImpl();
    formParams.add("client_id", CLIENT_ID_1);
    formParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
    formParams.add("grant_type", "authorization_code");
    formParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
    formParams.add("code", authCode.getId());
    Response response = orcidClientCredentialEndPointDelegator.obtainOauth2Token(null, formParams);
    assertNotNull(response);
    assertNotNull(response.getEntity());
    DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) response.getEntity();
    assertNotNull(token);
    assertTrue(!PojoUtil.isEmpty(token.getValue()));
    assertNotNull(token.getRefreshToken());
    assertTrue(!PojoUtil.isEmpty(token.getRefreshToken().getValue()));
    //Generate the refresh token
    MultivaluedMap<String, String> refreshTokenformParams = new MultivaluedMapImpl();
    refreshTokenformParams.add("client_id", CLIENT_ID_1);
    refreshTokenformParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
    refreshTokenformParams.add("grant_type", "refresh_token");
    refreshTokenformParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
    refreshTokenformParams.add("refresh_token", token.getRefreshToken().getValue());
    String authorization = "bearer " + token.getValue();
    Response refreshTokenResponse = orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
    assertNotNull(refreshTokenResponse);
    assertNotNull(refreshTokenResponse.getEntity());
    DefaultOAuth2AccessToken refreshToken = (DefaultOAuth2AccessToken) refreshTokenResponse.getEntity();
    assertNotNull(refreshToken);
    assertTrue(!PojoUtil.isEmpty(refreshToken.getValue()));
    assertNotNull(refreshToken.getRefreshToken());
    assertTrue(!PojoUtil.isEmpty(refreshToken.getRefreshToken().getValue()));
    //Assert that both tokens expires at the same time
    assertEquals(token.getExpiration(), refreshToken.getExpiration());
    //Try to generate another one, and fail, because parent token was disabled
    try {
        orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
    } catch (InvalidTokenException e) {
        assertTrue(e.getMessage().contains("Parent token is disabled"));
    }
}
Also used : Response(javax.ws.rs.core.Response) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 5 with OrcidOauth2AuthoriziationCodeDetail

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

the class OrcidClientCredentialEndPointDelegatorTest method createAuthorizationCode.

private OrcidOauth2AuthoriziationCodeDetail createAuthorizationCode(String value, String clientId, String redirectUri, boolean persistent, String... scopes) {
    OrcidOauth2AuthoriziationCodeDetail authorizationCode = new OrcidOauth2AuthoriziationCodeDetail();
    authorizationCode.setId(value);
    authorizationCode.setApproved(true);
    authorizationCode.setScopes(new HashSet<String>(Arrays.asList(scopes)));
    authorizationCode.setClientDetailsEntity(new ClientDetailsEntity(clientId));
    authorizationCode.setPersistent(persistent);
    authorizationCode.setProfileEntity(new ProfileEntity(USER_ORCID));
    authorizationCode.setRedirectUri(redirectUri);
    authorizationCode.setResourceIds(new HashSet<String>(Arrays.asList("orcid")));
    authorizationCode.setAuthenticated(true);
    orcidOauth2AuthoriziationCodeDetailDao.persist(authorizationCode);
    return authorizationCode;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity)

Aggregations

OrcidOauth2AuthoriziationCodeDetail (org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail)13 Test (org.junit.Test)4 DBUnitTest (org.orcid.test.DBUnitTest)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)3 Response (javax.ws.rs.core.Response)3 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)3 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)3 Authentication (org.springframework.security.core.Authentication)3 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)3 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)3 Calendar (java.util.Calendar)2 Date (java.util.Date)2 OrcidOauth2AuthInfo (org.orcid.core.oauth.OrcidOauth2AuthInfo)2 OrcidOauth2UserAuthentication (org.orcid.core.oauth.OrcidOauth2UserAuthentication)2 Transactional (org.springframework.transaction.annotation.Transactional)2 HashMap (java.util.HashMap)1 OrcidProfileUserDetails (org.orcid.core.oauth.OrcidProfileUserDetails)1 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)1 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)1