use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.
the class APIManagerComponent method activate.
@Activate
protected void activate(ComponentContext componentContext) throws Exception {
if (log.isDebugEnabled()) {
log.debug("API manager component activated");
}
try {
BundleContext bundleContext = componentContext.getBundleContext();
addRxtConfigs();
addApplicationsPermissionsToRegistry();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String filePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "api-manager.xml";
configuration.load(filePath);
String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
addDefinedSequencesToRegistry();
}
CommonConfigDeployer configDeployer = new CommonConfigDeployer();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), configDeployer, null);
TenantLoadMessageSender tenantLoadMessageSender = new TenantLoadMessageSender();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), tenantLoadMessageSender, null);
KeyMgtConfigDeployer keyMgtConfigDeployer = new KeyMgtConfigDeployer();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), keyMgtConfigDeployer, null);
// Registering Notifiers
bundleContext.registerService(Notifier.class.getName(), new SubscriptionsNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApisNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApplicationNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApplicationRegistrationNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new PolicyNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new DeployAPIInGatewayNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ScopesNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new CertificateNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new GoogleAnalyticsNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ExternalGatewayNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ExternallyDeployedApiNotifier(), null);
APIManagerConfigurationServiceImpl configurationService = new APIManagerConfigurationServiceImpl(configuration);
ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(configurationService);
APIMgtDBUtil.initialize();
APIMConfigService apimConfigService = new APIMConfigServiceImpl();
bundleContext.registerService(APIMConfigService.class.getName(), apimConfigService, null);
APIUtil.loadAndSyncTenantConf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantExternalStoreConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantGAConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantWorkFlowExtensions(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
// load self sigup configuration to the registry
APIUtil.loadTenantSelfSignUpConfigurations(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadCommonOperationPolicies(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIManagerAnalyticsConfiguration analyticsConfiguration = APIManagerAnalyticsConfiguration.getInstance();
analyticsConfiguration.setAPIManagerConfiguration(configuration);
registration = componentContext.getBundleContext().registerService(APIManagerConfigurationService.class.getName(), configurationService, null);
KeyManagerConfigurationServiceImpl keyManagerConfigurationService = new KeyManagerConfigurationServiceImpl();
registration = componentContext.getBundleContext().registerService(KeyManagerConfigurationService.class, keyManagerConfigurationService, null);
JWTValidationService jwtValidationService = new JWTValidationServiceImpl();
registration = componentContext.getBundleContext().registerService(JWTValidationService.class, jwtValidationService, null);
ServiceReferenceHolder.getInstance().setKeyManagerConfigurationService(keyManagerConfigurationService);
APIStatusObserverList.getInstance().init(configuration);
log.debug("Reading Analytics Configuration from file...");
// This method is called in two places. Mostly by the time activate hits,
// ServiceDataPublisherAdmin is not activated. Therefore, this same method is run,
// when ServiceDataPublisherAdmin is set.
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_GOVERNANCE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + "/trunk"), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
// Enabling API Publishers/Creators to make changes on life-cycle history.
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
setupImagePermissions();
GatewayArtifactsMgtDBUtil.initialize();
configureEventPublisherProperties();
configureNotificationEventPublisher();
// Load initially available api contexts at the server startup. This Cache is only use by the products other than the api-manager
/* TODO: Load Config values from apimgt.core*/
boolean apiManagementEnabled = APIUtil.isAPIManagementEnabled();
boolean loadAPIContextsAtStartup = APIUtil.isLoadAPIContextsAtStartup();
if (apiManagementEnabled && loadAPIContextsAtStartup) {
List<String> contextList = ApiMgtDAO.getInstance().getAllAvailableContexts();
Cache contextCache = APIUtil.getAPIContextCache();
for (String context : contextList) {
contextCache.put(context, Boolean.TRUE);
}
}
try {
APIUtil.createDefaultRoles(MultitenantConstants.SUPER_TENANT_ID);
} catch (APIManagementException e) {
log.error("Failed create default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
} catch (Exception e) {
// The generic Exception is handled explicitly so execution does not stop during config deployment
log.error("Exception when creating default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
}
// Adding default throttle policies
addDefaultAdvancedThrottlePolicies();
// Update all NULL THROTTLING_TIER values to Unlimited
boolean isNullThrottlingTierConversionEnabled = APIUtil.updateNullThrottlingTierAtStartup();
try {
if (isNullThrottlingTierConversionEnabled) {
ApiMgtDAO.getInstance().convertNullThrottlingTiers();
}
} catch (APIManagementException e) {
log.error("Failed to convert NULL THROTTLING_TIERS to Unlimited");
}
// // Initialise KeyManager.
// KeyManagerHolder.initializeKeyManager(configuration);
// Initialise sql constants
SQLConstantManagerFactory.initializeSQLConstantManager();
// Initialize PasswordResolver
PasswordResolverFactory.initializePasswordResolver();
APIUtil.init();
// Activating UserPostSelfRegistration handler componeAPITemplateBuilderImplnt
try {
registration = componentContext.getBundleContext().registerService(AbstractEventHandler.class.getName(), new UserPostSelfRegistrationHandler(), null);
} catch (Exception e) {
log.error("Error while activating UserPostSelfRegistration handler component.", e);
}
// Read the trust store
ServerConfiguration config = CarbonUtils.getServerConfiguration();
// Initialize product REST API token caches
CacheProvider.createRESTAPITokenCache();
CacheProvider.createRESTAPIInvalidTokenCache();
CacheProvider.createGatewayJWTTokenCache();
CacheProvider.createTenantConfigCache();
CacheProvider.createRecommendationsCache();
CacheProvider.createParsedSignJWTCache();
CacheProvider.createGatewayBasicAuthResourceCache();
CacheProvider.createGatewayUsernameCache();
CacheProvider.createIntrospectionCache();
// Initialize Recommendation wso2event output publisher
configureRecommendationEventPublisherProperties();
setupAccessTokenGenerator();
retrieveAndSetParentTrustStore();
if (configuration.getGatewayArtifactSynchronizerProperties().isRetrieveFromStorageEnabled()) {
if (APIConstants.GatewayArtifactSynchronizer.DB_RETRIEVER_NAME.equals(configuration.getGatewayArtifactSynchronizerProperties().getRetrieverName())) {
bundleContext.registerService(ArtifactRetriever.class.getName(), new DBRetriever(), null);
}
}
bundleContext.registerService(ScopeValidator.class, new SystemScopesIssuer(), null);
} catch (APIManagementException e) {
log.error("Error while initializing the API manager component", e);
} catch (APIManagerDatabaseException e) {
log.fatal("Error while Creating the database", e);
}
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.
the class SystemScopesIssuer method configureForJWTGrant.
protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
SignedJWT signedJWT = null;
JWTClaimsSet claimsSet = null;
String[] roles = null;
try {
signedJWT = getSignedJWT(tokReqMsgCtx);
} catch (IdentityOAuth2Exception e) {
log.error("Couldn't retrieve signed JWT", e);
}
if (signedJWT != null) {
claimsSet = getClaimSet(signedJWT);
}
String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
try {
identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
if (identityProvider != null) {
if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
if (identityProvider == null) {
log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
}
}
} else {
log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
}
} catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
log.error("Couldn't initiate identity provider instance", e);
}
try {
roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
} catch (ParseException e) {
log.error("Couldn't retrieve roles:", e);
}
List<String> updatedRoles = new ArrayList<>();
if (roles != null) {
for (String role : roles) {
String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
if (updatedRoleClaimValue != null) {
updatedRoles.add(updatedRoleClaimValue);
} else {
updatedRoles.add(role);
}
}
}
AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
if (roleClaim != null) {
userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
}
user.setUserAttributes(userAttributes);
tokReqMsgCtx.setAuthorizedUser(user);
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.
the class SystemScopesIssuer method getUserRoles.
/**
* This method is used to get roles list of the user.
*
* @param authenticatedUser Authenticated user
* @return roles list
*/
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {
String[] userRoles = null;
String tenantDomain;
String username;
if (authenticatedUser.isFederatedUser()) {
tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
} else {
tenantDomain = authenticatedUser.getTenantDomain();
username = authenticatedUser.getUserName();
}
String userStoreDomain = authenticatedUser.getUserStoreDomain();
RealmService realmService = getRealmService();
try {
int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
// If tenant Id is not set in the tokenReqContext, deriving it from username.
if (tenantId == 0 || tenantId == -1) {
tenantId = getTenantIdOfUser(username);
}
UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);
} catch (UserStoreException e) {
// Log and return since we do not want to stop issuing the token in case of scope validation failures.
log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
}
return userRoles;
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.
the class SystemScopesIssuer method getScopes.
/**
* This method is used to retrieve the authorized scopes with respect to a token.
*
* @param tokReqMsgCtx token message context
* @return authorized scopes list
*/
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
List<String> authorizedScopes = null;
List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
if (appScopes != null) {
// If no scopes can be found in the context of the application
if (isAppScopesEmpty(appScopes, clientId)) {
return getAllowedScopes(requestedScopes);
}
String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
String[] userRoles = null;
// If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
// JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
// use user roles from assertion or jwt otherwise use roles from userstore.
String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
authenticatedUser.setUserStoreDomain("FEDERATED");
tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
userRoles = getRolesFromAssertion(assertion);
} else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
configureForJWTGrant(tokReqMsgCtx);
Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
}
} else {
userRoles = getUserRoles(authenticatedUser);
}
authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
}
return authorizedScopes;
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.
the class SystemScopesIssuer method validateScope.
@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
if (accessTokenDO == null) {
return false;
}
String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
// Return true if there is no resource to validate the token against.
if (resource == null) {
return true;
}
// Get the list of scopes associated with the access token
String[] scopes = accessTokenDO.getScope();
// If no scopes are associated with the token
if (scopes == null || scopes.length == 0) {
return true;
}
String resourceScope = null;
int resourceTenantId = -1;
boolean cacheHit = false;
// Check the cache, if caching is enabled.
OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
// Cache hit
if (result != null && result instanceof ResourceScopeCacheEntry) {
resourceScope = ((ResourceScopeCacheEntry) result).getScope();
resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
cacheHit = true;
}
// Cache was not hit. So retrieve from database.
if (!cacheHit) {
Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
if (scopeMap != null) {
resourceScope = scopeMap.getLeft();
resourceTenantId = scopeMap.getRight();
}
cacheKey = new OAuthCacheKey(resource);
ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
cacheEntry.setTenantId(resourceTenantId);
// Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
// which scopes haven't been defined).
OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
}
// Return TRUE if - There does not exist a scope definition for the resource
if (resourceScope == null) {
if (log.isDebugEnabled()) {
log.debug("Resource '" + resource + "' is not protected with a scope");
}
return true;
}
List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
// If the access token does not bear the scope required for accessing the Resource.
if (!scopeList.contains(resourceScope)) {
if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
}
return false;
}
// This system property is set at server start using -D option, Thus will be a permanent property.
if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
return true;
}
AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
String clientId = accessTokenDO.getConsumerKey();
List<String> requestedScopes = Arrays.asList(scopes);
List<String> authorizedScopes = null;
String[] userRoles = null;
Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
if (appScopes != null) {
// If no scopes can be found in the context of the application
if (isAppScopesEmpty(appScopes, clientId)) {
authorizedScopes = getAllowedScopes(requestedScopes);
oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
return true;
}
userRoles = getUserRoles(authenticatedUser);
authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
}
if (ArrayUtils.isEmpty(userRoles)) {
if (log.isDebugEnabled()) {
log.debug("No roles associated for the user " + authenticatedUser.getUserName());
}
return false;
}
return true;
}
Aggregations