use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class DeviceEndpointTest method testDevice.
/**
* Test the device_authorize endpoint.
*
* @param clientId Consumer key of the application.
* @param expectedStatus Expected status for response.
* @param status Status of user code.
* @throws IdentityOAuth2Exception If failed at device endpoint
* @throws OAuthSystemException If failed at device endpoint.
*/
@Test(dataProvider = "dataValues")
public void testDevice(String clientId, int expectedStatus, boolean status) throws Exception {
DeviceEndpoint deviceEndpoint = PowerMockito.spy(new DeviceEndpoint());
mockOAuthServerConfiguration();
mockStatic(ServiceURLBuilder.class);
mockStatic(ServiceURL.class);
ServiceURLBuilder mockServiceURLBuilder = Mockito.mock(ServiceURLBuilder.class);
ServiceURL mockServiceURL = Mockito.mock(ServiceURL.class);
when(ServiceURLBuilder.create()).thenReturn(mockServiceURLBuilder);
when(mockServiceURLBuilder.addPath(anyString())).thenReturn(mockServiceURLBuilder);
when(mockServiceURLBuilder.addParameter(anyString(), anyString())).thenReturn(mockServiceURLBuilder);
when(mockServiceURLBuilder.build()).thenReturn(mockServiceURL);
when(mockServiceURL.getAbsolutePublicURL()).thenReturn("http://localhost:9443/authenticationendpoint/device.do");
mockStatic(HttpServletRequest.class);
OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext();
oAuthClientAuthnContext.setClientId(clientId);
oAuthClientAuthnContext.setAuthenticated(status);
when(request.getAttribute(anyString())).thenReturn(oAuthClientAuthnContext);
DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl();
deviceEndpoint.setDeviceAuthService(deviceAuthService);
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection(true)).thenReturn(connection);
when(IdentityDatabaseUtil.getDBConnection(false)).thenReturn(connection);
when(httpServletRequest.getParameter(anyString())).thenReturn(clientId);
Response response;
mockStatic(IdentityUtil.class);
when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn(TEST_URL);
mockStatic(DeviceFlowPersistenceFactory.class);
when(DeviceFlowPersistenceFactory.getInstance()).thenReturn(deviceFlowPersistenceFactory);
when(deviceFlowPersistenceFactory.getDeviceFlowDAO()).thenReturn(deviceFlowDAO);
when(deviceFlowDAO.checkClientIdExist(anyString())).thenReturn(status);
PowerMockito.when(deviceEndpoint, "getValidationObject", httpServletRequest).thenReturn(oAuthClientAuthnContext);
response = deviceEndpoint.authorize(httpServletRequest, new MultivaluedHashMap<String, String>(), httpServletResponse);
Assert.assertEquals(expectedStatus, response.getStatus());
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtilTest method provideErrorRedirectData.
@DataProvider(name = "provideErrorRedirectData")
public Object[][] provideErrorRedirectData() {
OAuth2Parameters params1 = new OAuth2Parameters();
OAuth2Parameters params2 = new OAuth2Parameters();
String state = "active";
String responseType = "dummyResponceType";
String appName = "myApp";
params1.setState(state);
params1.setResponseType(responseType);
params1.setApplicationName(appName);
params1.setRedirectURI("http://localhost:8080/callback");
params2.setState(state);
params2.setResponseType(responseType);
params2.setApplicationName(appName);
params2.setRedirectURI(null);
return new Object[][] { { true, true, params1, null, "http://localhost:8080/location", false }, { true, false, params1, null, "http://localhost:8080/location", false }, { false, true, params1, null, "http://localhost:8080/location", false }, { true, true, params2, null, ERROR_PAGE_URL, false }, { true, true, null, null, ERROR_PAGE_URL, false }, { true, true, params1, new OAuthSystemException(), ERROR_PAGE_URL, false }, { true, true, params1, new OAuthSystemException(), ERROR_PAGE_URL, true } };
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class AccessTokenDAOImpl method insertAccessToken.
private void insertAccessToken(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {
if (!isPersistenceEnabled()) {
return;
}
if (accessTokenDO == null) {
throw new IdentityOAuth2Exception("Access token data object should be available for further execution.");
}
if (accessTokenDO.getAuthzUser() == null) {
throw new IdentityOAuth2Exception("Authorized user should be available for further execution.");
}
String accessTokenHash = accessToken;
try {
OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
// check for persist alias for the token type
if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
accessTokenHash = oauthTokenIssuer.getAccessTokenHash(accessToken);
}
} catch (OAuthSystemException e) {
if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Error while getting access token hash for token(hashed): " + DigestUtils.sha256Hex(accessTokenHash));
}
throw new IdentityOAuth2Exception("Error while getting access token hash.", e);
} catch (InvalidOAuthClientException e) {
throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e);
}
if (log.isDebugEnabled()) {
if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Persisting access token(hashed): " + DigestUtils.sha256Hex(accessTokenHash) + " for " + "client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
} else {
log.debug("Persisting access token for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
}
}
userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
String userDomain = OAuth2Util.getUserStoreDomain(accessTokenDO.getAuthzUser());
String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(accessTokenDO.getAuthzUser());
PreparedStatement insertTokenPrepStmt = null;
PreparedStatement addScopePrepStmt = null;
if (log.isDebugEnabled()) {
String username;
if (isFederatedUser(accessTokenDO)) {
username = accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier();
} else {
username = accessTokenDO.getAuthzUser().toFullQualifiedUsername();
}
log.debug("Userstore domain for user: " + username + " is " + userDomain);
}
String sql;
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN_WITH_IDP_NAME;
} else {
sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN;
}
sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userDomain);
String sqlAddScopes = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_TOKEN_SCOPE, userDomain);
try {
insertTokenPrepStmt = connection.prepareStatement(sql);
insertTokenPrepStmt.setString(1, getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenHash));
if (accessTokenDO.getRefreshToken() != null) {
insertTokenPrepStmt.setString(2, getPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
} else {
insertTokenPrepStmt.setString(2, accessTokenDO.getRefreshToken());
}
insertTokenPrepStmt.setString(3, accessTokenDO.getAuthzUser().getUserName());
int tenantId = OAuth2Util.getTenantId(accessTokenDO.getAuthzUser().getTenantDomain());
insertTokenPrepStmt.setInt(4, tenantId);
insertTokenPrepStmt.setString(5, OAuth2Util.getSanitizedUserStoreDomain(userDomain));
insertTokenPrepStmt.setTimestamp(6, accessTokenDO.getIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC)));
insertTokenPrepStmt.setTimestamp(7, accessTokenDO.getRefreshTokenIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC)));
insertTokenPrepStmt.setLong(8, accessTokenDO.getValidityPeriodInMillis());
insertTokenPrepStmt.setLong(9, accessTokenDO.getRefreshTokenValidityPeriodInMillis());
insertTokenPrepStmt.setString(10, OAuth2Util.hashScopes(accessTokenDO.getScope()));
insertTokenPrepStmt.setString(11, accessTokenDO.getTokenState());
insertTokenPrepStmt.setString(12, accessTokenDO.getTokenType());
insertTokenPrepStmt.setString(13, accessTokenDO.getTokenId());
insertTokenPrepStmt.setString(14, accessTokenDO.getGrantType());
insertTokenPrepStmt.setString(15, accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier());
insertTokenPrepStmt.setString(16, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenHash));
if (accessTokenDO.getRefreshToken() != null) {
insertTokenPrepStmt.setString(17, getHashingPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
} else {
insertTokenPrepStmt.setString(17, accessTokenDO.getRefreshToken());
}
boolean tokenBindingAvailable = isTokenBindingAvailable(accessTokenDO.getTokenBinding());
if (tokenBindingAvailable) {
insertTokenPrepStmt.setString(18, accessTokenDO.getTokenBinding().getBindingReference());
} else {
insertTokenPrepStmt.setString(18, NONE);
}
insertTokenPrepStmt.setString(19, getPersistenceProcessor().getProcessedClientId(consumerKey));
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
insertTokenPrepStmt.setString(20, authenticatedIDP);
insertTokenPrepStmt.setInt(21, tenantId);
}
insertTokenPrepStmt.execute();
String accessTokenId = accessTokenDO.getTokenId();
addScopePrepStmt = connection.prepareStatement(sqlAddScopes);
if (accessTokenDO.getScope() != null && accessTokenDO.getScope().length > 0) {
for (String scope : accessTokenDO.getScope()) {
addScopePrepStmt.setString(1, accessTokenId);
addScopePrepStmt.setString(2, scope);
addScopePrepStmt.setInt(3, tenantId);
addScopePrepStmt.addBatch();
}
}
addScopePrepStmt.executeBatch();
if (tokenBindingAvailable) {
if (log.isDebugEnabled()) {
log.debug("Storing token binding information" + " accessTokenId: " + accessTokenId + " bindingType: " + accessTokenDO.getTokenBinding().getBindingType() + " bindingRef: " + accessTokenDO.getTokenBinding().getBindingReference());
}
try (PreparedStatement preparedStatement = connection.prepareStatement(STORE_TOKEN_BINDING)) {
preparedStatement.setString(1, accessTokenId);
preparedStatement.setString(2, accessTokenDO.getTokenBinding().getBindingType());
preparedStatement.setString(3, accessTokenDO.getTokenBinding().getBindingReference());
preparedStatement.setString(4, accessTokenDO.getTokenBinding().getBindingValue());
preparedStatement.setInt(5, tenantId);
preparedStatement.execute();
}
}
if (retryAttemptCounter > 0) {
log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter);
}
} catch (SQLIntegrityConstraintViolationException e) {
IdentityDatabaseUtil.rollbackTransaction(connection);
if (retryAttemptCounter >= getTokenPersistRetryCount()) {
log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
throw new IdentityOAuth2Exception(errorMsg, e);
}
recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
} catch (DataTruncation e) {
IdentityDatabaseUtil.rollbackTransaction(connection);
throw new IdentityOAuth2Exception("Invalid request", e);
} catch (SQLException e) {
IdentityDatabaseUtil.rollbackTransaction(connection);
// SQLIntegrityConstraintViolationException
if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY")) {
if (retryAttemptCounter >= getTokenPersistRetryCount()) {
log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
throw new IdentityOAuth2Exception(errorMsg, e);
}
recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
} else {
throw new IdentityOAuth2Exception("Error when storing the access token for consumer key : " + consumerKey, e);
}
} catch (Exception e) {
IdentityDatabaseUtil.rollbackTransaction(connection);
// SQLIntegrityConstraintViolationException or SQLException.
if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY") || (e.getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getMessage(), "CON_APP_KEY")) || (e.getCause() != null && e.getCause().getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getCause().getMessage(), "CON_APP_KEY"))) {
if (retryAttemptCounter >= getTokenPersistRetryCount()) {
log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount());
String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
throw new IdentityOAuth2Exception(errorMsg, e);
}
recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1);
} else {
throw new IdentityOAuth2Exception("Error when storing the access token for consumer key : " + consumerKey, e);
}
} finally {
IdentityDatabaseUtil.closeStatement(addScopePrepStmt);
IdentityDatabaseUtil.closeStatement(insertTokenPrepStmt);
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class ResponseTypeHandlerUtil method generateAuthorizationCode.
public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String authorizationCode;
String codeId = UUID.randomUUID().toString();
Timestamp timestamp = new Timestamp(new Date().getTime());
long validityPeriod = OAuthServerConfiguration.getInstance().getAuthorizationCodeValidityPeriodInSeconds();
// if a VALID callback is set through the callback handler, use
// it instead of the default one
long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
validityPeriod = callbackValidityPeriod;
}
// convert to milliseconds
validityPeriod = validityPeriod * 1000;
// set the validity period. this is needed by downstream handlers.
// if this is set before - then this will override it by the calculated new value.
oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);
oauthAuthzMsgCtx.setAuthorizationCodeValidityPeriod(validityPeriod);
// set code issued time.this is needed by downstream handlers.
oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
if (authorizationReqDTO.getUser() != null && authorizationReqDTO.getUser().isFederatedUser()) {
// if a federated user, treat the tenant domain as similar to application domain.
authorizationReqDTO.getUser().setTenantDomain(authorizationReqDTO.getTenantDomain());
}
try {
authorizationCode = oauthIssuerImpl.authorizationCode(oauthAuthzMsgCtx);
} catch (OAuthSystemException e) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
throw new IdentityOAuth2Exception(e.getMessage(), e);
}
AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(), authorizationReqDTO.getConsumerKey(), authorizationCode, codeId, authorizationReqDTO.getPkceCodeChallenge(), authorizationReqDTO.getPkceCodeChallengeMethod());
OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().insertAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(), authorizationReqDTO.getCallbackUrl(), authzCodeDO);
if (cacheEnabled) {
// Cache the authz Code, here we prepend the client_key to avoid collisions with
// AccessTokenDO instances. In database level, these are in two databases. But access
// tokens and authorization codes are in a single cache.
String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(authorizationReqDTO.getConsumerKey(), authorizationCode);
OAuthCache.getInstance().addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
if (log.isDebugEnabled()) {
log.debug("Authorization Code info was added to the cache for client id : " + authorizationReqDTO.getConsumerKey());
}
}
if (log.isDebugEnabled()) {
log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() + ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", validity period : " + validityPeriod);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", authorizationReqDTO.getConsumerKey());
if (authorizationReqDTO.getUser() != null) {
try {
params.put("user", authorizationReqDTO.getUser().getUserId());
} catch (UserIdNotFoundException e) {
if (StringUtils.isNotBlank(authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier())) {
params.put("user", authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
}
}
}
params.put("requestedScopes", OAuth2Util.buildScopeString(authorizationReqDTO.getScopes()));
params.put("redirectUri", authorizationReqDTO.getCallbackUrl());
Map<String, Object> configs = new HashMap<>();
configs.put("authzCodeValidityPeriod", String.valueOf(validityPeriod));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Issued Authorization Code to user.", "issue-authz-code", configs);
}
return authzCodeDO;
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class SHA256Generator method generateValue.
@Override
public String generateValue(String value) throws OAuthSystemException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(value.getBytes(StandardCharsets.UTF_8));
byte[] messageDigest = digest.digest();
// Return the hex representation of the hash.
return Hex.toHexString(messageDigest);
} catch (Exception e) {
throw new OAuthSystemException("Error while generating the token value.", e);
}
}
Aggregations