prabathabey 9 years ago
commit 69ba3e83ea

2
.gitignore vendored

@ -7,7 +7,7 @@ target
*.iws *.iws
*.ipr *.ipr
.idea .idea
*.ids
# Mac crap # Mac crap
.DS_Store .DS_Store

@ -36,6 +36,9 @@ public class APIPublisherDataHolder {
} }
public APIPublisherService getApiPublisherService() { public APIPublisherService getApiPublisherService() {
if (apiPublisherService == null) {
throw new IllegalStateException("APIPublisher service is not initialized properly");
}
return apiPublisherService; return apiPublisherService;
} }
@ -48,6 +51,9 @@ public class APIPublisherDataHolder {
} }
public ConfigurationContextService getConfigurationContextService() { public ConfigurationContextService getConfigurationContextService() {
if (configurationContextService == null) {
throw new IllegalStateException("ConfigurationContext service is not initialized properly");
}
return configurationContextService; return configurationContextService;
} }

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.config.permission; package org.wso2.carbon.device.mgt.common.permission.mgt;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
@ -31,6 +31,7 @@ public class Permission {
private String path; // permission string private String path; // permission string
private String url; // url of the resource private String url; // url of the resource
private String method; // http method private String method; // http method
private String scope; //scope of the resource
public String getName() { public String getName() {
return name; return name;
@ -50,6 +51,15 @@ public class Permission {
this.path = path; this.path = path;
} }
public String getScope() {
return scope;
}
@XmlElement(name = "scope", required = false)
public void setScope(String scope) {
this.scope = scope;
}
public String getUrl() { public String getUrl() {
return url; return url;
} }

@ -0,0 +1,60 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.permission.mgt;
/**
* Custom exception class of Permission related operations.
*/
public class PermissionManagementException extends Exception {
private static final long serialVersionUID = -3151279311929070298L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public PermissionManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public PermissionManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public PermissionManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public PermissionManagementException() {
super();
}
public PermissionManagementException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.permission.mgt;
import java.util.Properties;
/**
* This represents the Permission management functionality which should be implemented by
* required PermissionManagers.
*/
public interface PermissionManagerService {
/**
*
* @param permission - Permission to be added
* @return The status of the operation.
* @throws PermissionManagementException If some unusual behaviour is observed while adding the
* permission.
*/
public boolean addPermission(Permission permission) throws PermissionManagementException;
/**
*
* @param properties - Properties of the permission to be fetched.
* @return The matched Permission object.
* @throws PermissionManagementException If some unusual behaviour is observed while fetching the
* permission.
*/
public Permission getPermission(Properties properties) throws PermissionManagementException;
}

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.core.config.permission; package org.wso2.carbon.device.mgt.core.config.permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.util.List; import java.util.List;

@ -1,89 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.config.permission;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.List;
/**
* This class will add, update custom permissions defined in permission.xml in webapps.
*/
public class PermissionManager {
private static PermissionManager permissionManager;
private static PermissionTree permissionTree; // holds the permissions at runtime.
private PermissionManager() {
}
public static PermissionManager getInstance() {
if (permissionManager == null) {
synchronized (PermissionManager.class) {
if (permissionManager == null) {
permissionManager = new PermissionManager();
permissionTree = new PermissionTree();
}
}
}
return permissionManager;
}
public boolean addPermission(Permission permission) throws DeviceManagementException {
permissionTree.addPermission(permission); // adding a permission to the tree
try {
return PermissionUtils.putPermission(permission);
} catch (DeviceManagementException e) {
throw new DeviceManagementException("Error occurred while adding the permission : " +
permission.getName(), e);
}
}
public boolean addPermissions(List<Permission> permissions) throws DeviceManagementException {
for (Permission permission : permissions) {
this.addPermission(permission);
}
return true;
}
public void initializePermissions(InputStream permissionStream) throws DeviceManagementException {
try {
if (permissionStream != null) {
/* Un-marshaling Device Management configuration */
JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
unmarshaller.unmarshal(permissionStream);
if (permissionConfiguration != null && permissionConfiguration.getPermissions() != null) {
this.addPermissions(permissionConfiguration.getPermissions());
}
}
} catch (JAXBException e) {
throw new DeviceManagementException("Error occurred while initializing Data Source config", e);
}
}
public Permission getPermission(String url, String httpMethod) {
return permissionTree.getPermission(url, httpMethod);
}
}

@ -24,12 +24,21 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.config.permission.PermissionManager; import org.wso2.carbon.device.mgt.core.config.permission.PermissionConfiguration;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File; import java.io.File;
import java.io.InputStream;
/**
* This listener class will initiate the permission addition of permissions defined in
* permission.xml of any web-app.
*/
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class WebAppDeploymentLifecycleListener implements LifecycleListener { public class WebAppDeploymentLifecycleListener implements LifecycleListener {
@ -42,12 +51,29 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext(); ServletContext servletContext = context.getServletContext();
try { try {
PermissionManager.getInstance().initializePermissions(servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH)); InputStream permissionStream = servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH);
} catch (DeviceManagementException e) { if (permissionStream != null) {
log.error("Exception occurred while adding the permissions from webapp : " /* Un-marshaling Device Management configuration */
+ servletContext.getContextPath(),e); JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
} Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
} PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
unmarshaller.unmarshal(permissionStream);
if (permissionConfiguration != null &&
permissionConfiguration.getPermissions() != null) {
PermissionManagerServiceImpl.getInstance().addPermissions(
permissionConfiguration.getPermissions());
}
}
} catch (JAXBException e) {
log.error(
"Exception occurred while parsing the permission configuration of webapp : "
+ servletContext.getContextPath(), e);
} catch (PermissionManagementException e) {
log.error("Exception occurred while adding the permissions from webapp : "
+ servletContext.getContextPath(), e);
}
}
} }
} }

@ -51,6 +51,9 @@ public class DeviceManagementDataHolder {
} }
public RealmService getRealmService() { public RealmService getRealmService() {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
return realmService; return realmService;
} }
@ -79,6 +82,9 @@ public class DeviceManagementDataHolder {
} }
public RegistryService getRegistryService() { public RegistryService getRegistryService() {
if (registryService == null) {
throw new IllegalStateException("Registry service is not initialized properly");
}
return registryService; return registryService;
} }
@ -127,6 +133,9 @@ public class DeviceManagementDataHolder {
} }
public ConfigurationContextService getConfigurationContextService() { public ConfigurationContextService getConfigurationContextService() {
if (configurationContextService == null) {
throw new IllegalStateException("ConfigurationContext service is not initialized properly");
}
return configurationContextService; return configurationContextService;
} }

@ -25,10 +25,10 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
@ -45,6 +45,7 @@ import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementSe
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
@ -188,6 +189,11 @@ public class DeviceManagementServiceComponent {
= new NotificationManagementServiceImpl(); = new NotificationManagementServiceImpl();
bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null); bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null);
/* Registering PermissionManager Service */
PermissionManagerService permissionManagerService
= PermissionManagerServiceImpl.getInstance();
bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null);
/* Registering App Management service */ /* Registering App Management service */
try { try {
AppManagementConfigurationManager.getInstance().initConfig(); AppManagementConfigurationManager.getInstance().initConfig();

@ -42,6 +42,9 @@ public class EmailServiceDataHolder {
} }
public ConfigurationContextService getConfigurationContextService() { public ConfigurationContextService getConfigurationContextService() {
if (configurationContextService == null) {
throw new IllegalStateException("ConfigurationContext service is not initialized properly");
}
return configurationContextService; return configurationContextService;
} }

@ -0,0 +1,76 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import java.util.List;
import java.util.Properties;
/**
* This class will add, update custom permissions defined in permission.xml in webapps and it will
* use Registry as the persistence storage.
*/
public class PermissionManagerServiceImpl implements PermissionManagerService {
public static final String URL_PROPERTY = "URL";
public static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD";
private static PermissionManagerServiceImpl registryBasedPermissionManager;
private static PermissionTree permissionTree; // holds the permissions at runtime.
private PermissionManagerServiceImpl() {
}
public static PermissionManagerServiceImpl getInstance() {
if (registryBasedPermissionManager == null) {
synchronized (PermissionManagerServiceImpl.class) {
if (registryBasedPermissionManager == null) {
registryBasedPermissionManager = new PermissionManagerServiceImpl();
permissionTree = new PermissionTree();
}
}
}
return registryBasedPermissionManager;
}
public boolean addPermissions(List<Permission> permissions) throws PermissionManagementException {
for (Permission permission : permissions) {
this.addPermission(permission);
}
return true;
}
@Override
public boolean addPermission(Permission permission) throws PermissionManagementException {
// update the permission path to absolute permission path
permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath()));
// adding a permission to the tree
permissionTree.addPermission(permission);
return PermissionUtils.putPermission(permission);
}
@Override
public Permission getPermission(Properties properties) throws PermissionManagementException {
String url = (String) properties.get(URL_PROPERTY);
String httpMethod = (String) properties.get(HTTP_METHOD_PROPERTY);
return permissionTree.getPermission(url, httpMethod);
}
}

