List of usage examples for org.apache.commons.io Charsets UTF_8
Charset UTF_8
To view the source code for org.apache.commons.io Charsets UTF_8.
Click Source Link
Eight-bit Unicode Transformation Format.
From source file:org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator.java
/** * Helper method to add public certificate to JWT_HEADER to signature verification. * * @param tenantDomain//ww w . j a va2 s . c o m * @param tenantId * @throws IdentityOAuth2Exception */ private String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { try { Certificate certificate = getCertificate(tenantDomain, tenantId); // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization //generate the SHA-1 thumbprint of the certificate MessageDigest digestValue = MessageDigest.getInstance("SHA-1"); byte[] der = certificate.getEncoded(); digestValue.update(der); byte[] digestInBytes = digestValue.digest(); String publicCertThumbprint = hexify(digestInBytes); String base64EncodedThumbPrint = new String( base64Url.encode(publicCertThumbprint.getBytes(Charsets.UTF_8)), Charsets.UTF_8); return base64EncodedThumbPrint; } catch (Exception e) { String error = "Error in obtaining certificate for tenant " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } }
From source file:org.wso2.carbon.identity.oauth2.authz.handlers.TokenResponseTypeHandler.java
@Override public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception { OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO(); OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO(); String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()); respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl()); String consumerKey = authorizationReqDTO.getConsumerKey(); String authorizedUser = authorizationReqDTO.getUsername(); String oAuthCacheKeyString;/*w w w. j a va2 s . c o m*/ boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser); if (isUsernameCaseSensitive) { oAuthCacheKeyString = consumerKey + ":" + authorizedUser + ":" + scope; } else { oAuthCacheKeyString = consumerKey + ":" + authorizedUser.toLowerCase() + ":" + scope; } OAuthCacheKey cacheKey = new OAuthCacheKey(oAuthCacheKeyString); String userStoreDomain = null; //select the user store domain when multiple user stores are configured. if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(authorizedUser); } String refreshToken = null; Timestamp refreshTokenIssuedTime = null; long refreshTokenValidityPeriodInMillis = 0; synchronized ((consumerKey + ":" + authorizedUser + ":" + scope).intern()) { // check if valid access token exists in cache if (cacheEnabled) { AccessTokenDO accessTokenDO = (AccessTokenDO) oauthCache.getValueFromCache(cacheKey); if (accessTokenDO != null) { if (log.isDebugEnabled()) { log.debug("Retrieved active Access Token : " + accessTokenDO.getAccessToken() + " for Client Id : " + consumerKey + ", User ID :" + authorizedUser + " and Scope : " + scope + " from cache"); } long expireTime = OAuth2Util.getTokenExpireTimeMillis(accessTokenDO); if (expireTime > 0 || expireTime < 0) { if (log.isDebugEnabled()) { if (expireTime > 0) { log.debug("Access Token " + accessTokenDO.getAccessToken() + " is valid for another " + expireTime + "ms"); } else { log.debug("Infinite lifetime Access Token " + accessTokenDO.getAccessToken() + " found in cache"); } } respDTO.setAccessToken(accessTokenDO.getAccessToken()); if (expireTime > 0) { respDTO.setValidityPeriod(expireTime / 1000); } else { respDTO.setValidityPeriod(Long.MAX_VALUE / 1000); } respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope()); respDTO.setTokenType(accessTokenDO.getTokenType()); return respDTO; } else { long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(accessTokenDO); if (refreshTokenExpiryTime < 0 || refreshTokenExpiryTime > 0) { log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token."); refreshToken = accessTokenDO.getRefreshToken(); refreshTokenIssuedTime = accessTokenDO.getRefreshTokenIssuedTime(); refreshTokenValidityPeriodInMillis = accessTokenDO .getRefreshTokenValidityPeriodInMillis(); } //Token is expired. Clear it from cache oauthCache.clearCacheEntry(cacheKey); if (log.isDebugEnabled()) { log.debug("Access Token " + accessTokenDO.getAccessToken() + " is expired. Therefore cleared it from cache and marked it" + " as expired in database"); } } } else { if (log.isDebugEnabled()) { log.debug("No active access token found in cache for Client ID : " + consumerKey + ", User ID : " + authorizedUser + " and Scope : " + scope); } } } // check if the last issued access token is still active and valid in the database AccessTokenDO existingAccessTokenDO = tokenMgtDAO.retrieveLatestAccessToken(consumerKey, authorizedUser, userStoreDomain, scope, false); if (existingAccessTokenDO != null) { if (log.isDebugEnabled()) { log.debug("Retrieved latest Access Token : " + existingAccessTokenDO.getAccessToken() + " for Client ID : " + consumerKey + ", User ID :" + authorizedUser + " and Scope : " + scope + " from database"); } long expiryTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO); long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO); if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(existingAccessTokenDO.getTokenState()) && (expiryTime > 0 || expiryTime < 0)) { // token is active and valid if (log.isDebugEnabled()) { if (expiryTime > 0) { log.debug("Access token : " + existingAccessTokenDO.getAccessToken() + " is valid for another " + expiryTime + "ms"); } else { log.debug("Infinite lifetime Access Token " + existingAccessTokenDO.getAccessToken() + " found in cache"); } } if (cacheEnabled) { oauthCache.addToCache(cacheKey, existingAccessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token : " + existingAccessTokenDO.getAccessToken() + " was added to cache for cache key : " + cacheKey.getCacheKeyString()); } } respDTO.setAccessToken(existingAccessTokenDO.getAccessToken()); if (expiryTime > 0) { respDTO.setValidityPeriod(expiryTime / 1000); } else { respDTO.setValidityPeriod(Long.MAX_VALUE / 1000); } respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope()); respDTO.setTokenType(existingAccessTokenDO.getTokenType()); return respDTO; } else { if (log.isDebugEnabled()) { log.debug("Access Token " + existingAccessTokenDO.getAccessToken() + " is " + existingAccessTokenDO.getTokenState()); } String tokenState = existingAccessTokenDO.getTokenState(); if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) { // Token is expired. If refresh token is still valid, use it. if (refreshTokenExpiryTime > 0 || refreshTokenExpiryTime < 0) { log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token."); refreshToken = existingAccessTokenDO.getRefreshToken(); refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime(); refreshTokenValidityPeriodInMillis = existingAccessTokenDO .getRefreshTokenValidityPeriodInMillis(); } if (log.isDebugEnabled()) { log.debug("Marked Access Token " + existingAccessTokenDO.getAccessToken() + " as expired"); } } else { //Token is revoked or inactive if (log.isDebugEnabled()) { log.debug("Access Token " + existingAccessTokenDO.getAccessToken() + " is " + existingAccessTokenDO.getTokenState()); } } } } else { if (log.isDebugEnabled()) { log.debug("No access token found in database for Client ID : " + consumerKey + ", User ID : " + authorizedUser + " and Scope : " + scope + ". Therefore issuing new access token"); } } // issue a new access token String accessToken; try { accessToken = oauthIssuerImpl.accessToken(); // regenerate only if refresh token is null if (refreshToken == null) { refreshToken = oauthIssuerImpl.refreshToken(); } } catch (OAuthSystemException e) { throw new IdentityOAuth2Exception("Error occurred while generating access token and refresh token", e); } if (OAuth2Util.checkUserNameAssertionEnabled()) { String userName = oauthAuthzMsgCtx.getAuthorizationReqDTO().getUsername(); //use ':' for token & userStoreDomain separation String accessTokenStrToEncode = accessToken + ":" + userName; accessToken = Base64Utils.encode(accessTokenStrToEncode.getBytes(Charsets.UTF_8)); String refreshTokenStrToEncode = refreshToken + ":" + userName; refreshToken = Base64Utils.encode(refreshTokenStrToEncode.getBytes(Charsets.UTF_8)); } Timestamp timestamp = new Timestamp(new Date().getTime()); // if reusing existing refresh token, use its original issued time if (refreshTokenIssuedTime == null) { refreshTokenIssuedTime = timestamp; } // Default token validity Period long validityPeriodInMillis = OAuthServerConfiguration.getInstance() .getUserAccessTokenValidityPeriodInSeconds() * 1000; // if a VALID validity period is set through the callback, then use it long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod(); if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) { validityPeriodInMillis = callbackValidityPeriod * 1000; } // If issuing new refresh token, use default refresh token validity Period // otherwise use existing refresh token's validity period if (refreshTokenValidityPeriodInMillis == 0) { refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000; } AccessTokenDO newAccessTokenDO = new AccessTokenDO(consumerKey, OAuth2Util.getUserFromUserName(authorizationReqDTO.getUsername()), oauthAuthzMsgCtx.getApprovedScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, OAuthConstants.UserType.APPLICATION_USER); newAccessTokenDO.setAccessToken(accessToken); newAccessTokenDO.setRefreshToken(refreshToken); newAccessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE); newAccessTokenDO.setTokenId(UUID.randomUUID().toString()); // Persist the access token in database try { tokenMgtDAO.storeAccessToken(accessToken, authorizationReqDTO.getConsumerKey(), newAccessTokenDO, existingAccessTokenDO, userStoreDomain); } catch (IdentityException e) { throw new IdentityOAuth2Exception("Error occurred while storing new access token : " + accessToken, e); } if (log.isDebugEnabled()) { log.debug("Persisted Access Token : " + accessToken + " for " + "Client ID : " + authorizationReqDTO.getConsumerKey() + ", Authorized User : " + authorizationReqDTO.getUsername() + ", Timestamp : " + timestamp + ", Validity period (s) : " + newAccessTokenDO.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", Callback URL : " + authorizationReqDTO.getCallbackUrl() + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + OAuthConstants.UserType.APPLICATION_USER); } // Add the access token to the cache. if (cacheEnabled) { oauthCache.addToCache(cacheKey, newAccessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token : " + accessToken + " was added to OAuthCache for " + "cache key : " + cacheKey.getCacheKeyString()); } } respDTO.setAccessToken(accessToken); if (validityPeriodInMillis > 0) { respDTO.setValidityPeriod(newAccessTokenDO.getValidityPeriod()); } else { respDTO.setValidityPeriod(Long.MAX_VALUE / 1000); } respDTO.setScope(newAccessTokenDO.getScope()); respDTO.setTokenType(newAccessTokenDO.getTokenType()); return respDTO; } }
From source file:org.wso2.carbon.identity.oauth2.client.authentication.BasicAuthClientAuthenticator.java
/** * Extracts client id and secret from Authorization header. * * @param authorizationHeader Authroization header. * @param oAuthClientAuthnContext OAuth Client Authentication context. * @return An array which has client id as the first element and secret as the second element. * @throws OAuthClientAuthnException/*from w w w. j a v a2s . c om*/ */ protected static String[] extractCredentialsFromAuthzHeader(String authorizationHeader, OAuthClientAuthnContext oAuthClientAuthnContext) throws OAuthClientAuthnException { String[] splitValues = authorizationHeader.trim().split(" "); if (splitValues.length == CREDENTIAL_LENGTH) { byte[] decodedBytes = Base64Utils.decode(splitValues[1].trim()); String userNamePassword = new String(decodedBytes, Charsets.UTF_8); String[] credentials = userNamePassword.split(CREDENTIAL_SEPARATOR); if (credentials.length == CREDENTIAL_LENGTH) { return credentials; } } String errMsg = "Error decoding authorization header. Space delimited \"<authMethod> <base64Hash>\" format " + "violated."; throw new OAuthClientAuthnException(errMsg, OAuth2ErrorCodes.INVALID_REQUEST); }
From source file:org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler.java
@Override public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { OAuth2AccessTokenRespDTO tokenRespDTO; OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO(); String scope = OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()); String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(); String authorizedUser = tokReqMsgCtx.getAuthorizedUser().toString(); boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser); String cacheKeyString;/*from www . j av a 2s . c o m*/ if (isUsernameCaseSensitive) { cacheKeyString = consumerKey + ":" + authorizedUser + ":" + scope; } else { cacheKeyString = consumerKey + ":" + authorizedUser.toLowerCase() + ":" + scope; } OAuthCacheKey cacheKey = new OAuthCacheKey(cacheKeyString); String userStoreDomain = null; //select the user store domain when multiple user stores are configured. if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { userStoreDomain = tokReqMsgCtx.getAuthorizedUser().getUserStoreDomain(); } String tokenType; if (isOfTypeApplicationUser()) { tokenType = OAuthConstants.UserType.APPLICATION_USER; } else { tokenType = OAuthConstants.UserType.APPLICATION; } String refreshToken = null; Timestamp refreshTokenIssuedTime = null; long refreshTokenValidityPeriodInMillis = 0; synchronized ((consumerKey + ":" + authorizedUser + ":" + scope).intern()) { // check if valid access token exists in cache if (cacheEnabled) { AccessTokenDO existingAccessTokenDO = (AccessTokenDO) oauthCache.getValueFromCache(cacheKey); if (existingAccessTokenDO != null) { if (log.isDebugEnabled()) { log.debug("Retrieved active access token : " + existingAccessTokenDO.getAccessToken() + " for client Id " + consumerKey + ", user " + authorizedUser + " and scope " + scope + " from cache"); } long expireTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO); if (expireTime > 0 || expireTime < 0) { if (log.isDebugEnabled()) { if (expireTime > 0) { log.debug("Access Token " + existingAccessTokenDO.getAccessToken() + " is still valid"); } else { log.debug("Infinite lifetime Access Token " + existingAccessTokenDO.getAccessToken() + " found in cache"); } } tokenRespDTO = new OAuth2AccessTokenRespDTO(); tokenRespDTO.setAccessToken(existingAccessTokenDO.getAccessToken()); tokenRespDTO.setTokenId(existingAccessTokenDO.getTokenId()); if (issueRefreshToken() && OAuthServerConfiguration.getInstance().getSupportedGrantTypes() .containsKey(GrantType.REFRESH_TOKEN.toString())) { tokenRespDTO.setRefreshToken(existingAccessTokenDO.getRefreshToken()); } if (expireTime > 0) { tokenRespDTO.setExpiresIn(expireTime / 1000); tokenRespDTO.setExpiresInMillis(expireTime); } else { tokenRespDTO.setExpiresIn(Long.MAX_VALUE / 1000); tokenRespDTO.setExpiresInMillis(Long.MAX_VALUE); } return tokenRespDTO; } else { long refreshTokenExpiryTime = OAuth2Util .getRefreshTokenExpireTimeMillis(existingAccessTokenDO); if (refreshTokenExpiryTime < 0 || refreshTokenExpiryTime > 0) { log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token."); refreshToken = existingAccessTokenDO.getRefreshToken(); refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime(); refreshTokenValidityPeriodInMillis = existingAccessTokenDO .getRefreshTokenValidityPeriodInMillis(); } //Token is expired. Clear it from cache. oauthCache.clearCacheEntry(cacheKey); if (log.isDebugEnabled()) { log.debug("Access token " + existingAccessTokenDO.getAccessToken() + " is expired. Therefore cleared it from cache and marked it" + " as expired in database"); } } } } //Check if the last issued access token is still active and valid in database AccessTokenDO existingAccessTokenDO = tokenMgtDAO.retrieveLatestAccessToken( oAuth2AccessTokenReqDTO.getClientId(), tokReqMsgCtx.getAuthorizedUser().toString(), userStoreDomain, scope, false); if (existingAccessTokenDO != null) { if (log.isDebugEnabled()) { log.debug("Retrieved latest access token : " + existingAccessTokenDO.getAccessToken() + " for client Id " + consumerKey + ", user " + authorizedUser + " and scope " + scope + " from database"); } long expireTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO); long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO); if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(existingAccessTokenDO.getTokenState()) && (expireTime > 0 || expireTime < 0)) { // token is active and valid if (log.isDebugEnabled()) { if (expireTime > 0) { log.debug("Access token " + existingAccessTokenDO.getAccessToken() + " is valid for another " + expireTime + "ms"); } else { log.debug("Infinite lifetime Access Token " + existingAccessTokenDO.getAccessToken() + " found in cache"); } } tokenRespDTO = new OAuth2AccessTokenRespDTO(); tokenRespDTO.setAccessToken(existingAccessTokenDO.getAccessToken()); tokenRespDTO.setTokenId(existingAccessTokenDO.getTokenId()); if (issueRefreshToken() && OAuthServerConfiguration.getInstance().getSupportedGrantTypes() .containsKey(GrantType.REFRESH_TOKEN.toString())) { tokenRespDTO.setRefreshToken(existingAccessTokenDO.getRefreshToken()); } if (expireTime > 0) { tokenRespDTO.setExpiresIn(expireTime / 1000); tokenRespDTO.setExpiresInMillis(expireTime); } else { tokenRespDTO.setExpiresIn(Long.MAX_VALUE / 1000); tokenRespDTO.setExpiresInMillis(Long.MAX_VALUE); } if (cacheEnabled) { oauthCache.addToCache(cacheKey, existingAccessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token info was added to the cache for the cache key : " + cacheKey.getCacheKeyString()); } } return tokenRespDTO; } else { if (log.isDebugEnabled()) { log.debug("Access token + " + existingAccessTokenDO.getAccessToken() + " is not valid anymore"); } String tokenState = existingAccessTokenDO.getTokenState(); if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) { // Token is expired. If refresh token is still valid, use it. if (refreshTokenExpiryTime > 0 || refreshTokenExpiryTime < 0) { log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token."); refreshToken = existingAccessTokenDO.getRefreshToken(); refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime(); refreshTokenValidityPeriodInMillis = existingAccessTokenDO .getRefreshTokenValidityPeriodInMillis(); } if (log.isDebugEnabled()) { log.debug("Marked token " + existingAccessTokenDO.getAccessToken() + " as expired"); } } else { //Token is revoked or inactive if (log.isDebugEnabled()) { log.debug("Token " + existingAccessTokenDO.getAccessToken() + " is " + existingAccessTokenDO.getTokenState()); } } } } else { if (log.isDebugEnabled()) { log.debug("No access token found in database for client Id " + consumerKey + ", user " + authorizedUser + " and scope " + scope + ". Therefore issuing new token"); } } // issue a new access token. if (log.isDebugEnabled()) { log.debug("Issuing a new access token for " + consumerKey + " AuthorizedUser : " + authorizedUser); } String newAccessToken; try { String userName = tokReqMsgCtx.getAuthorizedUser().toString(); newAccessToken = oauthIssuerImpl.accessToken(); if (OAuth2Util.checkUserNameAssertionEnabled()) { //use ':' for token & userStoreDomain separation String accessTokenStrToEncode = newAccessToken + ":" + userName; newAccessToken = Base64Utils.encode(accessTokenStrToEncode.getBytes(Charsets.UTF_8)); } // regenerate only if refresh token is null if (refreshToken == null) { refreshToken = oauthIssuerImpl.refreshToken(); if (OAuth2Util.checkUserNameAssertionEnabled()) { //use ':' for token & userStoreDomain separation String refreshTokenStrToEncode = refreshToken + ":" + userName; refreshToken = Base64Utils.encode(refreshTokenStrToEncode.getBytes(Charsets.UTF_8)); } } } catch (OAuthSystemException e) { throw new IdentityOAuth2Exception("Error occurred while generating access token and refresh token", e); } Timestamp timestamp = new Timestamp(new Date().getTime()); // if reusing existing refresh token, use its original issued time if (refreshTokenIssuedTime == null) { refreshTokenIssuedTime = timestamp; } // Default Validity Period (in seconds) long validityPeriodInMillis = OAuthServerConfiguration.getInstance() .getApplicationAccessTokenValidityPeriodInSeconds() * 1000; if (isOfTypeApplicationUser()) { validityPeriodInMillis = OAuthServerConfiguration.getInstance() .getUserAccessTokenValidityPeriodInSeconds() * 1000; } // if a VALID validity period is set through the callback, then use it long callbackValidityPeriod = tokReqMsgCtx.getValidityPeriod(); if (callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) { validityPeriodInMillis = callbackValidityPeriod * 1000; } // If issuing new refresh token, use default refresh token validity Period // otherwise use existing refresh token's validity period if (refreshTokenValidityPeriodInMillis == 0) { refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000; } AccessTokenDO newAccessTokenDO = new AccessTokenDO(consumerKey, tokReqMsgCtx.getAuthorizedUser(), tokReqMsgCtx.getScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, tokenType); newAccessTokenDO.setAccessToken(newAccessToken); newAccessTokenDO.setRefreshToken(refreshToken); newAccessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE); newAccessTokenDO.setTenantID(tokReqMsgCtx.getTenantID()); newAccessTokenDO.setTokenId(UUID.randomUUID().toString()); // Persist the access token in database storeAccessToken(oAuth2AccessTokenReqDTO, userStoreDomain, newAccessTokenDO, newAccessToken, existingAccessTokenDO); if (log.isDebugEnabled()) { log.debug("Persisted Access Token : " + newAccessToken + " for " + "Client ID : " + oAuth2AccessTokenReqDTO.getClientId() + ", Authorized User : " + tokReqMsgCtx.getAuthorizedUser() + ", Timestamp : " + timestamp + ", Validity period (s) : " + newAccessTokenDO.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()) + " and Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE); } //update cache with newly added token if (cacheEnabled) { oauthCache.addToCache(cacheKey, newAccessTokenDO); if (log.isDebugEnabled()) { log.debug( "Access token was added to OAuthCache for cache key : " + cacheKey.getCacheKeyString()); } } tokenRespDTO = new OAuth2AccessTokenRespDTO(); tokenRespDTO.setAccessToken(newAccessToken); tokenRespDTO.setTokenId(newAccessTokenDO.getTokenId()); if (issueRefreshToken() && OAuthServerConfiguration.getInstance().getSupportedGrantTypes() .containsKey(GrantType.REFRESH_TOKEN.toString())) { tokenRespDTO.setRefreshToken(refreshToken); } if (validityPeriodInMillis > 0) { tokenRespDTO.setExpiresInMillis(newAccessTokenDO.getValidityPeriodInMillis()); tokenRespDTO.setExpiresIn(newAccessTokenDO.getValidityPeriod()); } else { tokenRespDTO.setExpiresInMillis(Long.MAX_VALUE); tokenRespDTO.setExpiresIn(Long.MAX_VALUE); } tokenRespDTO.setAuthorizedScopes(scope); return tokenRespDTO; } }
From source file:org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler.java
@Override public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO(); OAuth2AccessTokenReqDTO oauth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO(); String scope = OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()); String tokenId;//from ww w.j a v a2s. c o m String accessToken; String refreshToken; String userStoreDomain = null; Timestamp refreshTokenIssuedTime = null; long refreshTokenValidityPeriodInMillis = 0; try { tokenId = UUID.randomUUID().toString(); accessToken = oauthIssuerImpl.accessToken(); refreshToken = oauthIssuerImpl.refreshToken(); boolean renew = OAuthServerConfiguration.getInstance().isRefreshTokenRenewalEnabled(); //an active or expired token will be returned. since we do the validation for active or expired token in //validateGrant() no need to do it here again RefreshTokenValidationDataDO refreshTokenValidationDataDO = tokenMgtDAO.validateRefreshToken( oauth2AccessTokenReqDTO.getClientId(), oauth2AccessTokenReqDTO.getRefreshToken()); long issuedTime = refreshTokenValidationDataDO.getIssuedTime().getTime(); long refreshValidity = refreshTokenValidationDataDO.getValidityPeriodInMillis(); long skew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000; if (issuedTime + refreshValidity - (System.currentTimeMillis() + skew) > 1000) { if (!renew) { //if refresh token renewal not enabled, we use existing one else we issue a new refresh token refreshToken = oauth2AccessTokenReqDTO.getRefreshToken(); refreshTokenIssuedTime = refreshTokenValidationDataDO.getIssuedTime(); refreshTokenValidityPeriodInMillis = refreshTokenValidationDataDO.getValidityPeriodInMillis(); } } else { //todo add proper error message/error code return handleError(OAuthError.TokenResponse.INVALID_REQUEST, "Refresh token is expired."); } } catch (OAuthSystemException e) { throw new IdentityOAuth2Exception("Error when generating the tokens.", e); } if (OAuth2Util.checkUserNameAssertionEnabled()) { String userName = tokReqMsgCtx.getAuthorizedUser().toString(); //use ':' for token & userStoreDomain separation String accessTokenStrToEncode = accessToken + ":" + userName; accessToken = Base64Utils.encode(accessTokenStrToEncode.getBytes(Charsets.UTF_8)); String refreshTokenStrToEncode = refreshToken + ":" + userName; refreshToken = Base64Utils.encode(refreshTokenStrToEncode.getBytes(Charsets.UTF_8)); //logic to store access token into different tables when multiple user stores are configured. if (OAuth2Util.checkAccessTokenPartitioningEnabled()) { userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(userName); } } Timestamp timestamp = new Timestamp(new Date().getTime()); // if reusing existing refresh token, use its original issued time if (refreshTokenIssuedTime == null) { refreshTokenIssuedTime = timestamp; } // Default Validity Period (in seconds) long validityPeriodInMillis = OAuthServerConfiguration.getInstance() .getUserAccessTokenValidityPeriodInSeconds() * 1000; // if a VALID validity period is set through the callback, then use it long callbackValidityPeriod = tokReqMsgCtx.getValidityPeriod(); if (callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) { validityPeriodInMillis = callbackValidityPeriod * 1000; } // If issuing new refresh token, use default refresh token validity Period // otherwise use existing refresh token's validity period if (refreshTokenValidityPeriodInMillis == 0) { refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance() .getRefreshTokenValidityPeriodInSeconds() * 1000; } String tokenType; if (isOfTypeApplicationUser()) { tokenType = OAuthConstants.UserType.APPLICATION_USER; } else { tokenType = OAuthConstants.UserType.APPLICATION; } String clientId = oauth2AccessTokenReqDTO.getClientId(); AccessTokenDO accessTokenDO = new AccessTokenDO(clientId, tokReqMsgCtx.getAuthorizedUser(), tokReqMsgCtx.getScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, tokenType); accessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE); accessTokenDO.setRefreshToken(refreshToken); accessTokenDO.setTokenId(tokenId); accessTokenDO.setAccessToken(accessToken); RefreshTokenValidationDataDO oldAccessToken = (RefreshTokenValidationDataDO) tokReqMsgCtx .getProperty(PREV_ACCESS_TOKEN); String authorizedUser = tokReqMsgCtx.getAuthorizedUser().toString(); // set the previous access token state to "INACTIVE" and store new access token in single db connection tokenMgtDAO.invalidateAndCreateNewToken(oldAccessToken.getTokenId(), "INACTIVE", clientId, UUID.randomUUID().toString(), accessTokenDO, userStoreDomain); //remove the previous access token from cache and add the new access token info to the cache, // if it's enabled. if (cacheEnabled) { // Remove the old access token from the OAuthCache boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser); String cacheKeyString; if (isUsernameCaseSensitive) { cacheKeyString = clientId + ":" + authorizedUser + ":" + scope; } else { cacheKeyString = clientId + ":" + authorizedUser.toLowerCase() + ":" + scope; } CacheKey oauthCacheKey = new OAuthCacheKey(cacheKeyString); oauthCache.clearCacheEntry(oauthCacheKey); // Remove the old access token from the AccessTokenCache CacheKey accessTokenCacheKey = new OAuthCacheKey(oldAccessToken.getAccessToken()); oauthCache.clearCacheEntry(accessTokenCacheKey); // Add new access token to the OAuthCache oauthCache.addToCache(oauthCacheKey, accessTokenDO); // Add new access token to the AccessTokenCache accessTokenCacheKey = new OAuthCacheKey(accessToken); oauthCache.addToCache(accessTokenCacheKey, accessTokenDO); if (log.isDebugEnabled()) { log.debug("Access Token info for the refresh token was added to the cache for " + "the client id : " + clientId + ". Old access token entry was " + "also removed from the cache."); } } if (log.isDebugEnabled()) { log.debug("Persisted an access token for the refresh token, " + "Client ID : " + clientId + "authorized user : " + tokReqMsgCtx.getAuthorizedUser() + "timestamp : " + timestamp + "validity period (s) : " + accessTokenDO.getValidityPeriod() + "scope : " + OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()) + "Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + "User Type : " + tokenType); } tokenRespDTO.setAccessToken(accessToken); tokenRespDTO.setRefreshToken(refreshToken); if (validityPeriodInMillis > 0) { tokenRespDTO.setExpiresIn(accessTokenDO.getValidityPeriod()); tokenRespDTO.setExpiresInMillis(accessTokenDO.getValidityPeriodInMillis()); } else { tokenRespDTO.setExpiresIn(Long.MAX_VALUE); tokenRespDTO.setExpiresInMillis(Long.MAX_VALUE); } tokenRespDTO.setAuthorizedScopes(scope); ArrayList<ResponseHeader> respHeaders = new ArrayList<ResponseHeader>(); ResponseHeader header = new ResponseHeader(); header.setKey("DeactivatedAccessToken"); header.setValue(oldAccessToken.getAccessToken()); respHeaders.add(header); tokReqMsgCtx.addProperty("RESPONSE_HEADERS", respHeaders.toArray(new ResponseHeader[respHeaders.size()])); return tokenRespDTO; }
From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java
public static String getUserStoreDomainFromAccessToken(String apiKey) throws IdentityOAuth2Exception { String userStoreDomain = null; String userId;/*from ww w . java 2 s . co m*/ String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null) { userId = tmpArr[1]; if (userId != null) { userStoreDomain = getUserStoreDomainFromUserId(userId); } } return userStoreDomain; }
From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java
public static String getUserIdFromAccessToken(String apiKey) { String userId = null;/*from ww w. ja v a 2s .c o m*/ String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8); String[] tmpArr = decodedKey.split(":"); if (tmpArr != null && tmpArr.length > 1) { userId = tmpArr[1]; } return userId; }
From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java
/** * Helper method to add public certificate to JWT_HEADER to signature verification. * * @param tenantDomain//from w w w .j av a 2s . c o m * @param tenantId * @throws IdentityOAuth2Exception */ public static String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception { try { Certificate certificate = getCertificate(tenantDomain, tenantId); // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization //generate the SHA-1 thumbprint of the certificate MessageDigest digestValue = MessageDigest.getInstance("SHA-1"); byte[] der = certificate.getEncoded(); digestValue.update(der); byte[] digestInBytes = digestValue.digest(); String publicCertThumbprint = hexify(digestInBytes); String base64EncodedThumbPrint = new String( new Base64(0, null, true).encode(publicCertThumbprint.getBytes(Charsets.UTF_8)), Charsets.UTF_8); return base64EncodedThumbPrint; } catch (Exception e) { String error = "Error in obtaining certificate for tenant " + tenantDomain; throw new IdentityOAuth2Exception(error, e); } }
From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java
/** * Returns Base64 encoded token which have username appended. * * @param authenticatedUser/* w w w . j a v a 2s . co m*/ * @param token * @return */ public static String addUsernameToToken(AuthenticatedUser authenticatedUser, String token) { if (authenticatedUser == null) { throw new IllegalArgumentException("Authenticated user cannot be null"); } if (StringUtils.isBlank(token)) { throw new IllegalArgumentException("Token cannot be blank"); } String usernameForToken = authenticatedUser.toString(); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authenticatedUser.isFederatedUser()) { usernameForToken = OAuth2Util.getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); usernameForToken = usernameForToken + UserCoreConstants.DOMAIN_SEPARATOR + authenticatedUser.getAuthenticatedSubjectIdentifier(); } //use ':' for token & userStoreDomain separation String tokenStrToEncode = token + ":" + usernameForToken; return Base64Utils.encode(tokenStrToEncode.getBytes(Charsets.UTF_8)); }
From source file:org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder.java
@Override public String buildIDToken(OAuthTokenReqMessageContext request, OAuth2AccessTokenRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String tenantDomain = request.getOauth2AccessTokenReqDTO().getTenantDomain(); IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig samlAuthenticatorConfig = IdentityApplicationManagementUtil .getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); String issuer = IdentityApplicationManagementUtil .getProperty(samlAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue(); long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000; long curTimeInMillis = Calendar.getInstance().getTimeInMillis(); // setting subject String subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier(); if (!GrantType.AUTHORIZATION_CODE.toString().equals(request.getOauth2AccessTokenReqDTO().getGrantType()) && !org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString() .equals(request.getOauth2AccessTokenReqDTO().getGrantType())) { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder .getApplicationMgtService(); ServiceProvider serviceProvider = null; try {/*from ww w. ja v a 2 s . c o m*/ String spName = applicationMgtService.getServiceProviderNameByClientId( request.getOauth2AccessTokenReqDTO().getClientId(), INBOUND_AUTH2_TYPE, tenantDomain); serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while getting service provider information.", e); } if (serviceProvider != null) { String subjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .getSubjectClaimUri(); ClaimConfig claimConfig = serviceProvider.getClaimConfig(); if (claimConfig != null) { boolean isLocalClaimDialect = claimConfig.isLocalClaimDialect(); ClaimMapping[] claimMappings = claimConfig.getClaimMappings(); if (!isLocalClaimDialect && claimMappings.length > 0) { for (ClaimMapping claimMapping : claimMappings) { if (StringUtils.isNotBlank(subjectClaim) && StringUtils .equals(claimMapping.getRemoteClaim().getClaimUri(), subjectClaim)) { subjectClaim = claimMapping.getLocalClaim().getClaimUri(); } } } } if (subjectClaim != null) { String username = request.getAuthorizedUser().getUserName(); String userStore = request.getAuthorizedUser().getUserStoreDomain(); tenantDomain = request.getAuthorizedUser().getTenantDomain(); String fqdnUsername = request.getAuthorizedUser().toString(); try { UserStoreManager usm = IdentityTenantUtil.getRealm(tenantDomain, fqdnUsername) .getUserStoreManager(); subject = usm.getSecondaryUserStoreManager(userStore).getUserClaimValue(username, subjectClaim, null); if (StringUtils.isBlank(subject)) { subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier(); } boolean useUserstoreDomainInLocalSubjectIdentifier = serviceProvider .getLocalAndOutBoundAuthenticationConfig() .isUseUserstoreDomainInLocalSubjectIdentifier(); boolean useTenantDomainInLocalSubjectIdentifier = serviceProvider .getLocalAndOutBoundAuthenticationConfig() .isUseTenantDomainInLocalSubjectIdentifier(); if (useTenantDomainInLocalSubjectIdentifier) { subject = UserCoreUtil.addTenantDomainToEntry(subject, tenantDomain); } if (useUserstoreDomainInLocalSubjectIdentifier) { subject = IdentityUtil.addDomainToName(subject, userStore); } } catch (IdentityException e) { String error = "Error occurred while getting user claim for user " + request.getAuthorizedUser().toString() + ", claim " + subjectClaim; throw new IdentityOAuth2Exception(error, e); } catch (UserStoreException e) { if (e.getMessage().contains("UserNotFound")) { if (log.isDebugEnabled()) { log.debug("User " + username + " not found in user store " + userStore + " in tenant " + tenantDomain); } subject = request.getAuthorizedUser().toString(); } else { String error = "Error occurred while getting user claim for user " + request.getAuthorizedUser().toString() + ", claim " + subjectClaim; throw new IdentityOAuth2Exception(error, e); } } } } } String nonceValue = null; long authTime = 0; LinkedHashSet acrValue = new LinkedHashSet(); // AuthorizationCode only available for authorization code grant type if (request.getProperty(AUTHORIZATION_CODE) != null) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(request); if (authorizationGrantCacheEntry != null) { nonceValue = authorizationGrantCacheEntry.getNonceValue(); acrValue = authorizationGrantCacheEntry.getAcrValue(); if (authorizationGrantCacheEntry.getEssentialClaims() != null) { if (OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN).contains(OAuthConstants.OAuth20Params.AUTH_TIME)) { authTime = authorizationGrantCacheEntry.getAuthTime(); } } } } String atHash = null; if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { String digAlg = OAuth2Util.mapDigestAlgorithm(signatureAlgorithm); MessageDigest md; try { md = MessageDigest.getInstance(digAlg); } catch (NoSuchAlgorithmException e) { throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg); } md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8)); byte[] digest = md.digest(); int leftHalfBytes = 16; if (SHA384.equals(digAlg)) { leftHalfBytes = 24; } else if (SHA512.equals(digAlg)) { leftHalfBytes = 32; } byte[] leftmost = new byte[leftHalfBytes]; for (int i = 0; i < leftHalfBytes; i++) { leftmost[i] = digest[i]; } atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8); } if (log.isDebugEnabled()) { StringBuilder stringBuilder = (new StringBuilder()).append("Using issuer ").append(issuer).append("\n") .append("Subject ").append(subject).append("\n").append("ID Token life time ") .append(lifetimeInMillis / 1000).append("\n").append("Current time ") .append(curTimeInMillis / 1000).append("\n").append("Nonce Value ").append(nonceValue) .append("\n").append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); log.debug(stringBuilder.toString()); } ArrayList<String> audience = new ArrayList<String>(); audience.add(request.getOauth2AccessTokenReqDTO().getClientId()); if (CollectionUtils.isNotEmpty(getOIDCEndpointUrl())) { audience.addAll(getOIDCEndpointUrl()); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim("azp", request.getOauth2AccessTokenReqDTO().getClientId()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); if (authTime != 0) { jwtClaimsSet.setClaim("auth_time", authTime / 1000); } if (atHash != null) { jwtClaimsSet.setClaim("at_hash", atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim("nonce", nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim("acr", "urn:mace:incommon:iap:silver"); } request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken()); request.addProperty(MultitenantConstants.TENANT_DOMAIN, request.getOauth2AccessTokenReqDTO().getTenantDomain()); CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance() .getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); jwtClaimsSet.setSubject(subject); if (!isValidIdToken(jwtClaimsSet)) { throw new IDTokenValidationFailureException("Error while validating JWT token for required claims"); } if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String signingTenantDomain; if (isJWTSignedWithSPKey) { signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { signingTenantDomain = request.getAuthorizedUser().getTenantDomain(); } return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); }