use of org.apache.oltu.oauth2.common.OAuth in project pyramus by otavanopisto.
the class AbstractRESTPermissionsTest method createAccessTokens.
@Before
public void createAccessTokens() {
OAuthClientRequest tokenRequest = null;
if (!Role.EVERYONE.name().equals(role)) {
try {
tokenRequest = OAuthClientRequest.tokenLocation("https://dev.pyramus.fi:8443/1/oauth/token").setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(fi.otavanopisto.pyramus.Common.CLIENT_ID).setClientSecret(fi.otavanopisto.pyramus.Common.CLIENT_SECRET).setRedirectURI(fi.otavanopisto.pyramus.Common.REDIRECT_URL).setCode(fi.otavanopisto.pyramus.Common.getRoleAuth(Common.strToRole(role))).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
Response response = given().contentType("application/x-www-form-urlencoded").body(tokenRequest.getBody()).post("/oauth/token");
String accessToken = response.body().jsonPath().getString("access_token");
setAccessToken(accessToken);
} else {
setAccessToken("");
}
/**
* AdminAccessToken
*/
if (!Role.ADMINISTRATOR.name().equals(role)) {
tokenRequest = null;
try {
tokenRequest = OAuthClientRequest.tokenLocation("https://dev.pyramus.fi:8443/1/oauth/token").setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(fi.otavanopisto.pyramus.Common.CLIENT_ID).setClientSecret(fi.otavanopisto.pyramus.Common.CLIENT_SECRET).setRedirectURI(fi.otavanopisto.pyramus.Common.REDIRECT_URL).setCode(fi.otavanopisto.pyramus.Common.getRoleAuth(Role.ADMINISTRATOR)).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
Response response = given().contentType("application/x-www-form-urlencoded").body(tokenRequest.getBody()).post("/oauth/token");
String adminAccessToken = response.body().jsonPath().getString("access_token");
setAdminAccessToken(adminAccessToken);
} else {
setAdminAccessToken(accessToken);
}
}
use of org.apache.oltu.oauth2.common.OAuth in project pyramus by otavanopisto.
the class AbstractRESTPermissionsTestJUnit5 method getOauthToken.
protected String getOauthToken(Role role) {
if (!Role.EVERYONE.equals(role)) {
OAuthClientRequest tokenRequest = null;
try {
tokenRequest = OAuthClientRequest.tokenLocation("https://dev.pyramus.fi:8443/1/oauth/token").setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(fi.otavanopisto.pyramus.Common.CLIENT_ID).setClientSecret(fi.otavanopisto.pyramus.Common.CLIENT_SECRET).setRedirectURI(fi.otavanopisto.pyramus.Common.REDIRECT_URL).setCode(fi.otavanopisto.pyramus.Common.getRoleAuth(role)).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
Response response = given().contentType("application/x-www-form-urlencoded").body(tokenRequest.getBody()).post("/oauth/token");
return response.body().jsonPath().getString("access_token");
}
return "";
}
use of org.apache.oltu.oauth2.common.OAuth 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.OAuth in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthServerConfiguration method getOAuthTokenGenerator.
/**
* instantiate the OAuth token generator. to override the default implementation, one can specify the custom class
* in the identity.xml.
*
* @return
*/
public OAuthIssuer getOAuthTokenGenerator() {
if (oauthTokenGenerator == null) {
synchronized (this) {
if (oauthTokenGenerator == null) {
try {
if (oauthTokenGeneratorClassName != null) {
Class clazz = this.getClass().getClassLoader().loadClass(oauthTokenGeneratorClassName);
oauthTokenGenerator = (OAuthIssuer) clazz.newInstance();
log.info("An instance of " + oauthTokenGeneratorClassName + " is created for OAuth token generation.");
} else {
oauthTokenGenerator = new OAuthIssuerImpl(getTokenValueGenerator());
log.info("The default OAuth token issuer will be used. No custom token generator is set.");
}
} catch (Exception e) {
String errorMsg = "Error when instantiating the OAuthIssuer : " + tokenPersistenceProcessorClassName + ". Defaulting to OAuthIssuerImpl";
log.error(errorMsg, e);
oauthTokenGenerator = new OAuthIssuerImpl(getTokenValueGenerator());
}
}
}
}
return oauthTokenGenerator;
}
use of org.apache.oltu.oauth2.common.OAuth in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method getAllowedOAuthScopes.
private static List<String> getAllowedOAuthScopes(OAuth2Parameters params) throws OAuthSystemException {
Set<String> allowedScopes = params.getScopes();
List<String> allowedOAuthScopes = new ArrayList<>();
if (CollectionUtils.isNotEmpty(allowedScopes)) {
try {
startTenantFlow(params.getTenantDomain());
/* If DropUnregisteredScopes scopes config is enabled
then any unregistered scopes(excluding internal scopes
and allowed scopes) is be dropped. Therefore they will
not be shown in the user consent screen.*/
if (oauthServerConfiguration.isDropUnregisteredScopes()) {
if (log.isDebugEnabled()) {
log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
}
allowedScopes = dropUnregisteredScopes(params);
}
// Get registered OIDC scopes.
String[] oidcScopes = oAuthAdminService.getScopeNames();
List<String> oidcScopeList = new ArrayList<>(Arrays.asList(oidcScopes));
for (String scope : allowedScopes) {
if (!oidcScopeList.contains(scope)) {
allowedOAuthScopes.add(scope);
}
}
} catch (IdentityOAuthAdminException e) {
throw new OAuthSystemException("Error while retrieving OIDC scopes.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
if (log.isDebugEnabled()) {
log.debug("Allowed OAuth scopes : " + allowedOAuthScopes.stream().collect(Collectors.joining(" ")) + " for client : " + params.getClientId());
}
return allowedOAuthScopes;
}
Aggregations