@ -4,9 +4,9 @@
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * you may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
@ -16,7 +16,9 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.config.permission; package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;

@ -4,22 +4,23 @@
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * you may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.config.permission; package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -86,18 +87,19 @@ public class PermissionTree {
*/ */
public Permission getPermission(String url, String httpMethod) { public Permission getPermission(String url, String httpMethod) {
StringTokenizer st = new StringTokenizer(url, ROOT); StringTokenizer st = new StringTokenizer(url, ROOT);
PermissionNode tempRoot = rootNode; PermissionNode tempRoot;
PermissionNode currentRoot = rootNode;
while (st.hasMoreTokens()) { while (st.hasMoreTokens()) {
String currentToken = st.nextToken(); String currentToken = st.nextToken();
// returns the child node which matches with the 'currentToken' path. // returns the child node which matches with the 'currentToken' path.
tempRoot = tempRoot.getChild(currentToken); tempRoot = currentRoot.getChild(currentToken);
// if tempRoot is null, that means 'currentToken' is not matched with the child's path. // if tempRoot is null, that means 'currentToken' is not matched with the child's path.
// It means that it is at a point where the request must have dynamic path variables. // It means that it is at a point where the request must have dynamic path variables.
// Therefor it looks for '*' in the request path. ('*' denotes dynamic path variable). // Therefor it looks for '*' in the request path. ('*' denotes dynamic path variable).
if (tempRoot == null) { if (tempRoot == null) {
tempRoot = tempRoot.getChild(DYNAMIC_PATH_NOTATION); tempRoot = currentRoot.getChild(DYNAMIC_PATH_NOTATION);
// if tempRoot is null, that means there is no any permission which matches with the // if tempRoot is null, that means there is no any permission which matches with the
// given path // given path
if (tempRoot == null) { if (tempRoot == null) {
@ -107,7 +109,8 @@ public class PermissionTree {
return null; return null;
} }
} }
currentRoot = tempRoot;
} }
return tempRoot.getPermission(httpMethod); return currentRoot.getPermission(httpMethod);
} }
} }

