use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project identity-inbound-auth-oauth by wso2-extensions.
the class ResponseTypeHandlerUtil method generateNewAccessToken.
private static AccessTokenDO generateNewAccessToken(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, AccessTokenDO existingTokenBean, OauthTokenIssuer oauthIssuerImpl, String authorizedUserId, boolean cacheEnabled) throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
String consumerKey = authorizationReqDTO.getConsumerKey();
String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(authorizationReqDTO.getUser());
OAuthAppDO oAuthAppBean = getOAuthApp(consumerKey);
Timestamp timestamp = new Timestamp(new Date().getTime());
long validityPeriodInMillis = getConfiguredAccessTokenValidityPeriodInMillis(oauthAuthzMsgCtx, oAuthAppBean);
oauthAuthzMsgCtx.addProperty(OAuthConstants.UserType.USER_TYPE, OAuthConstants.UserType.APPLICATION_USER);
AccessTokenDO newTokenBean = createNewTokenBean(oauthAuthzMsgCtx, oAuthAppBean, existingTokenBean, oauthIssuerImpl, timestamp, validityPeriodInMillis);
setDetailsToMessageContext(oauthAuthzMsgCtx, newTokenBean);
// Persist the access token in database
persistAccessTokenInDB(oauthAuthzMsgCtx, existingTokenBean, newTokenBean);
deactivateCurrentAuthorizationCode(newTokenBean.getAuthorizationCode(), newTokenBean.getTokenId());
// update cache with newly added token
if (isHashDisabled && cacheEnabled) {
addTokenToCache(getOAuthCacheKey(consumerKey, scope, authorizedUserId, authenticatedIDP), newTokenBean);
}
return newTokenBean;
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project identity-inbound-auth-oauth by wso2-extensions.
the class AccessTokenDAOImpl method getAccessTokens.
@Override
public Set<AccessTokenDO> getAccessTokens(String consumerKey, AuthenticatedUser userName, String userStoreDomain, boolean includeExpired) throws IdentityOAuth2Exception {
if (log.isDebugEnabled()) {
log.debug("Retrieving access tokens for client: " + consumerKey + " user: " + userName.toString());
}
String tenantDomain = userName.getTenantDomain();
String tenantAwareUsernameWithNoUserDomain = userName.getUserName();
String userDomain = OAuth2Util.getUserStoreDomain(userName);
int tenantId = OAuth2Util.getTenantId(tenantDomain);
boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreCaseSensitive(userName.getUserStoreDomain(), tenantId);
userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(userName);
Connection connection = IdentityDatabaseUtil.getDBConnection(false);
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
Map<String, AccessTokenDO> accessTokenDOMap = new HashMap<>();
try {
String sql;
if (includeExpired) {
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER_IDP_NAME;
} else {
sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER;
}
} else {
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_IDP_NAME;
} else {
sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER;
}
}
sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userStoreDomain);
if (!isUsernameCaseSensitive) {
sql = sql.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
}
prepStmt = connection.prepareStatement(sql);
prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
if (isUsernameCaseSensitive) {
prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain);
} else {
prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain.toLowerCase());
}
prepStmt.setInt(3, tenantId);
prepStmt.setString(4, userDomain);
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
prepStmt.setString(5, authenticatedIDP);
}
resultSet = prepStmt.executeQuery();
while (resultSet.next()) {
String accessToken = getPersistenceProcessor().getPreprocessedAccessTokenIdentifier(resultSet.getString(1));
if (accessTokenDOMap.get(accessToken) == null) {
String refreshToken = getPersistenceProcessor().getPreprocessedRefreshToken(resultSet.getString(2));
Timestamp issuedTime = resultSet.getTimestamp(3, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
Timestamp refreshTokenIssuedTime = resultSet.getTimestamp(4, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
long validityPeriodInMillis = resultSet.getLong(5);
long refreshTokenValidityPeriodMillis = resultSet.getLong(6);
String tokenType = resultSet.getString(7);
String[] scope = OAuth2Util.buildScopeArray(resultSet.getString(8));
String tokenId = resultSet.getString(9);
String subjectIdentifier = resultSet.getString(10);
String tokenBindingReference = resultSet.getString(11);
AuthenticatedUser user = OAuth2Util.createAuthenticatedUser(tenantAwareUsernameWithNoUserDomain, userDomain, tenantDomain, authenticatedIDP);
ServiceProvider serviceProvider;
try {
serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService().getServiceProviderByClientId(consumerKey, OAuthConstants.Scope.OAUTH2, tenantDomain);
} catch (IdentityApplicationManagementException e) {
throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data " + "for client id " + consumerKey, e);
}
user.setAuthenticatedSubjectIdentifier(subjectIdentifier, serviceProvider);
AccessTokenDO dataDO = new AccessTokenDO(consumerKey, user, scope, issuedTime, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodMillis, tokenType);
dataDO.setAccessToken(accessToken);
dataDO.setRefreshToken(refreshToken);
dataDO.setTokenId(tokenId);
if (StringUtils.isNotBlank(tokenBindingReference) && !NONE.equals(tokenBindingReference)) {
setTokenBindingToAccessTokenDO(dataDO, connection, tokenId);
}
accessTokenDOMap.put(accessToken, dataDO);
} else {
String scope = resultSet.getString(8).trim();
AccessTokenDO accessTokenDO = accessTokenDOMap.get(accessToken);
accessTokenDO.setScope((String[]) ArrayUtils.add(accessTokenDO.getScope(), scope));
}
}
} catch (SQLException e) {
String errorMsg = "Error occurred while retrieving 'ACTIVE' access tokens for " + "Client ID : " + consumerKey + " and User ID : " + userName;
if (includeExpired) {
errorMsg = errorMsg.replace("ACTIVE", "ACTIVE or EXPIRED");
}
throw new IdentityOAuth2Exception(errorMsg, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return new HashSet<>(accessTokenDOMap.values());
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2ScopeService method getScope.
/**
* @param name Name of the scope which need to get retrieved
* @return Retrieved Scope
* @throws IdentityOAuth2ScopeException
*/
public Scope getScope(String name) throws IdentityOAuth2ScopeException {
Scope scope;
int tenantID = Oauth2ScopeUtils.getTenantID();
validateScopeName(name);
scope = OAuthScopeCache.getInstance().getValueFromCache(new OAuthScopeCacheKey(name), tenantID);
if (scope == null) {
try {
scope = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().getScopeByName(name, tenantID);
if (scope != null) {
if (log.isDebugEnabled()) {
log.debug("Scope is getting from the database. \n" + scope.toString());
}
OAuthScopeCache.getInstance().addToCache(new OAuthScopeCacheKey(name), scope, tenantID);
}
} catch (IdentityOAuth2ScopeServerException e) {
throw Oauth2ScopeUtils.generateServerException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_GET_SCOPE_BY_NAME, name, e);
}
}
if (scope == null) {
throw Oauth2ScopeUtils.generateClientException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_NOT_FOUND_SCOPE, name);
}
return scope;
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project identity-inbound-auth-oauth by wso2-extensions.
the class AuthorizationHandlerManager method validateAuthzRequest.
private OAuth2AuthorizeRespDTO validateAuthzRequest(OAuth2AuthorizeReqDTO authzReqDTO, OAuthAuthzReqMessageContext authzReqMsgCtx, ResponseTypeHandler authzHandler) throws IdentityOAuth2Exception {
OAuth2AuthorizeRespDTO authorizeRespDTO = new OAuth2AuthorizeRespDTO();
if (isInvalidResponseType(authzReqDTO, authorizeRespDTO)) {
return authorizeRespDTO;
}
if (isInvalidClient(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler)) {
return authorizeRespDTO;
}
if (isInvalidAccessDelegation(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler)) {
return authorizeRespDTO;
}
List<String> allowedScopes = OAuthServerConfiguration.getInstance().getAllowedScopes();
List<String> requestedAllowedScopes = new ArrayList<>();
String[] requestedScopes = authzReqMsgCtx.getAuthorizationReqDTO().getScopes();
List<String> scopesToBeValidated = new ArrayList<>();
if (requestedScopes != null) {
for (String scope : requestedScopes) {
if (OAuth2Util.isAllowedScope(allowedScopes, scope)) {
requestedAllowedScopes.add(scope);
} else {
scopesToBeValidated.add(scope);
}
}
authzReqMsgCtx.getAuthorizationReqDTO().setScopes(scopesToBeValidated.toArray(new String[0]));
}
// Execute Internal SCOPE Validation.
String[] authorizedInternalScopes = new String[0];
boolean isManagementApp = isManagementApp(authzReqDTO);
if (isManagementApp) {
if (log.isDebugEnabled()) {
log.debug("Handling the internal scope validation.");
}
JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
authorizedInternalScopes = scopeValidator.validateScope(authzReqMsgCtx);
// Execute internal console scopes validation.
if (IdentityUtil.isSystemRolesEnabled()) {
RoleBasedInternalScopeValidator roleBasedInternalScopeValidator = new RoleBasedInternalScopeValidator();
String[] roleBasedInternalConsoleScopes = roleBasedInternalScopeValidator.validateScope(authzReqMsgCtx);
authorizedInternalScopes = (String[]) ArrayUtils.addAll(authorizedInternalScopes, roleBasedInternalConsoleScopes);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Skipping the internal scope validation as the application is not" + " configured as Management App");
}
}
// Clear the internal scopes. Internal scopes should only handle in JDBCPermissionBasedInternalScopeValidator.
// Those scopes should not send to the other scopes validators.
// Thus remove the scopes from the authzReqMsgCtx. Will be added to the response after executing
// the other scope validators.
removeInternalScopes(authzReqMsgCtx);
// Adding the authorized internal scopes to tokReqMsgCtx for any special validators to use.
authzReqMsgCtx.setAuthorizedInternalScopes(authorizedInternalScopes);
boolean isDropUnregisteredScopes = OAuthServerConfiguration.getInstance().isDropUnregisteredScopes();
if (isDropUnregisteredScopes) {
if (log.isDebugEnabled()) {
log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
}
String[] filteredScopes = OAuth2Util.dropUnregisteredScopes(authzReqMsgCtx.getAuthorizationReqDTO().getScopes(), authzReqMsgCtx.getAuthorizationReqDTO().getTenantDomain());
authzReqMsgCtx.getAuthorizationReqDTO().setScopes(filteredScopes);
}
boolean valid = validateScope(authzReqDTO, authorizeRespDTO, authzReqMsgCtx, authzHandler);
if (valid) {
// Add authorized internal scopes to the request for sending in the response.
addAuthorizedInternalScopes(authzReqMsgCtx, authzReqMsgCtx.getAuthorizedInternalScopes());
addAllowedScopes(authzReqMsgCtx, requestedAllowedScopes.toArray(new String[0]));
}
return authorizeRespDTO;
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.Scope in project identity-inbound-auth-oauth by wso2-extensions.
the class AuthorizationCodeDAOImpl method validateAuthorizationCode.
@Override
public AuthorizationCodeValidationResult validateAuthorizationCode(String consumerKey, String authorizationKey) throws IdentityOAuth2Exception {
if (log.isDebugEnabled()) {
if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
log.debug("Validating authorization code(hashed): " + DigestUtils.sha256Hex(authorizationKey) + " for client: " + consumerKey);
} else {
log.debug("Validating authorization code for client: " + consumerKey);
}
}
Connection connection = IdentityDatabaseUtil.getDBConnection(false);
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
AuthorizationCodeValidationResult result = null;
try {
AuthenticatedUser user = null;
String codeState = null;
String authorizedUser = null;
String userstoreDomain = null;
String scopeString = null;
String callbackUrl = null;
String tenantDomain = null;
String codeId = null;
String subjectIdentifier = null;
String pkceCodeChallenge = null;
String pkceCodeChallengeMethod = null;
Timestamp issuedTime = null;
long validityPeriod = 0;
int tenantId;
String sql;
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
sql = SQLQueries.VALIDATE_AUTHZ_CODE_WITH_PKCE_IDP_NAME;
} else {
sql = SQLQueries.VALIDATE_AUTHZ_CODE_WITH_PKCE;
}
prepStmt = connection.prepareStatement(sql);
prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey));
// use hash value for search
prepStmt.setString(2, getHashingPersistenceProcessor().getProcessedAuthzCode(authorizationKey));
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
codeState = resultSet.getString(8);
authorizedUser = resultSet.getString(1);
userstoreDomain = resultSet.getString(2);
tenantId = resultSet.getInt(3);
tenantDomain = OAuth2Util.getTenantDomain(tenantId);
scopeString = resultSet.getString(4);
callbackUrl = resultSet.getString(5);
issuedTime = resultSet.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC)));
validityPeriod = resultSet.getLong(7);
codeId = resultSet.getString(11);
subjectIdentifier = resultSet.getString(12);
pkceCodeChallenge = resultSet.getString(13);
pkceCodeChallengeMethod = resultSet.getString(14);
String authenticatedIDP = null;
if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
authenticatedIDP = resultSet.getString(15);
}
user = OAuth2Util.createAuthenticatedUser(authorizedUser, userstoreDomain, tenantDomain, authenticatedIDP);
ServiceProvider serviceProvider;
try {
serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService().getServiceProviderByClientId(consumerKey, OAuthConstants.Scope.OAUTH2, tenantDomain);
} catch (IdentityApplicationManagementException e) {
throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data " + "for client id " + consumerKey, e);
}
user.setAuthenticatedSubjectIdentifier(subjectIdentifier, serviceProvider);
String tokenId = resultSet.getString(9);
String tokenBindingReference = NONE;
if (StringUtils.isNotBlank(tokenId)) {
tokenBindingReference = getTokenBindingReference(connection, tokenId, tenantId);
}
// for on demand scope migration.
if (StringUtils.isBlank(scopeString)) {
List<String> scopes = getAuthorizationCodeScopes(connection, codeId, tenantId);
scopeString = OAuth2Util.buildScopeString(scopes.toArray(new String[0]));
}
AuthzCodeDO codeDo = createAuthzCodeDo(consumerKey, authorizationKey, user, codeState, scopeString, callbackUrl, codeId, pkceCodeChallenge, pkceCodeChallengeMethod, issuedTime, validityPeriod, tokenBindingReference);
result = new AuthorizationCodeValidationResult(codeDo, tokenId);
}
return result;
} catch (SQLException e) {
throw new IdentityOAuth2Exception("Error when validating an authorization code", e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
}
Aggregations