use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project pyramus by otavanopisto.
the class AuthorizeClientApplicationViewController method processSend.
@Override
public void processSend(PageRequestContext requestContext) {
if (!requestContext.isLoggedIn()) {
HttpServletRequest request = requestContext.getRequest();
StringBuilder currentUrl = new StringBuilder(request.getRequestURL());
String queryString = request.getQueryString();
if (!StringUtils.isBlank(queryString)) {
currentUrl.append('?');
currentUrl.append(queryString);
}
throw new LoginRequiredException(currentUrl.toString());
}
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
ClientApplicationDAO clientApplicationDAO = DAOFactory.getInstance().getClientApplicationDAO();
ClientApplicationAuthorizationCodeDAO clientApplicationAuthorizationCodeDAO = DAOFactory.getInstance().getClientApplicationAuthorizationCodeDAO();
HttpServletRequest request = requestContext.getRequest();
HttpSession session = request.getSession();
Boolean authorized = "Authorize".equals(request.getParameter("authorize"));
if (authorized) {
Long userId = (Long) session.getAttribute("loggedUserId");
String authorizationCode = (String) session.getAttribute("pendingAuthCode");
String redirectURI = (String) session.getAttribute("pendingOauthRedirectUrl");
ClientApplication clientApplication = clientApplicationDAO.findByClientId((String) session.getAttribute("clientAppId"));
if (userId != null && authorizationCode != null && redirectURI != null && clientApplication != null) {
try {
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
builder.setCode(authorizationCode);
final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
User user = userDAO.findById(userId);
clientApplicationAuthorizationCodeDAO.create(user, clientApplication, authorizationCode, redirectURI);
requestContext.setRedirectURL(response.getLocationUri());
} catch (OAuthSystemException e) {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} else {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
}
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project pyramus by otavanopisto.
the class AuthorizeClientApplicationViewController method processForm.
@Override
public void processForm(PageRequestContext requestContext) {
ClientApplicationDAO clientApplicationDAO = DAOFactory.getInstance().getClientApplicationDAO();
if (!requestContext.isLoggedIn()) {
HttpServletRequest request = requestContext.getRequest();
StringBuilder currentUrl = new StringBuilder(request.getRequestURL());
String queryString = request.getQueryString();
if (!StringUtils.isBlank(queryString)) {
currentUrl.append('?');
currentUrl.append(queryString);
}
String clientId = requestContext.getString("client_id");
if (StringUtils.isNotBlank(clientId)) {
ClientApplication clientApplication = clientApplicationDAO.findByClientId(clientId);
if (clientApplication == null) {
throw new SmvcRuntimeException(HttpServletResponse.SC_FORBIDDEN, "Client application not found");
}
throw new LoginRequiredException(currentUrl.toString(), "OAUTHCLIENT", clientId);
} else {
throw new SmvcRuntimeException(HttpServletResponse.SC_FORBIDDEN, "Client application not defined");
}
}
HttpServletRequest request = requestContext.getRequest();
OAuthAuthzRequest oauthRequest;
OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
try {
oauthRequest = new OAuthAuthzRequest(request);
ClientApplication clientApplication = clientApplicationDAO.findByClientId(oauthRequest.getClientId());
if (clientApplication != null) {
request.getSession().setAttribute("clientAppId", oauthRequest.getClientId());
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
if (!responseType.equals(ResponseType.CODE.toString())) {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_NOT_IMPLEMENTED, String.format("Response type: %s not supported", responseType));
}
String authorizationCode = oauthIssuerImpl.authorizationCode();
request.getSession().setAttribute("pendingAuthCode", authorizationCode);
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
request.getSession().setAttribute("pendingOauthRedirectUrl", redirectURI);
request.setAttribute("clientAppName", clientApplication.getClientName());
if (clientApplication.getSkipPrompt()) {
ClientApplicationAuthorizationCodeDAO clientApplicationAuthorizationCodeDAO = DAOFactory.getInstance().getClientApplicationAuthorizationCodeDAO();
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
HttpSession session = request.getSession();
Long userId = (Long) session.getAttribute("loggedUserId");
if (userId != null && authorizationCode != null && redirectURI != null && clientApplication != null) {
try {
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
builder.setCode(authorizationCode);
final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
User user = userDAO.findById(userId);
clientApplicationAuthorizationCodeDAO.create(user, clientApplication, authorizationCode, redirectURI);
requestContext.setRedirectURL(response.getLocationUri());
} catch (OAuthSystemException e) {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} else {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
}
}
} else {
requestContext.setIncludeJSP("/templates/generic/errorpage.jsp");
throw new SmvcRuntimeException(HttpServletResponse.SC_FORBIDDEN, "Client application not found");
}
} catch (OAuthProblemException | OAuthSystemException e) {
throw new SmvcRuntimeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
// TODO: show auth page only if everything is ok
requestContext.setIncludeJSP("/templates/users/authorizeclientapp.jsp");
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project vcita-client-java-sdk by SimonIT.
the class OAuthOkHttpClient method execute.
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(entry.getValue());
} else {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null;
requestBuilder.method(requestMethod, body);
try {
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
}
}
use of org.apache.amber.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.amber.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);
}
}
Aggregations