@ -16,11 +16,13 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.config.permission; package org.wso2.carbon.device.mgt.core.permission.mgt;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.api.Resource;
@ -29,6 +31,7 @@ import org.wso2.carbon.registry.core.Registry;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File; import java.io.File;
import java.util.StringTokenizer;
/** /**
* Utility class which holds necessary utility methods required for persisting permissions in * Utility class which holds necessary utility methods required for persisting permissions in
@ -39,20 +42,24 @@ public class PermissionUtils {
public static String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; public static String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin";
public static String PERMISSION_PROPERTY_NAME = "name"; public static String PERMISSION_PROPERTY_NAME = "name";
public static Registry getGovernanceRegistry() throws DeviceManagementException { public static Registry getGovernanceRegistry() throws PermissionManagementException {
try { try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
return DeviceManagementDataHolder.getInstance().getRegistryService() return DeviceManagementDataHolder.getInstance().getRegistryService()
.getGovernanceSystemRegistry( .getGovernanceSystemRegistry(
tenantId); tenantId);
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DeviceManagementException( throw new PermissionManagementException(
"Error in retrieving governance registry instance: " + "Error in retrieving governance registry instance: " +
e.getMessage(), e); e.getMessage(), e);
} }
} }
public static Permission getPermission(String path) throws DeviceManagementException { public static String getAbsolutePermissionPath(String permissionPath) {
return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath;
}
public static Permission getPermission(String path) throws PermissionManagementException {
try { try {
Resource resource = PermissionUtils.getGovernanceRegistry().get(path); Resource resource = PermissionUtils.getGovernanceRegistry().get(path);
Permission permission = new Permission(); Permission permission = new Permission();
@ -60,44 +67,58 @@ public class PermissionUtils {
permission.setPath(resource.getPath()); permission.setPath(resource.getPath());
return permission; return permission;
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DeviceManagementException("Error in retrieving registry resource : " + throw new PermissionManagementException("Error in retrieving registry resource : " +
e.getMessage(), e); e.getMessage(), e);
} }
} }
public static boolean putPermission(Permission permission) public static boolean putPermission(Permission permission)
throws DeviceManagementException { throws PermissionManagementException {
boolean status; boolean status;
try { try {
Resource resource = PermissionUtils.getGovernanceRegistry().newCollection(); StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/");
resource.addProperty(PERMISSION_PROPERTY_NAME, permission.getName()); String lastToken = "", currentToken, tempPath;
PermissionUtils.getGovernanceRegistry().beginTransaction(); while(tokenizer.hasMoreTokens()){
PermissionUtils.getGovernanceRegistry().put(ADMIN_PERMISSION_REGISTRY_PATH + currentToken = tokenizer.nextToken();
permission.getPath(), resource); tempPath = lastToken + "/" + currentToken;
PermissionUtils.getGovernanceRegistry().commitTransaction(); if(!checkResourceExists(tempPath)){
createRegistryCollection(tempPath, currentToken.substring(0));
}
lastToken = tempPath;
}
status = true; status = true;
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DeviceManagementException( throw new PermissionManagementException(
"Error occurred while persisting permission : " + "Error occurred while persisting permission : " +
permission.getName(), e); permission.getName(), e);
} }
return status; return status;
} }
public static boolean checkPermissionExistence(Permission permission) public static void createRegistryCollection(String path, String resourceName)
throws DeviceManagementException, throws PermissionManagementException,
RegistryException {
Resource resource = PermissionUtils.getGovernanceRegistry().newCollection();
resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName);
PermissionUtils.getGovernanceRegistry().beginTransaction();
PermissionUtils.getGovernanceRegistry().put(path, resource);
PermissionUtils.getGovernanceRegistry().commitTransaction();
}
public static boolean checkResourceExists(String path)
throws PermissionManagementException,
org.wso2.carbon.registry.core.exceptions.RegistryException { org.wso2.carbon.registry.core.exceptions.RegistryException {
return PermissionUtils.getGovernanceRegistry().resourceExists(permission.getPath()); return PermissionUtils.getGovernanceRegistry().resourceExists(path);
} }
public static Document convertToDocument(File file) throws DeviceManagementException { public static Document convertToDocument(File file) throws PermissionManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
try { try {
DocumentBuilder docBuilder = factory.newDocumentBuilder(); DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file); return docBuilder.parse(file);
} catch (Exception e) { } catch (Exception e) {
throw new DeviceManagementException("Error occurred while parsing file, while converting " + throw new PermissionManagementException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e); "to a org.w3c.dom.Document", e);
} }
} }

@ -114,19 +114,19 @@
<parameter name="useGeneratedWSDLinJAXWS">${jaxwsparam}</parameter> <parameter name="useGeneratedWSDLinJAXWS">${jaxwsparam}</parameter>
<!-- Deployer for the dataservice. --> <!-- Deployer for the dataservice. -->
<!--<deployer extension="dbs" directory="dataservices" class="org.wso2.dataservices.DBDeployer"/>--> <!--<deployer extensions="dbs" directory="dataservices" class="org.wso2.dataservices.DBDeployer"/>-->
<!-- Axis1 deployer for Axis2--> <!-- Axis1 deployer for Axis2-->
<!--<deployer extension="wsdd" class="org.wso2.carbon.axis1services.Axis1Deployer" directory="axis1services"/>--> <!--<deployer extensions="wsdd" class="org.wso2.carbon.axis1services.Axis1Deployer" directory="axis1services"/>-->
<!-- POJO service deployer for Jar --> <!-- POJO service deployer for Jar -->
<!--<deployer extension="jar" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>--> <!--<deployer extensions="jar" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>-->
<!-- POJO service deployer for Class --> <!-- POJO service deployer for Class -->
<!--<deployer extension="class" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>--> <!--<deployer extensions="class" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>-->
<!-- JAXWS service deployer --> <!-- JAXWS service deployer -->
<!--<deployer extension=".jar" class="org.apache.axis2.jaxws.framework.JAXWSDeployer" directory="servicejars"/>--> <!--<deployer extensions=".jar" class="org.apache.axis2.jaxws.framework.JAXWSDeployer" directory="servicejars"/>-->
<!-- ================================================= --> <!-- ================================================= -->
<!-- Message Receivers --> <!-- Message Receivers -->
<!-- ================================================= --> <!-- ================================================= -->

@ -481,7 +481,7 @@
<!-- ===================== Default MIME Type Mappings =================== --> <!-- ===================== Default MIME Type Mappings =================== -->
<!-- When serving static resources, Tomcat will automatically generate --> <!-- When serving static resources, Tomcat will automatically generate -->
<!-- a "Content-Type" header based on the resource's filename extension, --> <!-- a "Content-Type" header based on the resource's filename extensions, -->
<!-- based on these mappings. Additional mappings can be added here (to --> <!-- based on these mappings. Additional mappings can be added here (to -->
<!-- apply to all web applications), or in your own application's web.xml --> <!-- apply to all web applications), or in your own application's web.xml -->
<!-- deployment descriptor. --> <!-- deployment descriptor. -->
@ -1003,7 +1003,7 @@
</mime-mapping> </mime-mapping>
<!-- <!--
<mime-mapping> <mime-mapping>
<extension>shtml</extension> <extensions>shtml</extensions>
<mime-type>text/x-server-parsed-html</mime-type> <mime-type>text/x-server-parsed-html</mime-type>
</mime-mapping> </mime-mapping>
--> -->

@ -1,67 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.dynamic.client.registration;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.dynamic.client.registration.internal.DataHolder;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
public class DynamicClientRegistrationUtil {
public static String getTenantDomain() throws DynamicClientRegistrationException {
CarbonContext ctx = CarbonContext.getThreadLocalCarbonContext();
String tenantDomain = ctx.getTenantDomain();
if (tenantDomain != null && !tenantDomain.isEmpty()) {
return tenantDomain;
}
int tenantId = ctx.getTenantId();
if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
throw new IllegalStateException("Invalid tenant Id found. This might likely have caused by improper " +
"handling of multi-tenancy");
}
TenantManager tenantManager = DataHolder.getInstance().getTenantManager();
try {
return tenantManager.getDomain(tenantId);
} catch (UserStoreException e) {
throw new DynamicClientRegistrationException("Error occurred while retrieving tenant domain from " +
"the tenant id derived out of the underlying carbon context", e);
}
}
public static void validateUsername(String username) {
if (username == null || username.isEmpty()) {
throw new IllegalArgumentException("Username cannot be null or empty");
}
}
public static void validateApplicationName(String applicationName) {
if (applicationName == null || applicationName.isEmpty()) {
throw new IllegalArgumentException("Application name cannot be null or empty");
}
}
public static void validateConsumerKey(String consumerKey) {
if (consumerKey == null || consumerKey.isEmpty()) {
throw new IllegalArgumentException("Consumer Key cannot be null or empty");
}
}
}

@ -1,48 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.dynamic.client.registration.internal;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.core.service.RealmService;
public class DataHolder {
private RealmService realmService;
private static DataHolder thisInstance = new DataHolder();
private DataHolder() {}
public static DataHolder getInstance() {
return thisInstance;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
}
public RealmService getRealmService() {
return realmService;
}
public TenantManager getTenantManager() {
return realmService.getTenantManager();
}
}

@ -20,7 +20,7 @@ package org.wso2.carbon.dynamic.client.web;
import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
public class RegistrationResponse extends Response { public abstract class RegistrationResponse extends Response {
@Override @Override
public Object getEntity() { public Object getEntity() {

@ -47,7 +47,7 @@
<Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version> <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Dynamic Client Registration Bundle</Bundle-Description> <Bundle-Description>Dynamic Client Registration Bundle</Bundle-Description>
<Bundle-Activator>org.wso2.carbon.dynamic.client.registration.internal.DynamicClientRegistrationServiceComponent</Bundle-Activator> <Bundle-Activator>org.wso2.carbon.dynamic.client.registration.internal.DynamicClientRegistrationBundleActivator</Bundle-Activator>
<Private-Package>org.wso2.carbon.dynamic.client.registration.internal</Private-Package> <Private-Package>org.wso2.carbon.dynamic.client.registration.internal</Private-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.dynamic.client.registration.internal, !org.wso2.carbon.dynamic.client.registration.internal,

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.dynamic.client.registration;
public class DynamicClientRegistrationUtil {
public static void validateUsername(String username) {
if (username == null || username.isEmpty()) {
throw new IllegalArgumentException("Username cannot be null or empty");
}
}
public static void validateApplicationName(String applicationName) {
if (applicationName == null || applicationName.isEmpty()) {
throw new IllegalArgumentException("Application name cannot be null or empty");
}
}
public static void validateConsumerKey(String consumerKey) {
if (consumerKey == null || consumerKey.isEmpty()) {
throw new IllegalArgumentException("Consumer Key cannot be null or empty");
}
}
}

@ -146,6 +146,10 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
// Create the Service Provider // Create the Service Provider
ServiceProvider serviceProvider = new ServiceProvider(); ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(applicationName); serviceProvider.setApplicationName(applicationName);
User user = new User();
user.setUserName(userName);
user.setTenantDomain(tenantDomain);
serviceProvider.setOwner(user);
serviceProvider.setDescription("Service Provider for application " + applicationName); serviceProvider.setDescription("Service Provider for application " + applicationName);
@ -156,13 +160,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
"Service"); "Service");
} }
ServiceProvider existingServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); ServiceProvider existingServiceProvider = appMgtService.getServiceProvider(
applicationName, tenantDomain);
if (existingServiceProvider == null) { if (existingServiceProvider == null) {
appMgtService.createApplication(serviceProvider, userName, tenantDomain); appMgtService.createApplication(serviceProvider, userName, tenantDomain);
} }
ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(
applicationName, tenantDomain);
if (createdServiceProvider == null) { if (createdServiceProvider == null) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Couldn't create Service Provider Application " + applicationName); "Couldn't create Service Provider Application " + applicationName);
@ -306,6 +312,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey); oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey);
} catch (IdentityOAuthAdminException e) { } catch (IdentityOAuthAdminException e) {
throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e);
} catch (Exception e) {
throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e);
} }
if (oAuthConsumerApp == null) { if (oAuthConsumerApp == null) {
@ -323,8 +331,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
"Error occurred while retrieving Application Management" + "Error occurred while retrieving Application Management" +
"Service"); "Service");
} }
ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(
applicationName, tenantDomain);
if (createdServiceProvider == null) { if (createdServiceProvider == null) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Couldn't retrieve Service Provider Application " + applicationName); "Couldn't retrieve Service Provider Application " + applicationName);
@ -337,6 +345,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
} catch (IdentityOAuthAdminException e) { } catch (IdentityOAuthAdminException e) {
throw new DynamicClientRegistrationException("Error occurred while removing application '" + throw new DynamicClientRegistrationException("Error occurred while removing application '" +
applicationName + "'", e); applicationName + "'", e);
} catch (Exception e) {
throw new DynamicClientRegistrationException("Error occurred while removing application '" +
applicationName + "'", e);
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser);
@ -354,7 +365,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
} }
try { try {
if (ApplicationManagementService.getInstance().getServiceProvider(applicationName, if (ApplicationManagementService.getInstance().getServiceProvider(applicationName,
CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != null) { CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != null) {
return true; return true;
} }
} catch (IdentityApplicationManagementException e) { } catch (IdentityApplicationManagementException e) {

@ -18,32 +18,31 @@
package org.wso2.carbon.dynamic.client.registration.internal; package org.wso2.carbon.dynamic.client.registration.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl;
/** /**
* @scr.component name="org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationServiceComponent" * BundleActivator class of DynamicClientRegistration component.
* immediate="true"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
*/ */
public class DynamicClientRegistrationServiceComponent { public class DynamicClientRegistrationBundleActivator implements BundleActivator{
protected void activate(ComponentContext componentContext) { private static final Log log = LogFactory.getLog(DynamicClientRegistrationBundleActivator.class);
BundleContext bundleContext = componentContext.getBundleContext();
bundleContext.registerService(DynamicClientRegistrationService.class.getName(),
new DynamicClientRegistrationImpl(), null);
}
protected void deactivate(ComponentContext componentContext) { @Override
//do nothing public void start(BundleContext bundleContext) throws Exception {
} DynamicClientRegistrationService dynamicClientRegistrationService =
new DynamicClientRegistrationImpl();
bundleContext.registerService(DynamicClientRegistrationService.class.getName(),
dynamicClientRegistrationService, null);
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
}
} }

@ -25,8 +25,8 @@ import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationExce
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.registration.OAuthApplicationInfo; import org.wso2.carbon.dynamic.client.registration.OAuthApplicationInfo;
import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile;
import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientRegistrationDataHolder; import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder;
import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientRegistrationConstants; import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationConstants;
import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationUtil; import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationUtil;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -34,24 +34,24 @@ import javax.servlet.ServletContext;
/** /**
* This class contains the logic to handle the OAuth application creation process. * This class contains the logic to handle the OAuth application creation process.
*/ */
public class DynamicRegistrationManager { public class DynamicClientWebAppRegistrationManager {
private static DynamicRegistrationManager dynamicRegistrationManager; private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager;
private static final Log log = private static final Log log =
LogFactory.getLog(DynamicRegistrationManager.class); LogFactory.getLog(DynamicClientWebAppRegistrationManager.class);
private DynamicRegistrationManager() { private DynamicClientWebAppRegistrationManager() {
} }
public static DynamicRegistrationManager getInstance() { public static DynamicClientWebAppRegistrationManager getInstance() {
if (dynamicRegistrationManager == null) { if (dynamicClientWebAppRegistrationManager == null) {
synchronized (DynamicRegistrationManager.class) { synchronized (DynamicClientWebAppRegistrationManager.class) {
if (dynamicRegistrationManager == null) { if (dynamicClientWebAppRegistrationManager == null) {
dynamicRegistrationManager = new DynamicRegistrationManager(); dynamicClientWebAppRegistrationManager = new DynamicClientWebAppRegistrationManager();
} }
} }
} }
return dynamicRegistrationManager; return dynamicClientWebAppRegistrationManager;
} }
public OAuthApp registerOAuthApplication(RegistrationProfile registrationProfile) { public OAuthApp registerOAuthApplication(RegistrationProfile registrationProfile) {
@ -60,7 +60,7 @@ public class DynamicRegistrationManager {
} }
if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) {
DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientRegistrationService dynamicClientRegistrationService =
DynamicClientRegistrationDataHolder.getInstance() DynamicClientWebAppRegistrationDataHolder.getInstance()
.getDynamicClientRegistrationService(); .getDynamicClientRegistrationService();
try { try {
OAuthApplicationInfo oAuthApplicationInfo = OAuthApplicationInfo oAuthApplicationInfo =
@ -110,9 +110,9 @@ public class DynamicRegistrationManager {
public void initiateDynamicClientRegistrationProcess(StandardContext context) { public void initiateDynamicClientRegistrationProcess(StandardContext context) {
ServletContext servletContext = context.getServletContext(); ServletContext servletContext = context.getServletContext();
String requiredDynamicClientRegistration = servletContext.getInitParameter( String requiredDynamicClientRegistration = servletContext.getInitParameter(
DynamicClientRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG);
DynamicRegistrationManager dynamicRegistrationManager = DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager =
DynamicRegistrationManager.getInstance(); DynamicClientWebAppRegistrationManager.getInstance();
//Get the application name from web-context //Get the application name from web-context
String webAppName = context.getBaseName(); String webAppName = context.getBaseName();
RegistrationProfile registrationProfile; RegistrationProfile registrationProfile;
@ -121,30 +121,34 @@ public class DynamicRegistrationManager {
if ((requiredDynamicClientRegistration != null) && if ((requiredDynamicClientRegistration != null) &&
(Boolean.parseBoolean(requiredDynamicClientRegistration))) { (Boolean.parseBoolean(requiredDynamicClientRegistration))) {
//Check whether this is an already registered application //Check whether this is an already registered application
if (!dynamicRegistrationManager.isRegisteredOAuthApplication(webAppName)) { if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
//Construct the RegistrationProfile //Construct the RegistrationProfile
registrationProfile = DynamicClientWebAppRegistrationUtil registrationProfile = DynamicClientWebAppRegistrationUtil.
.constructRegistrationProfile(servletContext, webAppName); constructRegistrationProfile(servletContext, webAppName);
//Register the OAuth application //Register the OAuth application
oAuthApp = dynamicRegistrationManager.registerOAuthApplication( oAuthApp = dynamicClientWebAppRegistrationManager.registerOAuthApplication(
registrationProfile); registrationProfile);
} else {
oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
} }
} else { } else {
//Jaggery apps //Jaggery apps
OAuthSettings oAuthSettings = DynamicClientWebAppRegistrationUtil OAuthSettings oAuthSettings = DynamicClientWebAppRegistrationUtil
.getJaggeryAppOAuthSettings(servletContext); .getJaggeryAppOAuthSettings(servletContext);
if (oAuthSettings.isRequireDynamicClientRegistration()) { if (oAuthSettings.isRequireDynamicClientRegistration()) {
if (!dynamicRegistrationManager.isRegisteredOAuthApplication(webAppName)) { if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
registrationProfile = DynamicClientWebAppRegistrationUtil registrationProfile = DynamicClientWebAppRegistrationUtil
.constructRegistrationProfile(oAuthSettings, webAppName); .constructRegistrationProfile(oAuthSettings, webAppName);
oAuthApp = dynamicRegistrationManager oAuthApp = dynamicClientWebAppRegistrationManager
.registerOAuthApplication(registrationProfile); .registerOAuthApplication(registrationProfile);
} else {
oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
} }
} }
} }
DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthApp, DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthApp,
servletContext); servletContext);
} }
} }

@ -26,20 +26,20 @@ import org.wso2.carbon.utils.ConfigurationContextService;
/** /**
* Dataholder class of DynamicClient Webapp Registration component. * Dataholder class of DynamicClient Webapp Registration component.
*/ */
public class DynamicClientRegistrationDataHolder { public class DynamicClientWebAppRegistrationDataHolder {
private RealmService realmService; private RealmService realmService;
private RegistryService registryService; private RegistryService registryService;
private DynamicClientRegistrationService dynamicClientRegistrationService; private DynamicClientRegistrationService dynamicClientRegistrationService;
private ConfigurationContextService configurationContextService; private ConfigurationContextService configurationContextService;
private static DynamicClientRegistrationDataHolder thisInstance = private static DynamicClientWebAppRegistrationDataHolder thisInstance =
new DynamicClientRegistrationDataHolder(); new DynamicClientWebAppRegistrationDataHolder();
private DynamicClientRegistrationDataHolder() { private DynamicClientWebAppRegistrationDataHolder() {
} }
public static DynamicClientRegistrationDataHolder getInstance() { public static DynamicClientWebAppRegistrationDataHolder getInstance() {
return thisInstance; return thisInstance;
} }

@ -76,7 +76,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Realm Service"); log.debug("Setting Realm Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setRealmService(realmService); DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService);
} }
/** /**
@ -88,7 +88,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Unsetting Realm Service"); log.debug("Unsetting Realm Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setRealmService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null);
} }
/** /**
@ -100,7 +100,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Registry Service"); log.debug("Setting Registry Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setRegistryService(registryService); DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService);
} }
/** /**
@ -112,7 +112,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Un setting Registry Service"); log.debug("Un setting Registry Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setRegistryService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null);
} }
/** /**
@ -124,7 +124,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Dynamic Client Registration Service"); log.debug("Setting Dynamic Client Registration Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(
dynamicClientRegistrationService); dynamicClientRegistrationService);
} }
@ -137,7 +137,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Un setting Dynamic Client Registration Service"); log.debug("Un setting Dynamic Client Registration Service");
} }
DynamicClientRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null);
} }
/** /**
@ -149,7 +149,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting ConfigurationContextService"); log.debug("Setting ConfigurationContextService");
} }
DynamicClientRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService); DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService);
} }
/** /**
@ -161,7 +161,7 @@ public class DynamicClientWebAppRegistrationServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService"); log.debug("Un-setting ConfigurationContextService");
} }
DynamicClientRegistrationDataHolder.getInstance().setConfigurationContextService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null);
} }
} }

@ -24,7 +24,7 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.dynamic.client.web.app.registration.DynamicRegistrationManager; import org.wso2.carbon.dynamic.client.web.app.registration.DynamicClientWebAppRegistrationManager;
/** /**
* This class initiates the dynamic client registration flow for Web applications upon on deployment * This class initiates the dynamic client registration flow for Web applications upon on deployment
@ -40,7 +40,7 @@ public class DynamicClientWebAppDeploymentLifecycleListener implements Lifecycle
public void lifecycleEvent(LifecycleEvent lifecycleEvent) { public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
DynamicRegistrationManager.getInstance().initiateDynamicClientRegistrationProcess( DynamicClientWebAppRegistrationManager.getInstance().initiateDynamicClientRegistrationProcess(
context); context);
} }
} }

@ -21,7 +21,7 @@ package org.wso2.carbon.dynamic.client.web.app.registration.util;
/** /**
* Holds the constants to be used in Dynamic client web app registration component. * Holds the constants to be used in Dynamic client web app registration component.
*/ */
public class DynamicClientRegistrationConstants { public class DynamicClientWebAppRegistrationConstants {
public final static String OAUTH_APP_DATA_REGISTRY_PATH = "/OAuth"; public final static String OAUTH_APP_DATA_REGISTRY_PATH = "/OAuth";
public final static String OAUTH_APP_NAME = "appName"; public final static String OAUTH_APP_NAME = "appName";

@ -26,7 +26,7 @@ import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationExce
import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile;
import org.wso2.carbon.dynamic.client.web.app.registration.OAuthApp; import org.wso2.carbon.dynamic.client.web.app.registration.OAuthApp;
import org.wso2.carbon.dynamic.client.web.app.registration.OAuthSettings; import org.wso2.carbon.dynamic.client.web.app.registration.OAuthSettings;
import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientRegistrationDataHolder; import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder;
import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Registry;
@ -62,7 +62,7 @@ public class DynamicClientWebAppRegistrationUtil {
public static Registry getGovernanceRegistry() throws DynamicClientRegistrationException { public static Registry getGovernanceRegistry() throws DynamicClientRegistrationException {
try { try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
return DynamicClientRegistrationDataHolder.getInstance().getRegistryService() return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService()
.getGovernanceSystemRegistry( .getGovernanceSystemRegistry(
tenantId); tenantId);
} catch (RegistryException e) { } catch (RegistryException e) {
@ -76,7 +76,7 @@ public class DynamicClientWebAppRegistrationUtil {
throws DynamicClientRegistrationException { throws DynamicClientRegistrationException {
Resource resource; Resource resource;
String resourcePath = String resourcePath =
DynamicClientRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName; DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Retrieving OAuth application " + appName + " data from Registry"); log.debug("Retrieving OAuth application " + appName + " data from Registry");
@ -88,7 +88,7 @@ public class DynamicClientWebAppRegistrationUtil {
return (OAuthApp) unmarshaller.unmarshal( return (OAuthApp) unmarshaller.unmarshal(
new StringReader(new String((byte[]) resource.getContent(), Charset new StringReader(new String((byte[]) resource.getContent(), Charset
.forName( .forName(
DynamicClientRegistrationConstants.CharSets.CHARSET_UTF8)))); DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8))));
} }
return new OAuthApp(); return new OAuthApp();
} catch (JAXBException e) { } catch (JAXBException e) {
@ -116,9 +116,9 @@ public class DynamicClientWebAppRegistrationUtil {
Resource resource = Resource resource =
DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource();
resource.setContent(writer.toString()); resource.setContent(writer.toString());
resource.setMediaType(DynamicClientRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML);
String resourcePath = String resourcePath =
DynamicClientRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" +
oAuthApp.getWebAppName(); oAuthApp.getWebAppName();
status = status =
DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource);
@ -172,7 +172,7 @@ public class DynamicClientWebAppRegistrationUtil {
public static String getUserName() { public static String getUserName() {
String username = ""; String username = "";
RealmService realmService = RealmService realmService =
DynamicClientRegistrationDataHolder.getInstance().getRealmService(); DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService();
if (realmService != null) { if (realmService != null) {
username = realmService.getBootstrapRealmConfiguration().getAdminUserName(); username = realmService.getBootstrapRealmConfiguration().getAdminUserName();
} }
@ -252,7 +252,7 @@ public class DynamicClientWebAppRegistrationUtil {
while (reader.hasNext()) { while (reader.hasNext()) {
String key = reader.nextName(); String key = reader.nextName();
switch (key) { switch (key) {
case DynamicClientRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG: case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG:
oAuthSettings.setRequireDynamicClientRegistration(reader.nextBoolean()); oAuthSettings.setRequireDynamicClientRegistration(reader.nextBoolean());
break; break;
case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE: case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE:
@ -289,7 +289,7 @@ public class DynamicClientWebAppRegistrationUtil {
// HTTPS port // HTTPS port
String mgtConsoleTransport = CarbonUtils.getManagementTransport(); String mgtConsoleTransport = CarbonUtils.getManagementTransport();
ConfigurationContextService configContextService = ConfigurationContextService configContextService =
DynamicClientRegistrationDataHolder.getInstance().getConfigurationContextService(); DynamicClientWebAppRegistrationDataHolder.getInstance().getConfigurationContextService();
int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
int httpsProxyPort = int httpsProxyPort =
CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
@ -310,9 +310,9 @@ public class DynamicClientWebAppRegistrationUtil {
//Check for client credentials //Check for client credentials
if ((oAuthApp.getClientKey() != null && !oAuthApp.getClientKey().isEmpty()) && if ((oAuthApp.getClientKey() != null && !oAuthApp.getClientKey().isEmpty()) &&
(oAuthApp.getClientSecret() != null && !oAuthApp.getClientSecret().isEmpty())) { (oAuthApp.getClientSecret() != null && !oAuthApp.getClientSecret().isEmpty())) {
servletContext.setAttribute(DynamicClientRegistrationConstants.OAUTH_CLIENT_KEY, servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_KEY,
oAuthApp.getClientKey()); oAuthApp.getClientKey());
servletContext.setAttribute(DynamicClientRegistrationConstants.OAUTH_CLIENT_SECRET, servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_SECRET,
oAuthApp.getClientSecret()); oAuthApp.getClientSecret());
} else { } else {
log.warn("Client credentials not found for web app : " + oAuthApp.getWebAppName()); log.warn("Client credentials not found for web app : " + oAuthApp.getWebAppName());

@ -21,9 +21,9 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>identity-extensions</artifactId>
<version>0.9.2-SNAPSHOT</version> <version>0.9.2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -31,32 +31,12 @@
<artifactId>dynamic-client-registration</artifactId> <artifactId>dynamic-client-registration</artifactId>
<version>0.9.2-SNAPSHOT</version> <version>0.9.2-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - Dynamic Client Registration Component</name> <name>WSO2 Carbon - Dynamic client registration</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<modules> <modules>
<module>dynamic-client-web</module>
<module>org.wso2.carbon.dynamic.client.registration</module> <module>org.wso2.carbon.dynamic.client.registration</module>
<module>org.wso2.carbon.dynamic.client.web.app.registration</module> <module>org.wso2.carbon.dynamic.client.web.app.registration</module>
<module>dynamic-client-web</module>
</modules> </modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project> </project>

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>identity-extensions</artifactId>
<version>0.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.oauth.extensions</artifactId>
<version>0.9.2-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - OAuth Extensions</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>OAuth Extensions Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.oauth.extensions.internal</Private-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.oauth.extensions.internal,
org.wso2.carbon.device.mgt.oauth.extensions.handlers.*,
org.wso2.carbon.device.mgt.oauth.extensions.validators.*
</Export-Package>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,64 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.oauth.extensions.handlers;
import org.wso2.carbon.identity.oauth.callback.AbstractOAuthCallbackHandler;
import org.wso2.carbon.identity.oauth.callback.OAuthCallback;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
/**
* This class represents a Custom OAuthCallback Handler implementation. This should be implemented
* if there's any necessity of custom logic to authorize OAuthCallbacks.
*/
public class DeviceMgtOAuthCallbackHandler extends AbstractOAuthCallbackHandler {
@Override
public boolean canHandle(Callback[] callbacks) throws IdentityOAuth2Exception {
return true;
}
@Override
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
if (callbacks != null && callbacks.length > 0){
OAuthCallback oauthCallback = (OAuthCallback) callbacks[0];
if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_AUTHZ.equals(
oauthCallback.getCallbackType())){
oauthCallback.setAuthorized(true);
} else if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN.equals(
oauthCallback.getCallbackType())){
oauthCallback.setAuthorized(true);
} else if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_AUTHZ.equals(
oauthCallback.getCallbackType())){
oauthCallback.setValidScope(true);
} else if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN.equals(
oauthCallback.getCallbackType())){
String[] scopes = oauthCallback.getRequestedScope();
oauthCallback.setApprovedScope(scopes);
oauthCallback.setValidScope(true);
//Add the necessary logic if we are doing the scope validation upon token issue
}
}
}
}

@ -0,0 +1,139 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.oauth.extensions.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.user.core.service.RealmService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.oauth.extensions" immediate="true"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="identity.oauth2.validation.service"
* interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOAuth2ValidationService"
* unbind="unsetOAuth2ValidationService"
* @scr.reference name="permission.manager.service"
* interface="org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService"
* cardinality="1..1"
* policy="dynamic"
* bind="setPermissionManagerService"
* unbind="unsetPermissionManagerService"
*/
public class OAuthExtensionServiceComponent {
private static final Log log = LogFactory.getLog(OAuthExtensionServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
if(log.isDebugEnabled()){
log.debug("Starting OAuthExtensionBundle");
}
}
@SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) {
if(log.isDebugEnabled()){
log.debug("Stopping OAuthExtensionBundle");
}
}
/**
* Sets Realm Service.
*
* @param realmService An instance of RealmService
*/
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Setting Realm Service");
}
OAuthExtensionsDataHolder.getInstance().setRealmService(realmService);
}
/**
* Unsets Realm Service.
*
* @param realmService An instance of RealmService
*/
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Realm Service");
}
OAuthExtensionsDataHolder.getInstance().setRealmService(null);
}
/**
* Sets OAuth2TokenValidation Service.
*
* @param tokenValidationService An instance of OAuth2TokenValidationService
*/
protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
if (log.isDebugEnabled()) {
log.debug("Setting OAuth2TokenValidation Service");
}
OAuthExtensionsDataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService);
}
/**
* Unsets OAuth2TokenValidation Service.
*
* @param tokenValidationService An instance of OAuth2TokenValidationService
*/
protected void unsetOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting OAuth2TokenValidation Service");
}
OAuthExtensionsDataHolder.getInstance().setoAuth2TokenValidationService(null);
}
/**
* Sets PermissionManagerService Service.
*
* @param permissionManagerService An instance of PermissionManagerService
*/
protected void setPermissionManagerService(PermissionManagerService permissionManagerService) {
if (log.isDebugEnabled()) {
log.debug("Setting PermissionManager Service");
}
OAuthExtensionsDataHolder.getInstance().setPermissionManagerService(permissionManagerService);
}
/**
* Unsets PermissionManagerService Service.
*
* @param permissionManagerService An instance of PermissionManagerService
*/
protected void unsetPermissionManagerService(PermissionManagerService permissionManagerService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting PermissionManager Service");
}
OAuthExtensionsDataHolder.getInstance().setPermissionManagerService(null);
}
}

@ -0,0 +1,75 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.oauth.extensions.internal;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.user.core.service.RealmService;
/**
* This holds the OSGi service references required for oauth extensions bundle.
*/
public class OAuthExtensionsDataHolder {
private RealmService realmService;
private OAuth2TokenValidationService oAuth2TokenValidationService;
private PermissionManagerService permissionManagerService;
private static OAuthExtensionsDataHolder thisInstance = new OAuthExtensionsDataHolder();
private OAuthExtensionsDataHolder() {}
public static OAuthExtensionsDataHolder getInstance() {
return thisInstance;
}
public RealmService getRealmService() {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
}
public OAuth2TokenValidationService getoAuth2TokenValidationService() {
if (oAuth2TokenValidationService == null) {
throw new IllegalStateException("OAuth2TokenValidation service is not initialized properly");
}
return oAuth2TokenValidationService;
}
public void setoAuth2TokenValidationService(
OAuth2TokenValidationService oAuth2TokenValidationService) {
this.oAuth2TokenValidationService = oAuth2TokenValidationService;
}
public void setPermissionManagerService(PermissionManagerService permissionManagerService) {
this.permissionManagerService = permissionManagerService;
}
public PermissionManagerService getPermissionManagerService() {
if (permissionManagerService == null) {
throw new IllegalStateException("PermissionManager service is not initialized properly");
}
return permissionManagerService;
}
}

@ -0,0 +1,89 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.oauth.extensions.validators;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.model.AccessTokenDO;
import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import java.util.Properties;
/**
* Custom OAuth2Token Scope validation implementation for DeviceManagement. This will validate the
* user permissions before dispatching the HTTP request to the actual endpoint.
*/
public class ScopeValidator extends OAuth2ScopeValidator {
private static final String URL_PROPERTY = "URL";
private static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD";
public static final class PermissionMethod {
private PermissionMethod() {
throw new AssertionError();
}
public static final String READ = "read";
public static final String WRITE = "write";
public static final String DELETE = "delete";
public static final String ACTION = "action";
}
private static final Log log = LogFactory.getLog(ScopeValidator.class);
@Override
public boolean validateScope(AccessTokenDO accessTokenDO, String resource)
throws IdentityOAuth2Exception {
boolean status = false;
//Extract the url & http method
int idx = resource.lastIndexOf(':');
String url = resource.substring(0, idx);
String method = resource.substring(++idx, resource.length());
Properties properties = new Properties();
properties.put(ScopeValidator.URL_PROPERTY, url);
properties.put(ScopeValidator.HTTP_METHOD_PROPERTY, method);
PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance().
getPermissionManagerService();
try {
Permission permission = permissionManagerService.getPermission(properties);
if((permission != null) && (accessTokenDO.getAuthzUser() != null)) {
String username = accessTokenDO.getAuthzUser().getUserName();
UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
if(userRealm != null && userRealm.getAuthorizationManager() != null){
status = userRealm.getAuthorizationManager().isUserAuthorized(username, permission.getPath(),
PermissionMethod.READ);
}
}
} catch (PermissionManagementException e) {
log.error("Error occurred while validating the resource scope for : " + resource +
", Msg = " + e.getMessage(), e);
} catch (UserStoreException e) {
log.error("Error occurred while retrieving user store. " + e.getMessage());
}
return status;
}
}

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>0.9.2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>identity-extensions</artifactId>
<version>0.9.2-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - Dynamic Client Registration Component</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.oauth.extensions</module>
<module>dynamic-client-registration</module>
</modules>
</project>

@ -114,19 +114,19 @@
<parameter name="useGeneratedWSDLinJAXWS">${jaxwsparam}</parameter> <parameter name="useGeneratedWSDLinJAXWS">${jaxwsparam}</parameter>
<!-- Deployer for the dataservice. --> <!-- Deployer for the dataservice. -->
<!--<deployer extension="dbs" directory="dataservices" class="org.wso2.dataservices.DBDeployer"/>--> <!--<deployer extensions="dbs" directory="dataservices" class="org.wso2.dataservices.DBDeployer"/>-->
<!-- Axis1 deployer for Axis2--> <!-- Axis1 deployer for Axis2-->
<!--<deployer extension="wsdd" class="org.wso2.carbon.axis1services.Axis1Deployer" directory="axis1services"/>--> <!--<deployer extensions="wsdd" class="org.wso2.carbon.axis1services.Axis1Deployer" directory="axis1services"/>-->
<!-- POJO service deployer for Jar --> <!-- POJO service deployer for Jar -->
<!--<deployer extension="jar" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>--> <!--<deployer extensions="jar" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>-->
<!-- POJO service deployer for Class --> <!-- POJO service deployer for Class -->
<!--<deployer extension="class" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>--> <!--<deployer extensions="class" class="org.apache.axis2.deployment.POJODeployer" directory="pojoservices"/>-->
<!-- JAXWS service deployer --> <!-- JAXWS service deployer -->
<!--<deployer extension=".jar" class="org.apache.axis2.jaxws.framework.JAXWSDeployer" directory="servicejars"/>--> <!--<deployer extensions=".jar" class="org.apache.axis2.jaxws.framework.JAXWSDeployer" directory="servicejars"/>-->
<!-- ================================================= --> <!-- ================================================= -->
<!-- Message Receivers --> <!-- Message Receivers -->
<!-- ================================================= --> <!-- ================================================= -->

@ -481,7 +481,7 @@
<!-- ===================== Default MIME Type Mappings =================== --> <!-- ===================== Default MIME Type Mappings =================== -->
<!-- When serving static resources, Tomcat will automatically generate --> <!-- When serving static resources, Tomcat will automatically generate -->
<!-- a "Content-Type" header based on the resource's filename extension, --> <!-- a "Content-Type" header based on the resource's filename extensions, -->
<!-- based on these mappings. Additional mappings can be added here (to --> <!-- based on these mappings. Additional mappings can be added here (to -->
<!-- apply to all web applications), or in your own application's web.xml --> <!-- apply to all web applications), or in your own application's web.xml -->
<!-- deployment descriptor. --> <!-- deployment descriptor. -->
@ -1003,7 +1003,7 @@
</mime-mapping> </mime-mapping>
<!-- <!--
<mime-mapping> <mime-mapping>
<extension>shtml</extension> <extensions>shtml</extensions>
<mime-type>text/x-server-parsed-html</mime-type> <mime-type>text/x-server-parsed-html</mime-type>
</mime-mapping> </mime-mapping>
--> -->

@ -82,6 +82,7 @@
org.wso2.carbon.core.util, org.wso2.carbon.core.util,
org.wso2.carbon.identity.base, org.wso2.carbon.identity.base,
org.wso2.carbon.identity.core.util, org.wso2.carbon.identity.core.util,
org.wso2.carbon.identity.oauth2.*,
org.wso2.carbon.tomcat.ext.valves, org.wso2.carbon.tomcat.ext.valves,
org.wso2.carbon.user.api, org.wso2.carbon.user.api,
org.wso2.carbon.user.core.service, org.wso2.carbon.user.core.service,
@ -95,8 +96,9 @@
org.wso2.carbon.apimgt.impl, org.wso2.carbon.apimgt.impl,
org.wso2.carbon.certificate.mgt.core.service, org.wso2.carbon.certificate.mgt.core.service,
org.wso2.carbon.certificate.mgt.core.exception, org.wso2.carbon.certificate.mgt.core.exception,
org.wso2.carbon.device.mgt.core.config.permission, org.wso2.carbon.device.mgt.core.permission.mgt,
org.wso2.carbon.device.mgt.common, org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.common.permission.mgt,
org.wso2.carbon.device.mgt.core.scep org.wso2.carbon.device.mgt.core.scep
</Import-Package> </Import-Package>
<!--<Fragment-Host>tomcat</Fragment-Host>--> <!--<Fragment-Host>tomcat</Fragment-Host>-->
@ -143,6 +145,10 @@
<groupId>org.wso2.carbon.identity</groupId> <groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.core</artifactId> <artifactId>org.wso2.carbon.identity.core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core.services</artifactId> <artifactId>org.wso2.carbon.core.services</artifactId>

@ -29,6 +29,7 @@ import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;

@ -20,6 +20,7 @@ package org.wso2.carbon.webapp.authenticator.framework;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.device.mgt.core.scep.SCEPManager; import org.wso2.carbon.device.mgt.core.scep.SCEPManager;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
public class DataHolder { public class DataHolder {
@ -28,6 +29,8 @@ public class DataHolder {
private RealmService realmService; private RealmService realmService;
private CertificateManagementService certificateManagementService; private CertificateManagementService certificateManagementService;
private SCEPManager scepManager; private SCEPManager scepManager;
private OAuth2TokenValidationService oAuth2TokenValidationService;
private static DataHolder thisInstance = new DataHolder(); private static DataHolder thisInstance = new DataHolder();
private DataHolder() {} private DataHolder() {}
@ -45,6 +48,9 @@ public class DataHolder {
} }
public RealmService getRealmService() { public RealmService getRealmService() {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
return realmService; return realmService;
} }
@ -53,6 +59,9 @@ public class DataHolder {
} }
public CertificateManagementService getCertificateManagementService() { public CertificateManagementService getCertificateManagementService() {
if (certificateManagementService == null) {
throw new IllegalStateException("CertificateManagement service is not initialized properly");
}
return certificateManagementService; return certificateManagementService;
} }
@ -61,10 +70,25 @@ public class DataHolder {
} }
public SCEPManager getScepManager() { public SCEPManager getScepManager() {
if (scepManager == null) {
throw new IllegalStateException("SCEPManager service is not initialized properly");
}
return scepManager; return scepManager;
} }
public void setScepManager(SCEPManager scepManager) { public void setScepManager(SCEPManager scepManager) {
this.scepManager = scepManager; this.scepManager = scepManager;
} }
public OAuth2TokenValidationService getoAuth2TokenValidationService() {
if (oAuth2TokenValidationService == null) {
throw new IllegalStateException("OAuth2TokenValidation service is not initialized properly");
}
return oAuth2TokenValidationService;
}
public void setoAuth2TokenValidationService(
OAuth2TokenValidationService oAuth2TokenValidationService) {
this.oAuth2TokenValidationService = oAuth2TokenValidationService;
}
} }

@ -24,12 +24,17 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.core.authenticate.APITokenValidator;
import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator; import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Constants;
import org.wso2.carbon.webapp.authenticator.framework.DataHolder;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -40,6 +45,8 @@ public class OAuthAuthenticator implements WebappAuthenticator {
private static final String OAUTH_AUTHENTICATOR = "OAuth"; private static final String OAUTH_AUTHENTICATOR = "OAuth";
private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s"; private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s";
private static final Pattern PATTERN = Pattern.compile(REGEX_BEARER_PATTERN); private static final Pattern PATTERN = Pattern.compile(REGEX_BEARER_PATTERN);
private static final String BEARER_TOKEN_TYPE = "bearer";
private static final String RESOURCE_KEY = "resource";
private static APITokenAuthenticator authenticator = new APITokenAuthenticator(); private static APITokenAuthenticator authenticator = new APITokenAuthenticator();
@ -66,6 +73,7 @@ public class OAuthAuthenticator implements WebappAuthenticator {
@Override @Override
public Status authenticate(Request request, Response response) { public Status authenticate(Request request, Response response) {
String requestUri = request.getRequestURI(); String requestUri = request.getRequestURI();
String requestMethod = request.getMethod();
if (requestUri == null || "".equals(requestUri)) { if (requestUri == null || "".equals(requestUri)) {
return Status.CONTINUE; return Status.CONTINUE;
} }
@ -76,29 +84,61 @@ public class OAuthAuthenticator implements WebappAuthenticator {
return Status.CONTINUE; return Status.CONTINUE;
} }
String apiVersion = tokenizer.nextToken(); String apiVersion = tokenizer.nextToken();
String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion,
request.getRequestURI(), request.getMethod()); requestUri,
requestMethod);
try { try {
if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) { if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) {
AuthenticationFrameworkUtil.handleNoMatchAuthScheme(request, response, request.getMethod(), AuthenticationFrameworkUtil
apiVersion, context); .handleNoMatchAuthScheme(request, response, requestMethod,
apiVersion, context);
return Status.CONTINUE; return Status.CONTINUE;
} else { } else {
String bearerToken = this.getBearerToken(request); String bearerToken = this.getBearerToken(request);
boolean isAuthenticated = // Create a OAuth2TokenValidationRequestDTO object for validating access token
AuthenticationFrameworkUtil.doAuthenticate(context, apiVersion, OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
bearerToken, authLevel, domain); //Set the access token info
return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE; OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken =
dto.new OAuth2AccessToken();
oAuth2AccessToken.setTokenType(OAuthAuthenticator.BEARER_TOKEN_TYPE);
oAuth2AccessToken.setIdentifier(bearerToken);
dto.setAccessToken(oAuth2AccessToken);
//Set the resource context param. This will be used in scope validation.
OAuth2TokenValidationRequestDTO.TokenValidationContextParam
resourceContextParam = dto.new TokenValidationContextParam();
resourceContextParam.setKey(OAuthAuthenticator.RESOURCE_KEY);
resourceContextParam.setValue(requestUri + ":" + requestMethod);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam []
tokenValidationContextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
tokenValidationContextParams[0] = resourceContextParam;
dto.setContext(tokenValidationContextParams);
OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO =
DataHolder.getInstance().
getoAuth2TokenValidationService().validate(dto);
if (oAuth2TokenValidationResponseDTO.isValid()) {
String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser();
try {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(
IdentityUtil.getTenantIdOFUser(username));
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantUtils.getTenantDomain(username));
} catch (IdentityException e) {
throw new AuthenticationException(
"Error occurred while retrieving the tenant ID of user '" +
username + "'", e);
}
boolean isAuthenticated = oAuth2TokenValidationResponseDTO.isValid();
return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE;
}
} }
} catch (APIManagementException e) {
log.error("Error occurred while key validation", e);
return Status.FAILURE;
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
log.error("Failed to authenticate the incoming request", e); log.error("Failed to authenticate the incoming request", e);
return Status.FAILURE; return Status.FAILURE;
} }
return Status.FAILURE;
} }
@Override @Override

@ -23,13 +23,14 @@ import org.apache.catalina.connector.Response;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.core.config.permission.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.core.config.permission.PermissionManager; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Constants;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import java.util.StringTokenizer; import java.util.Properties;
/** /**
* This class represents the methods that are used to authorize requests. * This class represents the methods that are used to authorize requests.
@ -48,8 +49,19 @@ public class PermissionAuthorizer {
return WebappAuthenticator.Status.CONTINUE; return WebappAuthenticator.Status.CONTINUE;
} }
PermissionManager permissionManager = PermissionManager.getInstance(); PermissionManagerServiceImpl
Permission requestPermission = permissionManager.getPermission(requestUri, requestMethod); registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance();
Properties properties = new Properties();
properties.put("",requestUri);
properties.put("",requestMethod);
Permission requestPermission = null;
try {
requestPermission = registryBasedPermissionManager.getPermission(properties);
} catch (PermissionManagementException e) {
log.error(
"Error occurred while fetching the permission for URI : " + requestUri + " ," +
" METHOD : " + requestMethod + ", msg = " + e.getMessage());
}
if (requestPermission == null) { if (requestPermission == null) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.device.mgt.core.scep.SCEPManager; import org.wso2.carbon.device.mgt.core.scep.SCEPManager;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
@ -30,7 +31,6 @@ import org.wso2.carbon.webapp.authenticator.framework.DataHolder;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository;
import org.wso2.carbon.webapp.authenticator.framework.authorizer.PermissionAuthorizationValve;
import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig;
import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig; import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig;
@ -57,6 +57,12 @@ import java.util.List;
* cardinality="1..n" * cardinality="1..n"
* bind="setSCEPManagementService" * bind="setSCEPManagementService"
* unbind="unsetSCEPManagementService" * unbind="unsetSCEPManagementService"
* @scr.reference name="identity.oauth2.validation.service"
* interface="org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOAuth2ValidationService"
* unbind="unsetOAuth2ValidationService"
*/ */
public class WebappAuthenticatorFrameworkServiceComponent { public class WebappAuthenticatorFrameworkServiceComponent {
@ -79,7 +85,7 @@ public class WebappAuthenticatorFrameworkServiceComponent {
List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>(); List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>();
valves.add(new WebappAuthenticationHandler()); valves.add(new WebappAuthenticationHandler());
valves.add(new PermissionAuthorizationValve()); //valves.add(new PermissionAuthorizationValve());
TomcatValveContainer.addValves(valves); TomcatValveContainer.addValves(valves);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -135,4 +141,28 @@ public class WebappAuthenticatorFrameworkServiceComponent {
DataHolder.getInstance().setScepManager(null); DataHolder.getInstance().setScepManager(null);
} }
/**
* Sets OAuth2TokenValidation Service.
*
* @param tokenValidationService An instance of OAuth2TokenValidationService
*/
protected void setOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
if (log.isDebugEnabled()) {
log.debug("Setting OAuth2TokenValidationService Service");
}
DataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService);
}
/**
* Unsets OAuth2TokenValidation Service.
*
* @param tokenValidationService An instance of OAuth2TokenValidationService
*/
protected void unsetOAuth2ValidationService(OAuth2TokenValidationService tokenValidationService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting OAuth2TokenValidationService Service");
}
DataHolder.getInstance().setoAuth2TokenValidationService(null);
}
} }

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>oauth-extensions-feature</artifactId>
<version>0.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.oauth.extensions.feature</artifactId>
<packaging>pom</packaging>
<version>0.9.2-SNAPSHOT</version>
<name>WSO2 Carbon - Device Mgt OAuth Extensions Feature</name>
<url>http://wso2.org</url>
<description>This feature contains devicemgt related OAuth extensions</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.oauth.extensions</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.oauth.extensions</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.oauth.extensions:${carbon.device.mgt.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>0.9.2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>oauth-extensions-feature</artifactId>
<version>0.9.2-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon Device Management - OAuth Extensions Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.oauth.extensions.feature</module>
</modules>
</project>

@ -37,17 +37,18 @@
<modules> <modules>
<module>components/device-mgt</module> <module>components/device-mgt</module>
<module>components/apimgt-extensions</module> <module>components/apimgt-extensions</module>
<module>components/policy-mgt</module> <module>components/policy-mgt</module>
<module>components/certificate-mgt</module> <module>components/certificate-mgt</module>
<module>components/webapp-authenticator-framework</module> <module>components/webapp-authenticator-framework</module>
<module>components/dynamic-client-registration</module> <module>components/identity-extensions</module>
<module>features/device-mgt</module> <module>features/device-mgt</module>
<module>features/apimgt-extensions</module> <module>features/apimgt-extensions</module>
<module>features/policy-mgt</module> <module>features/policy-mgt</module>
<module>features/webapp-authenticator-framework</module> <module>features/webapp-authenticator-framework</module>
<module>features/certificate-mgt</module> <module>features/certificate-mgt</module>
<module>features/dynamic-client-registration</module> <module>features/dynamic-client-registration</module>
<module>features/oauth-extensions</module>
</modules> </modules>
<dependencyManagement> <dependencyManagement>
@ -239,6 +240,17 @@
<artifactId>dynamic-client-web</artifactId> <artifactId>dynamic-client-web</artifactId>
<version>${carbon.device.mgt.version}</version> <version>${carbon.device.mgt.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.oauth.extensions</artifactId>
<version>${carbon.device.mgt.version}</version>
<exclusions>
<exclusion>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Device Management dependencies --> <!-- Device Management dependencies -->
<!-- Governance dependencies --> <!-- Governance dependencies -->

Loading…
Cancel
Save