revert-70aa11f8
prabathabey 9 years ago
commit a0ebec9f3d

@ -67,7 +67,8 @@ public class APIPublisherUtil {
api.setEndpointSecured(true); api.setEndpointSecured(true);
api.setStatus(APIStatus.PUBLISHED); api.setStatus(APIStatus.PUBLISHED);
api.setTransports(config.getTransports()); api.setTransports(config.getTransports());
api.setAsDefaultVersion(true);
api.setAsPublishedDefaultVersion(true);
return api; return api;
} }

@ -39,8 +39,8 @@ import java.util.StringTokenizer;
*/ */
public class PermissionUtils { public class PermissionUtils {
public static String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin";
public static String PERMISSION_PROPERTY_NAME = "name"; public static final String PERMISSION_PROPERTY_NAME = "name";
public static Registry getGovernanceRegistry() throws PermissionManagementException { public static Registry getGovernanceRegistry() throws PermissionManagementException {
try { try {
@ -78,11 +78,11 @@ public class PermissionUtils {
try { try {
StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/"); StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/");
String lastToken = "", currentToken, tempPath; String lastToken = "", currentToken, tempPath;
while(tokenizer.hasMoreTokens()){ while(tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken(); currentToken = tokenizer.nextToken();
tempPath = lastToken + "/" + currentToken; tempPath = lastToken + "/" + currentToken;
if(!checkResourceExists(tempPath)){ if(!checkResourceExists(tempPath)) {
createRegistryCollection(tempPath, currentToken.substring(0)); createRegistryCollection(tempPath, currentToken);
} }
lastToken = tempPath; lastToken = tempPath;
} }

@ -0,0 +1,123 @@
<?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>
<artifactId>identity-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>0.9.2-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>bundle</packaging>
<name>WSO2 Carbon - OAuth Back End Authenticator </name>
<artifactId>org.wso2.carbon.identity.authenticator.backend.oauth</artifactId>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.base</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</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>${pom.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${pom.artifactId}</Bundle-Name>
<Private-Package>
org.wso2.sample.authenticator.internal
</Private-Package>
<Export-Package>
!org.wso2.sample.authenticator.internal,
org.wso2.sample.authenticator.*,
</Export-Package>
<Import-Package>
javax.servlet.http,
org.apache.commons.logging,
org.wso2.carbon.identity.application.authentication.framework.*,
org.wso2.carbon.identity.oauth2,
org.wso2.carbon.identity.oauth2.dto,
org.wso2.carbon.user.core.service,
org.wso2.carbon.utils.multitenancy,
org.apache.axis2.client,
org.apache.axis2.context,
org.apache.axis2.transport.http,
org.apache.commons.httpclient,
org.osgi.framework,
org.osgi.service.component,
org.wso2.carbon.core.security,
org.wso2.carbon.core.services.authentication,
org.wso2.carbon.identity.oauth2.stub,
org.wso2.carbon.identity.oauth2.stub.dto,
org.wso2.carbon.base,
org.wso2.carbon.utils
</Import-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,41 @@
/*
* 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.identity.authenticator.backend.oauth;
/**
* Custom exception for backend OAuth authentication
*/
@SuppressWarnings("unused")
public class AuthenticatorException extends Exception {
private static final long serialVersionUID = 1L;
public AuthenticatorException(String message) {
super(message);
}
public AuthenticatorException(Throwable e) {
super(e);
}
public AuthenticatorException(String message, Throwable e) {
super(message, e);
}
}

@ -0,0 +1,161 @@
/*
* 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.identity.authenticator.backend.oauth;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.security.AuthenticatorsConfiguration;
import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidatorFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.rmi.RemoteException;
/**
* This is a custom back end authenticator for enable OAuth token authentication for admin services
*/
public class OauthAuthenticator implements CarbonServerAuthenticator {
private static final Log log = LogFactory.getLog(OauthAuthenticator.class);
private static final int PRIORITY = 5;
private static final int ACCESS_TOKEN_INDEX = 1;
private OAuth2TokenValidator tokenValidator;
public OauthAuthenticator() {
AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.
getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME);
boolean isRemote;
String hostUrl;
if (authenticatorConfig != null) {
isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get("isRemote"));
hostUrl = authenticatorConfig.getParameters().get("hostURL");
}else{
throw new IllegalArgumentException("Configuration parameters need to be defined in Authenticators.xml");
}
try {
tokenValidator = OAuthValidatorFactory.getValidator(isRemote, hostUrl);
} catch (IllegalArgumentException e) {
log.error("Failed to initialise Authenticator",e);
}
}
/**
* Checks whether the authentication of the context can be handled using this authenticator.
*
* @param messageContext containing the request need to be authenticated.
* @return boolean indicating whether the request can be authenticated by this Authenticator.
*/
public boolean isHandle(MessageContext messageContext) {
HttpServletRequest httpServletRequest = getHttpRequest(messageContext);
String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
if (headerValue != null && !headerValue.trim().isEmpty()) {
String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR);
if (OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER.equals(headerPart[0])) {
return true;
}
} else if (httpServletRequest.getParameter(OauthAuthenticatorConstants.BEARER_TOKEN_IDENTIFIER) != null) {
return true;
}
return false;
}
/**
* Authenticates the user using the provided OAuth token and returns the status as a boolean.
* Sets the tenant domain and tenant friendly username to the session as attributes.
*
* @param messageContext containing the request need to be authenticated.
* @return boolean indicating the authentication status.
*/
public boolean isAuthenticated(MessageContext messageContext) {
HttpServletRequest httpServletRequest = getHttpRequest(messageContext);
String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR);
String accessToken = headerPart[ACCESS_TOKEN_INDEX];
OAuthValidationResponse response = null;
try {
response = tokenValidator.validateToken(accessToken);
} catch (RemoteException e) {
log.error("Failed to validate the OAuth token provided.", e);
}
if (response != null && response.isValid()) {
HttpSession session;
if ((session = httpServletRequest.getSession(false)) != null) {
session.setAttribute(MultitenantConstants.TENANT_DOMAIN, response.getTenantDomain());
session.setAttribute(ServerConstants.USER_LOGGED_IN, response.getUserName());
if (log.isDebugEnabled()) {
log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN));
}
}
return true;
}
if (log.isDebugEnabled()) {
log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId());
}
return false;
}
/**
* this method is currently not implemented.
*
* @param messageContext containing the request need to be authenticated.
* @return boolean
*/
public boolean authenticateWithRememberMe(MessageContext messageContext) {
throw new UnsupportedOperationException();
}
/**
* @return string Authenticator name.
*/
public String getAuthenticatorName() {
return OauthAuthenticatorConstants.AUTHENTICATOR_NAME;
}
/**
* @return int priority of the authenticator.
*/
public int getPriority() {
return PRIORITY;
}
/**
* @return boolean true for enable or otherwise for disable status.
*/
public boolean isDisabled() {
return false;
}
/**
* Retrieve HTTP Servlet Request form thr Message Context.
*
* @param messageContext Containing the Servlet Request for backend authentication.
* @return HTTPServletRequest.
*/
private HttpServletRequest getHttpRequest(MessageContext messageContext) {
return (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
}
}

@ -0,0 +1,28 @@
/*
* 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.identity.authenticator.backend.oauth;
public class OauthAuthenticatorConstants {
public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer";
public static final String BEARER_TOKEN_TYPE = "bearer";
public static final String BEARER_TOKEN_IDENTIFIER = "token";
public static final String AUTHENTICATOR_NAME = "BackEndOAuthAuthenticator";
public static final String SPLITING_CHARACTOR = " ";
public static String OAUTH_ENDPOINT_POSTFIX =
"/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/";
}

@ -0,0 +1,56 @@
/*
* 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.identity.authenticator.backend.oauth.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator;
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator;
/**
* @scr.component component.name="org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator" immediate="true"
*/
@SuppressWarnings("unused")
public class OauthAuthenticatorServiceComponent {
private static final Log log = LogFactory.getLog(OauthAuthenticatorServiceComponent
.class);
protected void activate(ComponentContext ctxt) {
try {
OauthAuthenticator oauthAuthenticator = new OauthAuthenticator();
ctxt.getBundleContext().registerService(CarbonServerAuthenticator.class.getName(),
oauthAuthenticator, null);
if (log.isDebugEnabled()) {
log.debug("OAuth Authenticator bundle is activated");
}
} catch (Throwable e) {
log.fatal(" Error while activating OAuth authenticator ", e);
}
}
protected void deactivate(ComponentContext ctxt) {
if (log.isDebugEnabled()) {
log.debug("OAuth Authenticator bundle is deactivated");
}
}
}

@ -0,0 +1,34 @@
/*
* 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.identity.authenticator.backend.oauth.validator;
import java.rmi.RemoteException;
/**
* Interface for the OAuth@TokenValidators
*/
public interface OAuth2TokenValidator {
/**
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
* containing the validity and user details if valid.
*
* @param accessToken which need to be validated.
* @return OAuthValidationResponse with the validated results.
*/
OAuthValidationResponse validateToken(String accessToken) throws RemoteException;
}

@ -0,0 +1,58 @@
/*
* 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.identity.authenticator.backend.oauth.validator;
/**
* This class hold the validation information which can be retrieve by both remote and in house IDPs
*/
@SuppressWarnings("unused")
public class OAuthValidationResponse {
private String userName;
private String tenantDomain;
private boolean isValid;
public OAuthValidationResponse(String userName, String tenantDomain, boolean isValid) {
this.userName = userName;
this.tenantDomain = tenantDomain;
this.isValid = isValid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public boolean isValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
}

@ -0,0 +1,46 @@
/*
* 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.identity.authenticator.backend.oauth.validator;
import org.wso2.carbon.identity.authenticator.backend.oauth.AuthenticatorException;
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.ExternalOAuthValidator;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.LocalOAuthValidator;
/**
* The class validate the configurations and provide the most suitable implementation according to the configuration.
* Factory class for OAuthValidator.
*/
public class OAuthValidatorFactory {
/**
* The method check the configuration and provide the appropriate implementation for OAuth2TokenValidator
* @return OAuth2TokenValidator
*/
public static OAuth2TokenValidator getValidator(boolean isRemote, String hostURL) throws IllegalArgumentException {
if (isRemote) {
if (!(hostURL == null || hostURL.trim().isEmpty())) {
hostURL = hostURL + OauthAuthenticatorConstants.OAUTH_ENDPOINT_POSTFIX;
return new ExternalOAuthValidator(hostURL);
} else {
throw new IllegalArgumentException("Remote server name and ip both can't be empty");
}
}
return new LocalOAuthValidator();
}
}

@ -0,0 +1,85 @@
/*
* 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.identity.authenticator.backend.oauth.validator.impl;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.Header;
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
/**
* Handles the Authentication form external IDP servers.
* Currently only supports WSO@ IS
*/
public class ExternalOAuthValidator implements OAuth2TokenValidator{
protected String hostURL ;
public ExternalOAuthValidator(String hostURL) {
this.hostURL = hostURL;
}
/**
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
* containing the validity and user details if valid.
*
* @param token which need to be validated.
* @return OAuthValidationResponse with the validated results.
*/
public OAuthValidationResponse validateToken(String token) throws RemoteException {
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken =
new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
accessToken.setIdentifier(token);
validationRequest.setAccessToken(accessToken);
OAuth2TokenValidationServiceStub tokenValidationService =
new OAuth2TokenValidationServiceStub(hostURL);
ServiceClient client = tokenValidationService._getServiceClient();
Options options = client.getOptions();
List<Header> headerList = new ArrayList<>();
Header header = new Header();
header.setName(HTTPConstants.HEADER_AUTHORIZATION);
header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER+ " " + token);
headerList.add(header);
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
client.setOptions(options);
OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService.
findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
boolean isValid = tokenValidationResponse.getValid();
String userName = null;
String tenantDomain = null;
if(isValid){
userName = MultitenantUtils.getTenantAwareUsername(
tokenValidationResponse.getAuthorizedUser());
tenantDomain = MultitenantUtils.
getTenantDomain(tokenValidationResponse.getAuthorizedUser());
}
return new OAuthValidationResponse(userName,tenantDomain,isValid);
}
}

@ -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.identity.authenticator.backend.oauth.validator.impl;
import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator;
import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
/**
* Handles the authentication using the inbuilt IS features.
*/
public class LocalOAuthValidator implements OAuth2TokenValidator {
/**
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
* containing the validity and user details if valid.
*
* @param token which need to be validated.
* @return OAuthValidationResponse with the validated results.
*/
public OAuthValidationResponse validateToken(String token) {
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
validationRequest.new OAuth2AccessToken();
accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
accessToken.setIdentifier(token);
validationRequest.setAccessToken(accessToken);
OAuth2TokenValidationService validationService = new OAuth2TokenValidationService();
OAuth2TokenValidationResponseDTO tokenValidationResponse = validationService.
findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
boolean isValid = tokenValidationResponse.isValid();
String userName = null;
String tenantDomain = null;
if(isValid){
userName = MultitenantUtils.getTenantAwareUsername(
tokenValidationResponse.getAuthorizedUser());
tenantDomain =
MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
}
return new OAuthValidationResponse(userName,tenantDomain,isValid);
}
}

@ -22,15 +22,12 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
/** /**
* Created by harshan on 9/8/15. * Holds the utility methods used by Dynamic-Client web bundle.
*/ */
public class DynamicClientUtil { public class DynamicClientUtil {
public static DynamicClientRegistrationService getDynamicClientRegistrationService() { public static DynamicClientRegistrationService getDynamicClientRegistrationService() {
DynamicClientRegistrationService dynamicClientRegistrationService; PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); return (DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null);
dynamicClientRegistrationService = }
(DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null);
return dynamicClientRegistrationService;
}
} }

@ -46,30 +46,30 @@ public class RegistrationServiceImpl implements RegistrationService {
@POST @POST
@Override @Override
public Response register(RegistrationProfile profile) { public Response register(RegistrationProfile profile) {
Response response;
try { try {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext(). PrivilegedCarbonContext.getThreadLocalCarbonContext().
setTenantId(MultitenantConstants.SUPER_TENANT_ID); setTenantId(MultitenantConstants.SUPER_TENANT_ID);
DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil. DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil.
getDynamicClientRegistrationService(); getDynamicClientRegistrationService();
if(dynamicClientRegistrationService != null){ if (dynamicClientRegistrationService != null) {
OAuthApplicationInfo info = dynamicClientRegistrationService. OAuthApplicationInfo info = dynamicClientRegistrationService.registerOAuthApplication(profile);
registerOAuthApplication(profile);
return Response.status(Response.Status.CREATED).entity(info.toString()).build(); return Response.status(Response.Status.CREATED).entity(info.toString()).build();
} }
return Response.status(Response.Status.INTERNAL_SERVER_ERROR). response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("Dynamic Client Registration Service not available.").build(); entity("Dynamic Client Registration Service not available.").build();
} catch (DynamicClientRegistrationException e) { } catch (DynamicClientRegistrationException e) {
String msg = "Error occurred while registering client '" + profile.getClientName() + "'"; String msg = "Error occurred while registering client '" + profile.getClientName() + "'";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity( response = Response.status(Response.Status.BAD_REQUEST).entity(
new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build();
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
return response;
} }
@DELETE @DELETE
@ -77,26 +77,32 @@ public class RegistrationServiceImpl implements RegistrationService {
public Response unregister(@QueryParam("applicationName") String applicationName, public Response unregister(@QueryParam("applicationName") String applicationName,
@QueryParam("userId") String userId, @QueryParam("userId") String userId,
@QueryParam("consumerKey") String consumerKey) { @QueryParam("consumerKey") String consumerKey) {
Response response;
try { try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil. DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil.
getDynamicClientRegistrationService(); getDynamicClientRegistrationService();
if(dynamicClientRegistrationService != null){ if (dynamicClientRegistrationService != null) {
boolean status = dynamicClientRegistrationService.unregisterOAuthApplication(userId, boolean status = dynamicClientRegistrationService.unregisterOAuthApplication(userId, applicationName,
applicationName, consumerKey);
consumerKey); if (status) {
if(status){
return Response.status(Response.Status.ACCEPTED).build(); return Response.status(Response.Status.ACCEPTED).build();
} }
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
return Response.status(Response.Status.INTERNAL_SERVER_ERROR). response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("Dynamic Client Registration Service not available.").build(); entity("Dynamic Client Registration Service not available.").build();
} catch (DynamicClientRegistrationException e) { } catch (DynamicClientRegistrationException e) {
String msg = "Error occurred while un-registering client '" + applicationName + "'"; String msg = "Error occurred while un-registering client '" + applicationName + "'";
log.error(msg, e); log.error(msg, e);
return Response.serverError(). response = Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build();
entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); } finally {
PrivilegedCarbonContext.endTenantFlow();
} }
return response;
} }
} }

@ -36,6 +36,10 @@
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
@ -47,13 +51,30 @@
<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.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,
org.wso2.carbon.dynamic.client.registration.* org.wso2.carbon.dynamic.client.registration.*
</Export-Package> </Export-Package>
<DynamicImport-Package>*</DynamicImport-Package> <Import-Package>
org.apache.commons.logging,
org.json,
org.json.simple,
org.osgi.framework,
org.osgi.service.component,
org.wso2.carbon.context,
org.wso2.carbon.identity.application.common,
org.wso2.carbon.identity.application.common.model,
org.wso2.carbon.identity.application.mgt,
org.wso2.carbon.identity.base,
org.wso2.carbon.identity.oauth,
org.wso2.carbon.identity.oauth.dto,
org.wso2.carbon.identity.sso.saml.admin,
org.wso2.carbon.identity.sso.saml.dto,
org.wso2.carbon.registry.api,
org.wso2.carbon.registry.core,
org.wso2.carbon.utils.multitenancy
</Import-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

@ -26,6 +26,7 @@ public final class ApplicationConstants {
private ClientMetadata() { private ClientMetadata() {
throw new AssertionError(); throw new AssertionError();
} }
//todo refactor names
public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key
public static final String OAUTH_CLIENT_SECRET = "client_secret"; public static final String OAUTH_CLIENT_SECRET = "client_secret";
public static final String OAUTH_REDIRECT_URIS = "redirect_uris"; public static final String OAUTH_REDIRECT_URIS = "redirect_uris";
@ -36,7 +37,7 @@ public final class ApplicationConstants {
public static final String APP_CALLBACK_URL = "callback_url"; public static final String APP_CALLBACK_URL = "callback_url";
public static final String APP_HOME_PAGE = "homepage"; public static final String APP_HOME_PAGE = "homepage";
public static final String OAUTH_CLIENT_CONTACT = "contact"; public static final String OAUTH_CLIENT_CONTACT = "contact";
public static final String APP_LOGOURI = "logouri"; public static final String APP_LOGO_URI = "logo_uri";
public static final String OAUTH_CLIENT_SCOPE = "scope"; public static final String OAUTH_CLIENT_SCOPE = "scope";
public static final String OAUTH_CLIENT_GRANT = "grant_types"; public static final String OAUTH_CLIENT_GRANT = "grant_types";
public static final String OAUTH_CLIENT_RESPONSETYPE = "response_types"; public static final String OAUTH_CLIENT_RESPONSETYPE = "response_types";

@ -19,7 +19,7 @@
package org.wso2.carbon.dynamic.client.registration; package org.wso2.carbon.dynamic.client.registration;
/** /**
* Custom exception to be thrown inside DynamicClientRegistration related functionalities. * Custom exception to be thrown inside DynamicClientRegistration related functionality.
*/ */
public class DynamicClientRegistrationException extends Exception { public class DynamicClientRegistrationException extends Exception {

@ -21,7 +21,8 @@ package org.wso2.carbon.dynamic.client.registration;
import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile;
/** /**
* This class represents the interface to be implemented by DynamicClientRegistrationService. * This class represents the interface to be implemented by DynamicClientRegistrationService which
* is used to support the Dynamic-client-authentication protocol.
*/ */
public interface DynamicClientRegistrationService { public interface DynamicClientRegistrationService {
@ -34,7 +35,7 @@ public interface DynamicClientRegistrationService {
* @throws DynamicClientRegistrationException * @throws DynamicClientRegistrationException
* *
*/ */
public OAuthApplicationInfo registerOAuthApplication( OAuthApplicationInfo registerOAuthApplication(
RegistrationProfile profile) throws DynamicClientRegistrationException; RegistrationProfile profile) throws DynamicClientRegistrationException;
/** /**
@ -47,7 +48,7 @@ public interface DynamicClientRegistrationService {
* @throws DynamicClientRegistrationException * @throws DynamicClientRegistrationException
* *
*/ */
public boolean unregisterOAuthApplication(String userName, String applicationName, boolean unregisterOAuthApplication(String userName, String applicationName,
String consumerKey) throws DynamicClientRegistrationException; String consumerKey) throws DynamicClientRegistrationException;
/** /**
@ -58,6 +59,6 @@ public interface DynamicClientRegistrationService {
* @throws DynamicClientRegistrationException * @throws DynamicClientRegistrationException
* *
*/ */
public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException; boolean isOAuthApplicationAvailable(String applicationName) throws DynamicClientRegistrationException;
} }

@ -31,7 +31,7 @@ public class OAuthApplicationInfo {
private String clientName; private String clientName;
private String callBackURL; private String callBackURL;
private String clientSecret; private String clientSecret;
private Map<String,Object> parameters = new HashMap<String, Object>(); private Map<String, Object> parameters = new HashMap<String, Object>();
public String getClientId() { public String getClientId() {
return clientId; return clientId;
@ -49,39 +49,39 @@ public class OAuthApplicationInfo {
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
} }
public void setClientName(String clientName){ public void setClientName(String clientName) {
this.clientName = clientName; this.clientName = clientName;
} }
public void setCallBackURL(String callBackURL){ public void setCallBackURL(String callBackURL) {
this.callBackURL = callBackURL; this.callBackURL = callBackURL;
} }
public void addParameter(String name,Object value){ public void addParameter(String name, Object value) {
parameters.put(name,value); parameters.put(name, value);
} }
public Object getParameter(String name){ public Object getParameter(String name) {
return parameters.get(name); return parameters.get(name);
} }
public String getJsonString(){ public String getJsonString() {
return JSONObject.toJSONString(parameters); return JSONObject.toJSONString(parameters);
} }
public String getClientName(){ public String getClientName() {
return clientName; return clientName;
} }
public String getCallBackURL(){ public String getCallBackURL() {
return callBackURL; return callBackURL;
} }
public void putAll(Map<String,Object> parameters){ public void putAll(Map<String, Object> parameters) {
this.parameters.putAll(parameters); this.parameters.putAll(parameters);
} }
public void removeParameter(String key){ public void removeParameter(String key) {
this.parameters.remove(key); this.parameters.remove(key);
} }
@ -91,7 +91,6 @@ public class OAuthApplicationInfo {
obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_NAME, this.getClientName()); obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_NAME, this.getClientName());
obj.put(ApplicationConstants.ClientMetadata.OAUTH_CALLBACK_URIS, this.getCallBackURL()); obj.put(ApplicationConstants.ClientMetadata.OAUTH_CALLBACK_URIS, this.getCallBackURL());
obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_SECRET, this.getClientSecret()); obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_SECRET, this.getClientSecret());
obj.put("parameters", this.getJsonString());
return obj.toString(); return obj.toString();
} }

@ -25,6 +25,7 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType; import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.dynamic.client.registration.*; import org.wso2.carbon.dynamic.client.registration.*;
import org.wso2.carbon.dynamic.client.registration.internal.DynamicClientRegistrationDataHolder;
import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.*; import org.wso2.carbon.identity.application.common.model.*;
@ -43,7 +44,7 @@ import java.util.Arrays;
/** /**
* Implementation of DynamicClientRegistrationService. * Implementation of DynamicClientRegistrationService.
*/ */
public class DynamicClientRegistrationImpl implements DynamicClientRegistrationService { public class DynamicClientRegistrationServiceImpl implements DynamicClientRegistrationService {
private static final String TOKEN_SCOPE = "tokenScope"; private static final String TOKEN_SCOPE = "tokenScope";
private static final String MDM = "mdm"; private static final String MDM = "mdm";
@ -51,15 +52,16 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
private static final String BASIC_AUTHENTICATOR = "BasicAuthenticator"; private static final String BASIC_AUTHENTICATOR = "BasicAuthenticator";
private static final String BASIC = "basic"; private static final String BASIC = "basic";
private static final String LOCAL = "local"; private static final String LOCAL = "local";
private static final String ASSERTION_CONSUMER_URI = "https://localhost:9443/mdm/sso/acs";
private static final String AUDIENCE = "https://null:9443/oauth2/token";
private static final Log log = LogFactory.getLog(DynamicClientRegistrationService.class); private static final Log log = LogFactory.getLog(DynamicClientRegistrationService.class);
private static final String AUTH_TYPE_OAUTH_2 = "oauth2";
private static final String OAUTH_CONSUMER_SECRET = "oauthConsumerSecret";
private static final int STEP_ORDER = 1;
private static final String OAUTH_VERSION = "OAuth-2.0";
@Override @Override
public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) throws
throws DynamicClientRegistrationException { DynamicClientRegistrationException {
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
String applicationName = profile.getClientName(); String applicationName = profile.getClientName();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -74,9 +76,10 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
OAuthApplicationInfo info; OAuthApplicationInfo info;
try { try {
info = this.createOAuthApplication(profile); info = this.createOAuthApplication(profile);
} catch (Exception e) { } catch (DynamicClientRegistrationException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e);
"Can not create OAuth application : " + applicationName, e); } catch (IdentityException e) {
throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e);
} }
if (info == null || info.getJsonString() == null) { if (info == null || info.getJsonString() == null) {
@ -92,18 +95,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
try { try {
JSONObject jsonObject = new JSONObject(info.getJsonString()); JSONObject jsonObject = new JSONObject(info.getJsonString());
if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) {
oAuthApplicationInfo oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS,
.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, jsonObject
jsonObject .get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS));
.get(ApplicationConstants.ClientMetadata.
OAUTH_REDIRECT_URIS));
} }
if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) {
oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, jsonObject
OAUTH_CLIENT_GRANT, jsonObject .get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT));
.get(ApplicationConstants.ClientMetadata.
OAUTH_CLIENT_GRANT));
} }
} catch (JSONException e) { } catch (JSONException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
@ -113,8 +112,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
} }
private OAuthApplicationInfo createOAuthApplication( private OAuthApplicationInfo createOAuthApplication(
RegistrationProfile profile) RegistrationProfile profile) throws DynamicClientRegistrationException, IdentityException {
throws DynamicClientRegistrationException, IdentityException {
//Subscriber's name should be passed as a parameter, since it's under the subscriber //Subscriber's name should be passed as a parameter, since it's under the subscriber
//the OAuth App is created. //the OAuth App is created.
@ -123,6 +121,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
String grantType = profile.getGrantType(); String grantType = profile.getGrantType();
String callbackUrl = profile.getCallbackUrl(); String callbackUrl = profile.getCallbackUrl();
boolean isSaaSApp = profile.isSaasApp(); boolean isSaaSApp = profile.isSaasApp();
String audience = profile.getAudience();
String assertionConsumerURL = profile.getAssertionConsumerURL();
String recepientValidationURL = profile.getRecepientValidationURL();
if (userId == null || userId.isEmpty()) { if (userId == null || userId.isEmpty()) {
return null; return null;
@ -152,26 +153,22 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
serviceProvider.setOwner(user); serviceProvider.setOwner(user);
serviceProvider.setDescription("Service Provider for application " + applicationName); serviceProvider.setDescription("Service Provider for application " + applicationName);
ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance().
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); getApplicationManagementService();
if (appMgtService == null) { if (appMgtService == null) {
throw new IllegalStateException( throw new IllegalStateException("Error occurred while retrieving Application Management" + "Service");
"Error occurred while retrieving Application Management" +
"Service");
} }
ServiceProvider existingServiceProvider = appMgtService.getServiceProvider( ServiceProvider existingServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain);
applicationName, tenantDomain);
if (existingServiceProvider == null) { if (existingServiceProvider == null) {
appMgtService.createApplication(serviceProvider, userName, tenantDomain); appMgtService.createApplication(serviceProvider, tenantDomain, userName);
} }
ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain);
applicationName, tenantDomain);
if (createdServiceProvider == null) { if (createdServiceProvider == null) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException("Couldn't create Service Provider Application " +
"Couldn't create Service Provider Application " + applicationName); applicationName);
} }
//Set SaaS app option //Set SaaS app option
createdServiceProvider.setSaasApp(isSaaSApp); createdServiceProvider.setSaasApp(isSaaSApp);
@ -182,11 +179,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
oAuthConsumerApp.setApplicationName(applicationName); oAuthConsumerApp.setApplicationName(applicationName);
oAuthConsumerApp.setCallbackUrl(callbackUrl); oAuthConsumerApp.setCallbackUrl(callbackUrl);
oAuthConsumerApp.setGrantTypes(grantType); oAuthConsumerApp.setGrantTypes(grantType);
oAuthConsumerApp.setOAuthVersion(OAUTH_VERSION);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Creating OAuth App " + applicationName); log.debug("Creating OAuth App " + applicationName);
} }
if (existingServiceProvider == null) { if ((existingServiceProvider == null) || (existingServiceProvider.getInboundAuthenticationConfig().
getInboundAuthenticationRequestConfigs().length == 0)) {
oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp);
} }
@ -208,22 +207,25 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new
InboundAuthenticationRequestConfig(); InboundAuthenticationRequestConfig();
inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey()); inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey());
inboundAuthenticationRequestConfig.setInboundAuthType("oauth2"); inboundAuthenticationRequestConfig.setInboundAuthType(AUTH_TYPE_OAUTH_2);
if (createdApp.getOauthConsumerSecret() != null && !createdApp. String oauthConsumerSecret = createdApp.getOauthConsumerSecret();
getOauthConsumerSecret() if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
.isEmpty()) {
Property property = new Property(); Property property = new Property();
property.setName("oauthConsumerSecret"); property.setName(OAUTH_CONSUMER_SECRET);
property.setValue(createdApp.getOauthConsumerSecret()); property.setValue(oauthConsumerSecret);
Property[] properties = {property}; Property[] properties = { property };
inboundAuthenticationRequestConfig.setProperties(properties); inboundAuthenticationRequestConfig.setProperties(properties);
} }
SAMLSSOServiceProviderDTO samlssoServiceProviderDTO = new SAMLSSOServiceProviderDTO(); SAMLSSOServiceProviderDTO samlssoServiceProviderDTO = new SAMLSSOServiceProviderDTO();
samlssoServiceProviderDTO.setIssuer(MDM); samlssoServiceProviderDTO.setIssuer(MDM);
samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI); samlssoServiceProviderDTO.setAssertionConsumerUrls(new String[] {assertionConsumerURL});
samlssoServiceProviderDTO.setDoSignResponse(true); samlssoServiceProviderDTO.setDoSignResponse(true);
samlssoServiceProviderDTO.setRequestedAudiences(new String[]{AUDIENCE}); samlssoServiceProviderDTO.setRequestedAudiences(new String[] { audience });
samlssoServiceProviderDTO.setDefaultAssertionConsumerUrl(assertionConsumerURL);
samlssoServiceProviderDTO.setRequestedRecipients(new String[] {recepientValidationURL});
samlssoServiceProviderDTO.setDoSignAssertions(true);
SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry()); SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry());
configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO); configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO);
@ -238,15 +240,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
localAuth.setEnabled(true); localAuth.setEnabled(true);
AuthenticationStep authStep = new AuthenticationStep(); AuthenticationStep authStep = new AuthenticationStep();
authStep.setStepOrder(1); authStep.setStepOrder(STEP_ORDER);
authStep.setSubjectStep(true); authStep.setSubjectStep(true);
authStep.setAttributeStep(true); authStep.setAttributeStep(true);
authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[]{localAuth}); authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[] { localAuth });
LocalAndOutboundAuthenticationConfig localOutboundAuthConfig = new LocalAndOutboundAuthenticationConfig(); LocalAndOutboundAuthenticationConfig localOutboundAuthConfig = new LocalAndOutboundAuthenticationConfig();
localOutboundAuthConfig.setAuthenticationType(LOCAL); localOutboundAuthConfig.setAuthenticationType(LOCAL);
localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[]{authStep}); localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[] { authStep });
inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig; inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
inboundAuthenticationRequestConfigs[1] = samlAuthenticationRequest; inboundAuthenticationRequestConfigs[1] = samlAuthenticationRequest;
@ -261,15 +263,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey());
oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl());
oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); oAuthApplicationInfo.setClientSecret(oauthConsumerSecret);
oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); oAuthApplicationInfo.setClientName(createdApp.getApplicationName());
oAuthApplicationInfo.addParameter( oAuthApplicationInfo.addParameter(
ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl());
createdApp.getCallbackUrl());
oAuthApplicationInfo.addParameter( oAuthApplicationInfo.addParameter(
ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes());
createdApp.getGrantTypes());
return oAuthApplicationInfo; return oAuthApplicationInfo;
} catch (IdentityApplicationManagementException e) { } catch (IdentityApplicationManagementException e) {
@ -285,20 +285,19 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
} }
protected Registry getConfigSystemRegistry() { protected Registry getConfigSystemRegistry() {
return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext(). return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.
getRegistry(RegistryType.SYSTEM_CONFIGURATION); SYSTEM_CONFIGURATION);
} }
@Override @Override
public boolean unregisterOAuthApplication(String userId, String applicationName, public boolean unregisterOAuthApplication(String userId, String applicationName, String consumerKey) throws
String consumerKey) throws DynamicClientRegistrationException { DynamicClientRegistrationException {
DynamicClientRegistrationUtil.validateUsername(userId); DynamicClientRegistrationUtil.validateUsername(userId);
DynamicClientRegistrationUtil.validateApplicationName(applicationName); DynamicClientRegistrationUtil.validateApplicationName(applicationName);
DynamicClientRegistrationUtil.validateConsumerKey(consumerKey); DynamicClientRegistrationUtil.validateConsumerKey(consumerKey);
boolean status = false; boolean status = false;
String tenantDomain = MultitenantUtils.getTenantDomain(userId); String tenantDomain = MultitenantUtils.getTenantDomain(userId);
String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
String userName = MultitenantUtils.getTenantAwareUsername(userId); String userName = MultitenantUtils.getTenantAwareUsername(userId);
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
@ -310,9 +309,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
try { try {
oAuthAdminService = new OAuthAdminService(); oAuthAdminService = new OAuthAdminService();
oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey); oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey);
} catch (IdentityOAuthAdminException e) {
throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e);
} catch (Exception e) { } catch (Exception e) {
//We had to catch Exception here because getOAuthApplicationData can throw exceptions of java.lang.Exception
// class.
throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e);
} }
@ -323,16 +322,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
try { try {
oAuthAdminService.removeOAuthApplicationData(consumerKey); oAuthAdminService.removeOAuthApplicationData(consumerKey);
ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance().
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); getApplicationManagementService();
if (appMgtService == null) { if (appMgtService == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Error occurred while retrieving Application Management" + "Error occurred while retrieving Application Management" +
"Service"); "Service");
} }
ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain);
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);
@ -343,36 +341,31 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while removing ServiceProvider for application '" + applicationName + "'", e); "Error occurred while removing ServiceProvider for application '" + applicationName + "'", e);
} catch (IdentityOAuthAdminException e) { } catch (IdentityOAuthAdminException e) {
throw new DynamicClientRegistrationException("Error occurred while removing application '" +
applicationName + "'", e);
} catch (Exception e) {
throw new DynamicClientRegistrationException("Error occurred while removing application '" + throw new DynamicClientRegistrationException("Error occurred while removing application '" +
applicationName + "'", e); applicationName + "'", e);
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser);
} }
return status; return status;
} }
@Override @Override
public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException { public boolean isOAuthApplicationAvailable(String applicationName) throws DynamicClientRegistrationException {
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance().
getApplicationManagementService();
if (appMgtService == null) { if (appMgtService == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Error occurred while retrieving Application Management" + "Error occurred while retrieving Application Management" +
"Service"); "Service");
} }
try { try {
if (ApplicationManagementService.getInstance().getServiceProvider(applicationName, return appMgtService.getServiceProvider(applicationName,
CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != null) { CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) !=
return true; null;
}
} catch (IdentityApplicationManagementException e) { } catch (IdentityApplicationManagementException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while retrieving information of OAuthApp " + applicationName, e); "Error occurred while retrieving information of OAuthApp " + applicationName, e);
} }
return false;
} }
} }

@ -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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl;
/**
* BundleActivator class of DynamicClientRegistration component.
*/
public class DynamicClientRegistrationBundleActivator implements BundleActivator{
private static final Log log = LogFactory.getLog(DynamicClientRegistrationBundleActivator.class);
@Override
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 {
}
}

@ -0,0 +1,51 @@
/*
* 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.identity.application.mgt.ApplicationManagementService;
/**
* DataHolder class of DynamicClientRegistration bundle. This hold a reference to
* ApplicationManagementService.
*/
public class DynamicClientRegistrationDataHolder {
private ApplicationManagementService applicationManagementService;
private static DynamicClientRegistrationDataHolder thisInstance =
new DynamicClientRegistrationDataHolder();
private DynamicClientRegistrationDataHolder() {
}
public static DynamicClientRegistrationDataHolder getInstance() {
return thisInstance;
}
public ApplicationManagementService getApplicationManagementService() {
if (applicationManagementService == null) {
throw new IllegalStateException("ApplicationManagementService is not initialized properly");
}
return applicationManagementService;
}
public void setApplicationManagementService(ApplicationManagementService applicationManagementService) {
this.applicationManagementService = applicationManagementService;
}
}

@ -0,0 +1,87 @@
/*
* 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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationServiceImpl;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
/**
* @scr.component name="org.wso2.carbon.dynamic.client.registration" immediate="true"
* @scr.reference name="identity.application.management.service"
* interface="org.wso2.carbon.identity.application.mgt.ApplicationManagementService"
* cardinality="1..1"
* policy="dynamic"
* bind="setApplicationManagementService"
* unbind="unsetApplicationManagementService"
*/
public class DynamicClientRegistrationServiceComponent {
private static final Log log = LogFactory.getLog(DynamicClientRegistrationServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
if(log.isDebugEnabled()){
log.debug("Starting DynamicClientRegistrationServiceComponent");
}
DynamicClientRegistrationService dynamicClientRegistrationService =
new DynamicClientRegistrationServiceImpl();
componentContext.getBundleContext().registerService(
DynamicClientRegistrationService.class.getName(), dynamicClientRegistrationService, null);
}
@SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) {
if(log.isDebugEnabled()){
log.debug("Stopping DynamicClientRegistrationServiceComponent");
}
}
/**
* Sets ApplicationManagement Service.
*
* @param applicationManagementService An instance of ApplicationManagementService
*/
protected void setApplicationManagementService(ApplicationManagementService
applicationManagementService) {
if (log.isDebugEnabled()) {
log.debug("Setting ApplicationManagement Service");
}
DynamicClientRegistrationDataHolder.getInstance().
setApplicationManagementService(applicationManagementService);
}
/**
* Unsets ApplicationManagement Service.
*
* @param applicationManagementService An instance of ApplicationManagementService
*/
protected void unsetApplicationManagementService(ApplicationManagementService
applicationManagementService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting ApplicationManagement Service");
}
DynamicClientRegistrationDataHolder.getInstance().setApplicationManagementService(null);
}
}

@ -19,11 +19,11 @@ package org.wso2.carbon.dynamic.client.registration.profile;
/** /**
* *
* DTO class to be used when registering a OAuth application. * DTO class to be used when registering an OAuth application.
* *
* */ * */
public class RegistrationProfile { public class RegistrationProfile {
//todo mark mandatory fields
private String applicationType; private String applicationType;
private String[] redirectUris; private String[] redirectUris;
private String clientName; private String clientName;
@ -41,6 +41,34 @@ public class RegistrationProfile {
private String tokenScope; private String tokenScope;
private String grantType; private String grantType;
private boolean saasApp; private boolean saasApp;
private String audience;
public String getRecepientValidationURL() {
return recepientValidationURL;
}
public void setRecepientValidationURL(String recepientValidationURL) {
this.recepientValidationURL = recepientValidationURL;
}
public String getAssertionConsumerURL() {
return assertionConsumerURL;
}
public void setAssertionConsumerURL(String assertionConsumerURL) {
this.assertionConsumerURL = assertionConsumerURL;
}
private String recepientValidationURL;
private String assertionConsumerURL;
public String getAudience() {
return audience;
}
public void setAudience(String audience) {
this.audience = audience;
}
public boolean isSaasApp() { public boolean isSaasApp() {
return saasApp; return saasApp;

@ -87,6 +87,10 @@
<groupId>org.wso2.carbon.identity</groupId> <groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId> <artifactId>org.wso2.carbon.identity.oauth</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.core</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.tomcat</groupId> <groupId>org.wso2.tomcat</groupId>
<artifactId>tomcat</artifactId> <artifactId>tomcat</artifactId>

@ -19,17 +19,21 @@
package org.wso2.carbon.dynamic.client.web.app.registration; package org.wso2.carbon.dynamic.client.web.app.registration;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
import org.apache.commons.collections.iterators.IteratorEnumeration;
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.registration.DynamicClientRegistrationException; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException;
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.dto.OAuthAppDetails;
import org.wso2.carbon.dynamic.client.web.app.registration.dto.JaggeryOAuthConfigurationSettings;
import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder; import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder;
import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationConstants; 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;
import java.util.*;
/** /**
* This class contains the logic to handle the OAuth application creation process. * This class contains the logic to handle the OAuth application creation process.
@ -37,8 +41,9 @@ import javax.servlet.ServletContext;
public class DynamicClientWebAppRegistrationManager { public class DynamicClientWebAppRegistrationManager {
private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager;
private static final Log log = private static Map<String, ServletContext> webAppContexts = new HashMap<>();
LogFactory.getLog(DynamicClientWebAppRegistrationManager.class);
private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class);
private DynamicClientWebAppRegistrationManager() { private DynamicClientWebAppRegistrationManager() {
} }
@ -47,36 +52,34 @@ public class DynamicClientWebAppRegistrationManager {
if (dynamicClientWebAppRegistrationManager == null) { if (dynamicClientWebAppRegistrationManager == null) {
synchronized (DynamicClientWebAppRegistrationManager.class) { synchronized (DynamicClientWebAppRegistrationManager.class) {
if (dynamicClientWebAppRegistrationManager == null) { if (dynamicClientWebAppRegistrationManager == null) {
dynamicClientWebAppRegistrationManager = new DynamicClientWebAppRegistrationManager(); dynamicClientWebAppRegistrationManager =
new DynamicClientWebAppRegistrationManager();
} }
} }
} }
return dynamicClientWebAppRegistrationManager; return dynamicClientWebAppRegistrationManager;
} }
public OAuthApp registerOAuthApplication(RegistrationProfile registrationProfile) { public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName()); log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName());
} }
if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) {
DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientRegistrationService dynamicClientRegistrationService =
DynamicClientWebAppRegistrationDataHolder.getInstance() DynamicClientWebAppRegistrationDataHolder.getInstance().getDynamicClientRegistrationService();
.getDynamicClientRegistrationService();
try { try {
OAuthApplicationInfo oAuthApplicationInfo = OAuthApplicationInfo oAuthApplicationInfo =
dynamicClientRegistrationService dynamicClientRegistrationService.registerOAuthApplication(registrationProfile);
.registerOAuthApplication(registrationProfile); OAuthAppDetails oAuthAppDetails = new OAuthAppDetails();
OAuthApp oAuthApp = new OAuthApp(); oAuthAppDetails.setWebAppName(registrationProfile.getClientName());
oAuthApp.setWebAppName(registrationProfile.getClientName()); oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName());
oAuthApp.setClientName(oAuthApplicationInfo.getClientName()); oAuthAppDetails.setClientKey(oAuthApplicationInfo.getClientId());
oAuthApp.setClientKey(oAuthApplicationInfo.getClientId()); oAuthAppDetails.setClientSecret(oAuthApplicationInfo.getClientSecret());
oAuthApp.setClientSecret(oAuthApplicationInfo.getClientSecret());
//store it in registry //store it in registry
if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthApp)) { if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) {
return oAuthApp; return oAuthAppDetails;
} else { } else {
dynamicClientRegistrationService dynamicClientRegistrationService.unregisterOAuthApplication(registrationProfile.getOwner(),
.unregisterOAuthApplication(registrationProfile.getOwner(),
oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientName(),
oAuthApplicationInfo.getClientId()); oAuthApplicationInfo.getClientId());
log.warn("Error occurred while persisting the OAuth application data in registry."); log.warn("Error occurred while persisting the OAuth application data in registry.");
@ -86,69 +89,91 @@ public class DynamicClientWebAppRegistrationManager {
registrationProfile.getClientName(), e); registrationProfile.getClientName(), e);
} }
} }
return new OAuthApp(); return null;
} }
public OAuthApp getOAuthApplicationData(String clientName) { public OAuthAppDetails getOAuthApplicationData(String clientName) {
try { try {
return DynamicClientWebAppRegistrationUtil.getOAuthApplicationData(clientName); return DynamicClientWebAppRegistrationUtil.getOAuthApplicationData(clientName);
} catch (DynamicClientRegistrationException e) { } catch (DynamicClientRegistrationException e) {
log.error("Error occurred while fetching the OAuth application data for web app : " + log.error("Error occurred while fetching the OAuth application data for web app : " +
clientName, e); clientName, e);
} }
return new OAuthApp(); return null;
} }
public boolean isRegisteredOAuthApplication(String clientName) { public boolean isRegisteredOAuthApplication(String clientName) {
OAuthApp oAuthApp = this.getOAuthApplicationData(clientName); OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName);
if (oAuthApp.getClientKey() != null && oAuthApp.getClientSecret() != null) { if (oAuthAppDetails != null && (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() !=
null)) {
return true; return true;
} }
return false; return false;
} }
public void initiateDynamicClientRegistrationProcess(StandardContext context) { public void saveServletContextToCache(StandardContext context) {
ServletContext servletContext = context.getServletContext(); DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(),
String requiredDynamicClientRegistration = servletContext.getInitParameter( context.getServletContext());
DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); }
public void initiateDynamicClientRegistration() {
String requiredDynamicClientRegistration, webAppName;
ServletContext servletContext;
RegistrationProfile registrationProfile;
OAuthAppDetails oAuthAppDetails = null;
DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager =
DynamicClientWebAppRegistrationManager.getInstance(); DynamicClientWebAppRegistrationManager.getInstance();
//Get the application name from web-context //todo move enumeration to while loop
String webAppName = context.getBaseName(); Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager.
RegistrationProfile registrationProfile; webAppContexts.keySet().iterator());
OAuthApp oAuthApp = null; if (log.isDebugEnabled()) {
//Java web-app section log.debug("Initiating the DynamicClientRegistration service for web-apps");
if ((requiredDynamicClientRegistration != null) && }
(Boolean.parseBoolean(requiredDynamicClientRegistration))) { while (enumeration.hasMoreElements()) {
//Check whether this is an already registered application oAuthAppDetails = new OAuthAppDetails();
if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { webAppName = (String) enumeration.nextElement();
//Construct the RegistrationProfile servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName);
registrationProfile = DynamicClientWebAppRegistrationUtil. requiredDynamicClientRegistration = servletContext.getInitParameter(
constructRegistrationProfile(servletContext, webAppName); DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG);
//Register the OAuth application //Java web-app section
oAuthApp = dynamicClientWebAppRegistrationManager.registerOAuthApplication( if ((requiredDynamicClientRegistration != null) && (Boolean.
registrationProfile); parseBoolean(
requiredDynamicClientRegistration))) {
} else { //Check whether this is an already registered application
oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
}
} else {
//Jaggery apps
OAuthSettings oAuthSettings = DynamicClientWebAppRegistrationUtil
.getJaggeryAppOAuthSettings(servletContext);
if (oAuthSettings.isRequireDynamicClientRegistration()) {
if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
registrationProfile = DynamicClientWebAppRegistrationUtil //Construct the RegistrationProfile
.constructRegistrationProfile(oAuthSettings, webAppName); registrationProfile = DynamicClientWebAppRegistrationUtil.
oAuthApp = dynamicClientWebAppRegistrationManager constructRegistrationProfile(servletContext, webAppName);
.registerOAuthApplication(registrationProfile); //Register the OAuth application
oAuthAppDetails =
dynamicClientWebAppRegistrationManager.registerOAuthApplication(registrationProfile);
} else { } else {
oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
} }
} else if (requiredDynamicClientRegistration == null) {
//Jaggery apps
JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings =
DynamicClientWebAppRegistrationUtil.getJaggeryAppOAuthSettings(servletContext);
if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) {
if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
registrationProfile = DynamicClientWebAppRegistrationUtil.
constructRegistrationProfile(jaggeryOAuthConfigurationSettings,
webAppName);
oAuthAppDetails = dynamicClientWebAppRegistrationManager.
registerOAuthApplication(registrationProfile);
} else {
oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
}
}
}
//Add client credentials to the web-context
if ((oAuthAppDetails != null && oAuthAppDetails.getClientKey() != null) && !oAuthAppDetails.getClientKey().isEmpty()) {
DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails,
servletContext);
log.info("Added OAuth application credentials to webapp context of webapp : " +
webAppName);
} }
} }
DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthApp,
servletContext);
} }
}
}

@ -0,0 +1,38 @@
/*
* 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.web.app.registration;
import org.wso2.carbon.core.ServerStartupObserver;
/**
* ServerStartupObserver implementation to initiate the DynamicClientRegistration process for web
* apps after the Carbon server is up and ready.
*/
public class WebAppRegistrationServerStartupObserver implements ServerStartupObserver {
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
DynamicClientWebAppRegistrationManager.getInstance().initiateDynamicClientRegistration();
}
}

@ -16,22 +16,52 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.dynamic.client.web.app.registration; package org.wso2.carbon.dynamic.client.web.app.registration.dto;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
/** /**
* Represents OAuthConfiguration data. * Represents OAuthConfiguration data required to create OAuth service provider for Jaggery apps.
*/ */
@XmlRootElement(name = "OAuthSettings") @XmlRootElement(name = "OAuthSettings")
public class OAuthSettings { public class JaggeryOAuthConfigurationSettings {
private String grantType; private String grantType;
private boolean saasApp; private boolean saasApp;
private String callbackURL; private String callbackURL;
private String tokenScope; private String tokenScope;
private boolean requireDynamicClientRegistration; private boolean requireDynamicClientRegistration;
private String audience;
private String assertionConsumerURL;
private String recepientValidationURL;
@XmlElement(name = "assertionConsumerURL", required = true)
public String getAssertionConsumerURL() {
return assertionConsumerURL;
}
public void setAssertionConsumerURL(String assertionConsumerURL) {
this.assertionConsumerURL = assertionConsumerURL;
}
@XmlElement(name = "recepientValidationURL", required = true)
public String getRecepientValidationURL() {
return recepientValidationURL;
}
public void setRecepientValidationURL(String recepientValidationURL) {
this.recepientValidationURL = recepientValidationURL;
}
@XmlElement(name = "audience", required = true)
public String getAudience() {
return audience;
}
public void setAudience(String audience) {
this.audience = audience;
}
@XmlElement(name = "saasApp", required = true) @XmlElement(name = "saasApp", required = true)
public boolean isSaasApp() { public boolean isSaasApp() {

@ -16,16 +16,16 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.dynamic.client.web.app.registration; package org.wso2.carbon.dynamic.client.web.app.registration.dto;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
/** /**
* Represents an OAuth application with basic data. * Represents an OAuth application with basic necessary data.
*/ */
@XmlRootElement(name = "OAuthApp") @XmlRootElement(name = "OAuthAppDetails")
public class OAuthApp { public class OAuthAppDetails {
private String clientName; private String clientName;
private String clientKey; private String clientKey;

@ -44,10 +44,11 @@ public class DynamicClientWebAppRegistrationDataHolder {
} }
public ConfigurationContextService getConfigurationContextService() { public ConfigurationContextService getConfigurationContextService() {
if(configurationContextService != null){ if (configurationContextService != null) {
return configurationContextService; return configurationContextService;
} else { } else {
throw new IllegalStateException("ConfigurationContext service has not initialized properly"); throw new IllegalStateException(
"ConfigurationContext service has not initialized properly");
} }
} }
@ -57,10 +58,11 @@ public class DynamicClientWebAppRegistrationDataHolder {
} }
public DynamicClientRegistrationService getDynamicClientRegistrationService() { public DynamicClientRegistrationService getDynamicClientRegistrationService() {
if(dynamicClientRegistrationService != null){ if (dynamicClientRegistrationService != null) {
return dynamicClientRegistrationService; return dynamicClientRegistrationService;
} else { } else {
throw new IllegalStateException("DynamicClientRegistration service has not initialized properly"); throw new IllegalStateException(
"DynamicClientRegistration service has not initialized properly");
} }
} }
@ -70,7 +72,7 @@ public class DynamicClientWebAppRegistrationDataHolder {
} }
public RealmService getRealmService() { public RealmService getRealmService() {
if(realmService != null){ if (realmService != null) {
return realmService; return realmService;
} else { } else {
throw new IllegalStateException("RealmService has not initialized properly"); throw new IllegalStateException("RealmService has not initialized properly");
@ -82,7 +84,7 @@ public class DynamicClientWebAppRegistrationDataHolder {
} }
public RegistryService getRegistryService() { public RegistryService getRegistryService() {
if(registryService != null){ if (registryService != null) {
return registryService; return registryService;
} else { } else {
throw new IllegalStateException("Registry Service has not initialized properly"); throw new IllegalStateException("Registry Service has not initialized properly");

@ -21,7 +21,10 @@ package org.wso2.carbon.dynamic.client.web.app.registration.internal;
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.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.web.app.registration.WebAppRegistrationServerStartupObserver;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
@ -55,113 +58,119 @@ import org.wso2.carbon.utils.ConfigurationContextService;
*/ */
public class DynamicClientWebAppRegistrationServiceComponent { public class DynamicClientWebAppRegistrationServiceComponent {
private static Log log = LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); private static Log log =
LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) { @SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
} componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(),
new WebAppRegistrationServerStartupObserver(), null);
@SuppressWarnings("unused") }
protected void deactivate(ComponentContext componentContext) {
//do nothing @SuppressWarnings("unused")
} protected void deactivate(ComponentContext componentContext) {
/** }
* Sets Realm Service.
* /**
* @param realmService An instance of RealmService * Sets Realm Service.
*/ *
protected void setRealmService(RealmService realmService) { * @param realmService An instance of RealmService
if (log.isDebugEnabled()) { */
log.debug("Setting Realm Service"); protected void setRealmService(RealmService realmService) {
} if (log.isDebugEnabled()) {
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); log.debug("Setting Realm Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService);
/** }
* Unsets Realm Service.
* /**
* @param realmService An instance of RealmService * Unsets Realm Service.
*/ *
protected void unsetRealmService(RealmService realmService) { * @param realmService An instance of RealmService
if (log.isDebugEnabled()) { */
log.debug("Unsetting Realm Service"); protected void unsetRealmService(RealmService realmService) {
} if (log.isDebugEnabled()) {
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); log.debug("Unsetting Realm Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null);
/** }
* Sets Registry Service.
* /**
* @param registryService An instance of RegistryService * Sets Registry Service.
*/ *
protected void setRegistryService(RegistryService registryService) { * @param registryService An instance of RegistryService
if (log.isDebugEnabled()) { */
log.debug("Setting Registry Service"); protected void setRegistryService(RegistryService registryService) {
} if (log.isDebugEnabled()) {
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); log.debug("Setting Registry Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService);
/** }
* Unsets Registry Service.
* /**
* @param registryService An instance of RegistryService * Unsets Registry Service.
*/ *
protected void unsetRegistryService(RegistryService registryService) { * @param registryService An instance of RegistryService
if (log.isDebugEnabled()) { */
log.debug("Un setting Registry Service"); protected void unsetRegistryService(RegistryService registryService) {
} if (log.isDebugEnabled()) {
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); log.debug("Un setting Registry Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null);
/** }
* Sets Dynamic Client Registration Service.
* /**
* @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService * Sets Dynamic Client Registration Service.
*/ *
protected void setDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService
if (log.isDebugEnabled()) { */
log.debug("Setting Dynamic Client Registration Service"); protected void setDynamicClientService(
} DynamicClientRegistrationService dynamicClientRegistrationService) {
DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( if (log.isDebugEnabled()) {
dynamicClientRegistrationService); log.debug("Setting Dynamic Client Registration Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(
/** dynamicClientRegistrationService);
* Unsets Dynamic Client Registration Service. }
*
* @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService /**
*/ * Unsets Dynamic Client Registration Service.
protected void unsetDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { *
if (log.isDebugEnabled()) { * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService
log.debug("Un setting Dynamic Client Registration Service"); */
} protected void unsetDynamicClientService(
DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); DynamicClientRegistrationService dynamicClientRegistrationService) {
} if (log.isDebugEnabled()) {
log.debug("Un setting Dynamic Client Registration Service");
/** }
* Sets ConfigurationContext Service. DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null);
* }
* @param configurationContextService An instance of ConfigurationContextService
*/ /**
protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { * Sets ConfigurationContext Service.
if (log.isDebugEnabled()) { *
log.debug("Setting ConfigurationContextService"); * @param configurationContextService An instance of ConfigurationContextService
} */
DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService); protected void setConfigurationContextService(
} ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
/** log.debug("Setting ConfigurationContextService");
* Unsets ConfigurationContext Service. }
* DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(
* @param configurationContextService An instance of ConfigurationContextService configurationContextService);
*/ }
protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) { /**
log.debug("Un-setting ConfigurationContextService"); * Unsets ConfigurationContext Service.
} *
DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); * @param configurationContextService An instance of ConfigurationContextService
} */
protected void unsetConfigurationContextService(
} ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService");
}
DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null);
}
}

@ -40,8 +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();
DynamicClientWebAppRegistrationManager.getInstance().initiateDynamicClientRegistrationProcess( DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache(context);
context);
} }
} }
} }

@ -24,8 +24,8 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException;
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.dto.OAuthAppDetails;
import org.wso2.carbon.dynamic.client.web.app.registration.OAuthSettings; import org.wso2.carbon.dynamic.client.web.app.registration.dto.JaggeryOAuthConfigurationSettings;
import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder; 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;
@ -52,8 +52,11 @@ public class DynamicClientWebAppRegistrationUtil {
private final static String OAUTH_PARAM_TOKEN_SCOPE = "tokenScope"; private final static String OAUTH_PARAM_TOKEN_SCOPE = "tokenScope";
private final static String OAUTH_PARAM_SAAS_APP = "saasApp"; private final static String OAUTH_PARAM_SAAS_APP = "saasApp";
private final static String OAUTH_PARAM_CALLBACK_URL = "callbackURL"; private final static String OAUTH_PARAM_CALLBACK_URL = "callbackURL";
private final static String AUDIENCE = "audience";
private final static String ASSERTION_CONSUMER_URL = "assertionConsumerURL";
private final static String RECEPIENT_VALIDATION_URL = "recepientValidationURL";
private static final String JAGGERY_APP_OAUTH_CONFIG_PATH = private static final String JAGGERY_APP_OAUTH_CONFIG_PATH =
"config" + File.separator + "oauth.json"; "config" + File.separator + "service-provider.json";
private static final Log log = private static final Log log =
LogFactory.getLog(DynamicClientWebAppRegistrationUtil.class); LogFactory.getLog(DynamicClientWebAppRegistrationUtil.class);
@ -62,9 +65,8 @@ 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 DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService() return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService().
.getGovernanceSystemRegistry( getGovernanceSystemRegistry(tenantId);
tenantId);
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error in retrieving governance registry instance: " + "Error in retrieving governance registry instance: " +
@ -72,115 +74,98 @@ public class DynamicClientWebAppRegistrationUtil {
} }
} }
public static OAuthApp getOAuthApplicationData(String appName) public static OAuthAppDetails getOAuthApplicationData(String appName)
throws DynamicClientRegistrationException { throws DynamicClientRegistrationException {
Resource resource; Resource resource;
String resourcePath = String resourcePath = DynamicClientWebAppRegistrationConstants.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");
} }
resource = DynamicClientWebAppRegistrationUtil.getRegistryResource(resourcePath); resource = DynamicClientWebAppRegistrationUtil.getRegistryResource(resourcePath);
if (resource != null) { if (resource != null) {
JAXBContext context = JAXBContext.newInstance(OAuthApp.class); JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class);
Unmarshaller unmarshaller = context.createUnmarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller();
return (OAuthApp) unmarshaller.unmarshal( return (OAuthAppDetails) unmarshaller.unmarshal(
new StringReader(new String((byte[]) resource.getContent(), Charset new StringReader(new String((byte[]) resource.getContent(), Charset.forName(
.forName( DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8))));
DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8))));
} }
return new OAuthApp(); return new OAuthAppDetails();
} catch (JAXBException e) { } catch (JAXBException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while parsing the OAuth application data : " + appName, e); "Error occurred while parsing the OAuth application data : " + appName, e);
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while retrieving the Registry resource of OAuth application : " + "Error occurred while retrieving the Registry resource of OAuth application : " + appName, e);
appName, e);
} }
} }
public static boolean putOAuthApplicationData(OAuthApp oAuthApp) public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws
throws DynamicClientRegistrationException { DynamicClientRegistrationException {
boolean status; boolean status;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Persisting OAuth application data in Registry"); log.debug("Persisting OAuth application data in Registry");
} }
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(OAuthApp.class); JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class);
Marshaller marshaller = context.createMarshaller(); Marshaller marshaller = context.createMarshaller();
marshaller.marshal(oAuthApp, writer); marshaller.marshal(oAuthAppDetails, writer);
Resource resource = Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource();
DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource();
resource.setContent(writer.toString()); resource.setContent(writer.toString());
resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML);
String resourcePath = String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" +
DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + oAuthAppDetails.getWebAppName();
oAuthApp.getWebAppName(); status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource);
status =
DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource);
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while persisting OAuth application data : " + "Error occurred while persisting OAuth application data : " +
oAuthApp.getClientName(), e); oAuthAppDetails.getClientName(), e);
} catch (JAXBException e) { } catch (JAXBException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException(
"Error occurred while parsing the OAuth application data : " + "Error occurred while parsing the OAuth application data : " +
oAuthApp.getWebAppName(), e); oAuthAppDetails.getWebAppName(), e);
} }
return status; return status;
} }
public static boolean putRegistryResource(String path, public static boolean putRegistryResource(String path, Resource resource) throws DynamicClientRegistrationException {
Resource resource)
throws DynamicClientRegistrationException {
boolean status;
try { try {
Registry governanceRegistry = DynamicClientWebAppRegistrationUtil Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry();
.getGovernanceRegistry();
governanceRegistry.beginTransaction(); governanceRegistry.beginTransaction();
governanceRegistry.put(path, resource); governanceRegistry.put(path, resource);
governanceRegistry.commitTransaction(); governanceRegistry.commitTransaction();
status = true; return true;
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException("Error occurred while persisting registry resource : " +
"Error occurred while persisting registry resource : " + e.getMessage(), e);
e.getMessage(), e);
} }
return status;
} }
public static Resource getRegistryResource(String path) public static Resource getRegistryResource(String path) throws DynamicClientRegistrationException {
throws DynamicClientRegistrationException {
try { try {
Registry governanceRegistry = DynamicClientWebAppRegistrationUtil Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry();
.getGovernanceRegistry();
if (governanceRegistry.resourceExists(path)) { if (governanceRegistry.resourceExists(path)) {
return governanceRegistry.get(path); return governanceRegistry.get(path);
} }
return null; return null;
} catch (RegistryException e) { } catch (RegistryException e) {
throw new DynamicClientRegistrationException( throw new DynamicClientRegistrationException("Error in retrieving registry resource : " +
"Error in retrieving registry resource : " + e.getMessage(), e);
e.getMessage(), e);
} }
} }
public static String getUserName() { public static String getUserName() {
String username = ""; String username = "";
RealmService realmService = RealmService realmService = DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService();
DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService();
if (realmService != null) { if (realmService != null) {
username = realmService.getBootstrapRealmConfiguration().getAdminUserName(); username = realmService.getBootstrapRealmConfiguration().getAdminUserName();
} }
return username; return username;
} }
public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, String webAppName) {
String webAppName) {
RegistrationProfile registrationProfile; RegistrationProfile registrationProfile;
registrationProfile = new RegistrationProfile(); registrationProfile = new RegistrationProfile();
registrationProfile.setGrantType(servletContext.getInitParameter( registrationProfile.setGrantType(servletContext.getInitParameter(
@ -193,40 +178,40 @@ public class DynamicClientWebAppRegistrationUtil {
if ((callbackURL != null) && !callbackURL.isEmpty()) { if ((callbackURL != null) && !callbackURL.isEmpty()) {
registrationProfile.setCallbackUrl(callbackURL); registrationProfile.setCallbackUrl(callbackURL);
} else { } else {
registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl( registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName));
webAppName));
} }
registrationProfile.setClientName(webAppName); registrationProfile.setClientName(webAppName);
registrationProfile.setSaasApp(Boolean.parseBoolean(servletContext.getInitParameter( registrationProfile.setSaasApp(Boolean.parseBoolean(servletContext.getInitParameter(
DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP))); DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP)));
return registrationProfile; return registrationProfile;
} }
public static RegistrationProfile constructRegistrationProfile( public static RegistrationProfile constructRegistrationProfile(JaggeryOAuthConfigurationSettings
OAuthSettings oAuthSettings, String webAppName) { jaggeryOAuthConfigurationSettings, String webAppName) {
RegistrationProfile registrationProfile = new RegistrationProfile(); RegistrationProfile registrationProfile = new RegistrationProfile();
if (oAuthSettings != null) { if (jaggeryOAuthConfigurationSettings != null) {
registrationProfile.setGrantType(oAuthSettings.getGrantType()); registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType());
registrationProfile.setTokenScope(oAuthSettings.getTokenScope()); registrationProfile.setTokenScope(jaggeryOAuthConfigurationSettings.getTokenScope());
registrationProfile.setClientName(webAppName); registrationProfile.setClientName(webAppName);
registrationProfile.setSaasApp(oAuthSettings.isSaasApp()); registrationProfile.setSaasApp(jaggeryOAuthConfigurationSettings.isSaasApp());
registrationProfile.setOwner(DynamicClientWebAppRegistrationUtil.getUserName()); registrationProfile.setOwner(DynamicClientWebAppRegistrationUtil.getUserName());
if (oAuthSettings.getCallbackURL() != null) { registrationProfile.setAudience(jaggeryOAuthConfigurationSettings.getAudience());
registrationProfile.setCallbackUrl(oAuthSettings.getCallbackURL()); registrationProfile.setAssertionConsumerURL(jaggeryOAuthConfigurationSettings.getAssertionConsumerURL());
registrationProfile.setRecepientValidationURL(jaggeryOAuthConfigurationSettings.getRecepientValidationURL());
if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) {
registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL());
} else { } else {
registrationProfile.setCallbackUrl( registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName));
DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName));
} }
} else { } else {
log.warn( log.warn("Please configure OAuth settings properly for jaggery app : " + webAppName);
"Please configure OAuth settings properly for jaggery app : " + webAppName);
} }
return registrationProfile; return registrationProfile;
} }
public static boolean validateRegistrationProfile(RegistrationProfile registrationProfile) { public static boolean validateRegistrationProfile(RegistrationProfile registrationProfile) {
boolean status = true; boolean status = true;
//todo fix this
if (registrationProfile.getGrantType() == null) { if (registrationProfile.getGrantType() == null) {
status = false; status = false;
log.warn("Required parameter 'grantType' is missing for initiating Dynamic-Client " + log.warn("Required parameter 'grantType' is missing for initiating Dynamic-Client " +
@ -240,43 +225,50 @@ public class DynamicClientWebAppRegistrationUtil {
return status; return status;
} }
public static OAuthSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) {
OAuthSettings oAuthSettings = new OAuthSettings(); JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings();
try { try {
InputStream inputStream = InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH);
servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH);
if (inputStream != null) { if (inputStream != null) {
JsonReader reader = JsonReader reader = new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8));
new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8));
reader.beginObject(); reader.beginObject();
while (reader.hasNext()) { while (reader.hasNext()) {
String key = reader.nextName(); String key = reader.nextName();
switch (key) { switch (key) {
case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG: case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG:
oAuthSettings.setRequireDynamicClientRegistration(reader.nextBoolean()); jaggeryOAuthConfigurationSettings.setRequireDynamicClientRegistration(reader.nextBoolean());
break; break;
case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE: case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE:
oAuthSettings.setGrantType(reader.nextString()); jaggeryOAuthConfigurationSettings.setGrantType(reader.nextString());
break; break;
case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_TOKEN_SCOPE: case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_TOKEN_SCOPE:
oAuthSettings.setTokenScope(reader.nextString()); jaggeryOAuthConfigurationSettings.setTokenScope(reader.nextString());
break; break;
case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP: case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP:
oAuthSettings.setSaasApp(reader.nextBoolean()); jaggeryOAuthConfigurationSettings.setSaasApp(reader.nextBoolean());
break; break;
case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL: case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL:
oAuthSettings.setCallbackURL(reader.nextString()); jaggeryOAuthConfigurationSettings.setCallbackURL(reader.nextString());
break;
case DynamicClientWebAppRegistrationUtil.AUDIENCE:
jaggeryOAuthConfigurationSettings.setAudience(reader.nextString());
break;
case DynamicClientWebAppRegistrationUtil.ASSERTION_CONSUMER_URL:
jaggeryOAuthConfigurationSettings.setAssertionConsumerURL(reader.nextString());
break;
case DynamicClientWebAppRegistrationUtil.RECEPIENT_VALIDATION_URL:
jaggeryOAuthConfigurationSettings.setRecepientValidationURL(reader.nextString());
break; break;
} }
} }
return oAuthSettings; return jaggeryOAuthConfigurationSettings;
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e); log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e); log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
} }
return oAuthSettings; return jaggeryOAuthConfigurationSettings;
} }
public static String getServerBaseUrl() { public static String getServerBaseUrl() {
@ -304,18 +296,18 @@ public class DynamicClientWebAppRegistrationUtil {
return getServerBaseUrl() + "/" + context; return getServerBaseUrl() + "/" + context;
} }
public static void addClientCredentialsToWebContext(OAuthApp oAuthApp, public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails,
ServletContext servletContext) { ServletContext servletContext) {
if(oAuthApp != null){ if (oAuthAppDetails != null) {
//Check for client credentials //Check for client credentials
if ((oAuthApp.getClientKey() != null && !oAuthApp.getClientKey().isEmpty()) && if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) &&
(oAuthApp.getClientSecret() != null && !oAuthApp.getClientSecret().isEmpty())) { (oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) {
servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_KEY, servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_KEY,
oAuthApp.getClientKey()); oAuthAppDetails.getClientKey());
servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_SECRET, servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_SECRET,
oAuthApp.getClientSecret()); oAuthAppDetails.getClientSecret());
} else { } else {
log.warn("Client credentials not found for web app : " + oAuthApp.getWebAppName()); log.warn("Client credentials not found for web app : " + oAuthAppDetails.getWebAppName());
} }
} }
} }

@ -37,7 +37,7 @@ import java.util.Properties;
* Custom OAuth2Token Scope validation implementation for DeviceManagement. This will validate the * Custom OAuth2Token Scope validation implementation for DeviceManagement. This will validate the
* user permissions before dispatching the HTTP request to the actual endpoint. * user permissions before dispatching the HTTP request to the actual endpoint.
*/ */
public class ScopeValidator extends OAuth2ScopeValidator { public class PermissionBasedScopeValidator extends OAuth2ScopeValidator {
private static final String URL_PROPERTY = "URL"; private static final String URL_PROPERTY = "URL";
private static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD"; private static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD";
@ -46,13 +46,14 @@ public class ScopeValidator extends OAuth2ScopeValidator {
private PermissionMethod() { private PermissionMethod() {
throw new AssertionError(); throw new AssertionError();
} }
public static final String READ = "read"; public static final String READ = "read";
public static final String WRITE = "write"; public static final String WRITE = "write";
public static final String DELETE = "delete"; public static final String DELETE = "delete";
public static final String ACTION = "action"; public static final String ACTION = "action";
} }
private static final Log log = LogFactory.getLog(ScopeValidator.class); private static final Log log = LogFactory.getLog(PermissionBasedScopeValidator.class);
@Override @Override
public boolean validateScope(AccessTokenDO accessTokenDO, String resource) public boolean validateScope(AccessTokenDO accessTokenDO, String resource)
@ -64,18 +65,19 @@ public class ScopeValidator extends OAuth2ScopeValidator {
String method = resource.substring(++idx, resource.length()); String method = resource.substring(++idx, resource.length());
Properties properties = new Properties(); Properties properties = new Properties();
properties.put(ScopeValidator.URL_PROPERTY, url); properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url);
properties.put(ScopeValidator.HTTP_METHOD_PROPERTY, method); properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method);
PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance(). PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance().
getPermissionManagerService(); getPermissionManagerService();
try { try {
Permission permission = permissionManagerService.getPermission(properties); Permission permission = permissionManagerService.getPermission(properties);
if((permission != null) && (accessTokenDO.getAuthzUser() != null)) { if ((permission != null) && (accessTokenDO.getAuthzUser() != null)) {
String username = accessTokenDO.getAuthzUser().getUserName(); String username = accessTokenDO.getAuthzUser().getUserName();
UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm(); UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
if(userRealm != null && userRealm.getAuthorizationManager() != null){ if (userRealm != null && userRealm.getAuthorizationManager() != null) {
status = userRealm.getAuthorizationManager().isUserAuthorized(username, permission.getPath(), status = userRealm.getAuthorizationManager()
PermissionMethod.READ); .isUserAuthorized(username, permission.getPath(),
PermissionMethod.READ);
} }
} }
} catch (PermissionManagementException e) { } catch (PermissionManagementException e) {

@ -37,6 +37,7 @@
<modules> <modules>
<module>org.wso2.carbon.device.mgt.oauth.extensions</module> <module>org.wso2.carbon.device.mgt.oauth.extensions</module>
<module>dynamic-client-registration</module> <module>dynamic-client-registration</module>
<module>backend-oauth-authenticator</module>
</modules> </modules>
</project> </project>

@ -44,10 +44,11 @@ public class Policy implements Comparable<Policy>, Serializable {
private List<String> users; private List<String> users;
private boolean active; private boolean active;
private boolean updated; private boolean updated;
private String description;
/* Compliance data*/ /* Compliance data*/
private String Compliance; private String compliance;
/*Dynamic policy attributes*/ /*Dynamic policy attributes*/
@ -170,6 +171,15 @@ public class Policy implements Comparable<Policy>, Serializable {
this.updated = updated; this.updated = updated;
} }
@XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@XmlElement @XmlElement
public List<PolicyCriterion> getPolicyCriterias() { public List<PolicyCriterion> getPolicyCriterias() {
return policyCriterias; return policyCriterias;
@ -181,11 +191,11 @@ public class Policy implements Comparable<Policy>, Serializable {
@XmlElement @XmlElement
public String getCompliance() { public String getCompliance() {
return Compliance; return compliance;
} }
public void setCompliance(String compliance) { public void setCompliance(String compliance) {
Compliance = compliance; this.compliance = compliance;
} }
@XmlElement @XmlElement

@ -69,7 +69,7 @@ public interface PolicyManagerService {
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException; deviceResponse) throws PolicyComplianceException;
boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException; boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException;

@ -22,10 +22,7 @@ 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.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
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.core.operation.mgt.PolicyOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
@ -170,7 +167,7 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
} }
@Override @Override
public List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException { deviceResponse) throws PolicyComplianceException {
return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse); return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse);
} }

@ -19,11 +19,9 @@
package org.wso2.carbon.policy.mgt.core.dao; package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Criterion; import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyCriterion; import org.wso2.carbon.policy.mgt.common.PolicyCriterion;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -34,8 +32,22 @@ public interface PolicyDAO {
Policy addPolicy(String deviceType, Policy policy) throws PolicyManagerDAOException; Policy addPolicy(String deviceType, Policy policy) throws PolicyManagerDAOException;
/**
* This method is used to add/update the roles associated with the policy.
* @param roleNames - List of the roles that needs to be applied
* @param policy - policy object with the current role list
* @return
* @throws PolicyManagerDAOException
*/
Policy addPolicyToRole(List<String> roleNames, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToRole(List<String> roleNames, Policy policy) throws PolicyManagerDAOException;
/**
* This method is used to add/update the users associated with the policy.
* @param usernameList - List of the users that needs to be applied
* @param policy - policy object with the current role list
* @return
* @throws PolicyManagerDAOException
*/
Policy addPolicyToUser(List<String> usernameList, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToUser(List<String> usernameList, Policy policy) throws PolicyManagerDAOException;
Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException;

@ -22,17 +22,15 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Criterion; import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyCriterion; import org.wso2.carbon.policy.mgt.common.PolicyCriterion;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import org.wso2.carbon.policy.mgt.core.util.SetReferenceTransformer;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@ -70,45 +68,87 @@ public class PolicyDAOImpl implements PolicyDAO {
} }
@Override @Override
public Policy addPolicyToRole(List<String> roleNames, Policy policy) throws PolicyManagerDAOException { public Policy addPolicyToRole(List<String> rolesToAdd, Policy policy) throws PolicyManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement insertStmt = null;
PreparedStatement deleteStmt = null;
final List<String> currentRoles = policy.getRoles();
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
transformer.transform(currentRoles, rolesToAdd);
rolesToAdd = transformer.getObjectsToAdd();
List<String> rolesToDelete = transformer.getObjectsToRemove();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)"; if (rolesToAdd.size() > 0){
stmt = conn.prepareStatement(query); String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)";
for (String role : roleNames) { insertStmt = conn.prepareStatement(query);
stmt.setString(1, role); for (String role : rolesToAdd) {
stmt.setInt(2, policy.getId()); insertStmt.setString(1, role);
stmt.addBatch(); insertStmt.setInt(2, policy.getId());
insertStmt.addBatch();
}
insertStmt.executeBatch();
}
if (rolesToAdd.size() > 0){
String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?";
deleteStmt = conn.prepareStatement(deleteQuery);
for (String role : rolesToDelete) {
deleteStmt.setString(1, role);
deleteStmt.setInt(2, policy.getId());
deleteStmt.addBatch();
}
deleteStmt.executeBatch();
} }
stmt.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database", e); throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database", e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
} }
return policy; return policy;
} }
@Override @Override
public Policy addPolicyToUser(List<String> usernameList, Policy policy) throws PolicyManagerDAOException { public Policy addPolicyToUser(List<String> usersToAdd, Policy policy) throws PolicyManagerDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement insertStmt = null;
PreparedStatement deleteStmt = null;
final List<String> currentUsers = policy.getUsers();
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
transformer.transform(currentUsers, usersToAdd);
usersToAdd = transformer.getObjectsToAdd();
List<String> usersToDelete = transformer.getObjectsToRemove();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)"; if (usersToAdd.size() > 0){
stmt = conn.prepareStatement(query); String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)";
for (String username : usernameList) { insertStmt = conn.prepareStatement(query);
stmt.setInt(1, policy.getId()); for (String username : usersToAdd) {
stmt.setString(2, username); insertStmt.setInt(1, policy.getId());
stmt.addBatch(); insertStmt.setString(2, username);
insertStmt.addBatch();
}
insertStmt.executeBatch();
} }
stmt.executeBatch(); if (usersToDelete.size() > 0){
String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?";
deleteStmt = conn.prepareStatement(deleteQuery);
for (String username : usersToDelete) {
deleteStmt.setString(1, username);
deleteStmt.setInt(2, policy.getId());
deleteStmt.addBatch();
}
deleteStmt.executeBatch();
}
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database", e); throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database", e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
PolicyManagementDAOUtil.cleanupResources(deleteStmt, null);
} }
return policy; return policy;
} }
@ -611,15 +651,16 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," + String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," +
" UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; " UPDATED = ?, DESCRIPTION = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
stmt.setInt(2, policy.getProfile().getProfileId()); stmt.setInt(2, policy.getProfile().getProfileId());
stmt.setInt(3, policy.getPriorityId()); stmt.setInt(3, policy.getPriorityId());
stmt.setString(4, policy.getCompliance()); stmt.setString(4, policy.getCompliance());
stmt.setInt(5, 1); stmt.setInt(5, 1);
stmt.setInt(6, policy.getId()); stmt.setString(6, policy.getDescription());
stmt.setInt(7, tenantId); stmt.setInt(7, policy.getId());
stmt.setInt(8, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
@ -724,6 +765,9 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setProfileId(resultSet.getInt("PROFILE_ID")); policy.setProfileId(resultSet.getInt("PROFILE_ID"));
policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
} }
return policy; return policy;
@ -757,6 +801,9 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setTenantId(resultSet.getInt("TENANT_ID")); policy.setTenantId(resultSet.getInt("TENANT_ID"));
policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
} }
return policy; return policy;
} catch (SQLException e) { } catch (SQLException e) {
@ -792,6 +839,7 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policies.add(policy); policies.add(policy);
} }
return policies; return policies;
@ -1167,8 +1215,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
" " + "UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
"UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
@ -1179,6 +1226,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setString(6, policy.getOwnershipType()); stmt.setString(6, policy.getOwnershipType());
stmt.setInt(7, 0); stmt.setInt(7, 0);
stmt.setInt(8, 0); stmt.setInt(8, 0);
stmt.setString(9, policy.getDescription());
int affectedRows = stmt.executeUpdate(); int affectedRows = stmt.executeUpdate();

@ -35,6 +35,7 @@ import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
/** /**
@ -86,11 +87,13 @@ public class PolicyManagementServiceComponent {
componentContext.getBundleContext().registerService( componentContext.getBundleContext().registerService(
PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null); PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null);
PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getDeviceManagementConfigRepository().getPolicyConfiguration(); getDeviceManagementConfigRepository().getPolicyConfiguration();
if(policyConfiguration.getMonitoringEnable()) { if(policyConfiguration.getMonitoringEnable()) {
TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl();
taskScheduleService.startTask(policyConfiguration.getMonitoringFrequency()); taskScheduleService.startTask(PolicyManagerUtil.getMonitoringFequency());
} }
} catch (Throwable t) { } catch (Throwable t) {

@ -27,9 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
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.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfigRepository;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -320,6 +318,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
if (!deviceIdsToAddOperation.isEmpty()) { if (!deviceIdsToAddOperation.isEmpty()) {
// monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); // monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
monitoringDAO.addComplianceDetails(firstTimeDevices); monitoringDAO.addComplianceDetails(firstTimeDevices);
monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsToAddOperation.keySet()), false);
} }
if (!deviceIdsWithExistingOperation.isEmpty()) { if (!deviceIdsWithExistingOperation.isEmpty()) {

@ -25,13 +25,11 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
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.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager;
import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl;
import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.dao.*;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
@ -136,6 +134,9 @@ public class PolicyManagerImpl implements PolicyManager {
public Policy updatePolicy(Policy policy) throws PolicyManagementException { public Policy updatePolicy(Policy policy) throws PolicyManagementException {
try { try {
// Previous policy needs to be obtained before begining the transaction
Policy previousPolicy = getPolicy(policy.getId());
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
// This will keep track of the policies updated. // This will keep track of the policies updated.
policyDAO.recordUpdatedPolicy(policy); policyDAO.recordUpdatedPolicy(policy);
@ -146,16 +147,18 @@ public class PolicyManagerImpl implements PolicyManager {
.getProfileId()); .getProfileId());
policyDAO.deleteAllPolicyRelatedConfigs(policy.getId()); policyDAO.deleteAllPolicyRelatedConfigs(policy.getId());
if (policy.getUsers() != null) { if (policy.getUsers() != null) {
policyDAO.addPolicyToUser(policy.getUsers(), policy); policyDAO.addPolicyToUser(policy.getUsers(), previousPolicy);
} }
if (policy.getRoles() != null) { if (policy.getRoles() != null) {
policyDAO.addPolicyToRole(policy.getRoles(), policy); policyDAO.addPolicyToRole(policy.getRoles(), previousPolicy);
} }
if (policy.getDevices() != null) { if (policy.getDevices() != null) {
policyDAO.addPolicyToDevice(policy.getDevices(), policy); policyDAO.addPolicyToDevice(policy.getDevices(), previousPolicy);
} }
if (policy.getPolicyCriterias() != null) { if (policy.getPolicyCriterias() != null) {
@ -468,17 +471,18 @@ public class PolicyManagerImpl implements PolicyManager {
Policy policy; Policy policy;
List<Device> deviceList; List<Device> deviceList;
List<String> roleNames; List<String> roleNames;
List<String> userNames;
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policy = policyDAO.getPolicy(policyId); policy = policyDAO.getPolicy(policyId);
roleNames = policyDAO.getPolicyAppliedRoles(policyId); roleNames = policyDAO.getPolicyAppliedRoles(policyId);
userNames = policyDAO.getPolicyAppliedUsers(policyId);
Profile profile = profileDAO.getProfile(policy.getProfileId()); Profile profile = profileDAO.getProfile(policy.getProfileId());
policy.setProfile(profile); policy.setProfile(profile);
policy.setRoles(roleNames); policy.setRoles(roleNames);
policy.setUsers(userNames);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" +

@ -122,9 +122,9 @@ public class PolicyManagementService implements PolicyManagerService {
} }
@Override @Override
public List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException { deviceResponse) throws PolicyComplianceException {
return policyManagerService.CheckPolicyCompliance(deviceIdentifier, deviceResponse); return policyManagerService.checkPolicyCompliance(deviceIdentifier, deviceResponse);
} }
@Override @Override

@ -22,7 +22,14 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
@ -41,15 +48,16 @@ import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
public class PolicyManagerUtil { public class PolicyManagerUtil {
private static final Log log = LogFactory.getLog(PolicyManagerUtil.class); private static final Log log = LogFactory.getLog(PolicyManagerUtil.class);
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
public static final String MONITORING_FREQUENCY = "notifierFrequency";
public static Document convertToDocument(File file) throws PolicyManagementException { public static Document convertToDocument(File file) throws PolicyManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
@ -159,13 +167,13 @@ public class PolicyManagerUtil {
// } // }
public static Cache<Integer, Policy> getPolicyCache(String name){ public static Cache<Integer, Policy> getPolicyCache(String name) {
CacheManager manager = getCacheManager(); CacheManager manager = getCacheManager();
return (manager != null) ? manager.<Integer, Policy>getCache(name) : return (manager != null) ? manager.<Integer, Policy>getCache(name) :
Caching.getCacheManager().<Integer, Policy>getCache(name); Caching.getCacheManager().<Integer, Policy>getCache(name);
} }
public static Cache<Integer, List<Policy>> getPolicyListCache(String name){ public static Cache<Integer, List<Policy>> getPolicyListCache(String name) {
CacheManager manager = getCacheManager(); CacheManager manager = getCacheManager();
return (manager != null) ? manager.<Integer, List<Policy>>getCache(name) : return (manager != null) ? manager.<Integer, List<Policy>>getCache(name) :
Caching.getCacheManager().<Integer, List<Policy>>getCache(name); Caching.getCacheManager().<Integer, List<Policy>>getCache(name);
@ -185,4 +193,35 @@ public class PolicyManagerUtil {
} }
return deviceHashMap; return deviceHashMap;
} }
public static int getMonitoringFequency() {
TenantConfigurationManagementService configMgtService = new TenantConfigurationManagementServiceImpl();
TenantConfiguration tenantConfiguration = null;
int monitoringFrequency = 0;
try {
tenantConfiguration = configMgtService.getConfiguration(GENERAL_CONFIG_RESOURCE_PATH);
List<ConfigurationEntry> configuration = tenantConfiguration.getConfiguration();
if (configuration != null && !configuration.isEmpty()) {
for (ConfigurationEntry cEntry : configuration) {
if (cEntry.getName().equalsIgnoreCase(MONITORING_FREQUENCY)) {
monitoringFrequency = (int) cEntry.getValue();
}
}
}
} catch (ConfigurationManagementException e) {
log.error("Error while getting the configurations from registry.", e);
}
if (monitoringFrequency == 0) {
PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig().getDeviceManagementConfigRepository().getPolicyConfiguration();
monitoringFrequency = policyConfiguration.getMonitoringFrequency();
}
return monitoringFrequency;
}
} }

@ -0,0 +1,42 @@
package org.wso2.carbon.policy.mgt.core.util;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class SetReferenceTransformer<T>{
private List<T> objectsToRemove;
private List<T> objectsToAdd;
/**
* Use the Set theory to find the objects to delete and objects to add
The difference of objects in existingSet and newSet needed to be deleted
new roles to add = newSet - The intersection of roles in existingSet and newSet
* @param currentList
* @param nextList
*/
public void transform(List<T> currentList, List<T> nextList){
TreeSet<T> existingSet = new TreeSet<T>(currentList);
TreeSet<T> newSet = new TreeSet<T>(nextList);;
existingSet.removeAll(newSet);
objectsToRemove = new ArrayList<>(existingSet);
// Clearing and re-initializing the set
existingSet = new TreeSet<T>(currentList);
newSet.removeAll(existingSet);
objectsToAdd = new ArrayList<T>(newSet);
}
public List<T> getObjectsToRemove() {
return objectsToRemove;
}
public List<T> getObjectsToAdd() {
return objectsToAdd;
}
}

@ -27,15 +27,12 @@ import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
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.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl; import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.util.*; import org.wso2.carbon.policy.mgt.core.util.*;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
@ -163,6 +160,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
roles.add("Test_ROLE_02"); roles.add("Test_ROLE_02");
roles.add("Test_ROLE_03"); roles.add("Test_ROLE_03");
policy = pap.getPolicy(policy.getId());
pap.addPolicyToRole(roles, policy); pap.addPolicyToRole(roles, policy);
} }

@ -39,6 +39,7 @@ public class PolicyCreator {
policy.setUsers(users); policy.setUsers(users);
policy.setCompliance("NOTIFY"); policy.setCompliance("NOTIFY");
policy.setOwnershipType("COPE"); policy.setOwnershipType("COPE");
policy.setDescription("This is the first policy.");
return policy; return policy;
} }
@ -87,6 +88,7 @@ public class PolicyCreator {
policy.setOwnershipType("COPE"); policy.setOwnershipType("COPE");
policy.setPolicyCriterias(criteria); policy.setPolicyCriterias(criteria);
policy.setDescription("This is the second policy.");
return policy; return policy;
@ -126,7 +128,7 @@ public class PolicyCreator {
criteria.add(criterion); criteria.add(criterion);
policy.setPolicyCriterias(criteria); policy.setPolicyCriterias(criteria);
policy.setDescription("This is the third policy.");
return policy; return policy;
} }
@ -175,6 +177,8 @@ public class PolicyCreator {
policy.setPolicyCriterias(criteria); policy.setPolicyCriterias(criteria);
policy.setDescription("This is the fourth policy.");
return policy; return policy;
} }

@ -139,6 +139,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE (
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) NULL DEFAULT NULL , NAME VARCHAR(45) NULL DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,

@ -62,8 +62,8 @@ public class AuthenticationFrameworkUtil {
String username = apiKeyValidationDTO.getEndUserName(); String username = apiKeyValidationDTO.getEndUserName();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
try { try {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(IdentityUtil.
IdentityUtil.getTenantIdOFUser(username)); getTenantIdOFUser(username));
} catch (IdentityException e) { } catch (IdentityException e) {
throw new AuthenticationException("Error occurred while retrieving the tenant ID of user '" + throw new AuthenticationException("Error occurred while retrieving the tenant ID of user '" +
username + "'", e); username + "'", e);

@ -0,0 +1,65 @@
/*
* 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.webapp.authenticator.framework;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
/**
* DTO class to hold the information of authenticated user AND STATUS.
*/
public class AuthenticationInfo {
private WebappAuthenticator.Status status = WebappAuthenticator.Status.FAILURE;
private String username;
private String tenantDomain;
private int tenantId = -1;
public WebappAuthenticator.Status getStatus() {
return status;
}
public void setStatus(
WebappAuthenticator.Status status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -23,7 +23,7 @@ import org.wso2.carbon.device.mgt.core.scep.SCEPManager;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; 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 AuthenticatorFrameworkDataHolder {
private WebappAuthenticatorRepository repository; private WebappAuthenticatorRepository repository;
private RealmService realmService; private RealmService realmService;
@ -31,11 +31,12 @@ public class DataHolder {
private SCEPManager scepManager; private SCEPManager scepManager;
private OAuth2TokenValidationService oAuth2TokenValidationService; private OAuth2TokenValidationService oAuth2TokenValidationService;
private static DataHolder thisInstance = new DataHolder(); private static AuthenticatorFrameworkDataHolder
thisInstance = new AuthenticatorFrameworkDataHolder();
private DataHolder() {} private AuthenticatorFrameworkDataHolder() {}
public static DataHolder getInstance() { public static AuthenticatorFrameworkDataHolder getInstance() {
return thisInstance; return thisInstance;
} }

@ -22,6 +22,7 @@ import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response; 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.PrivilegedCarbonContext;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.tomcat.ext.valves.CompositeValve;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
@ -31,9 +32,9 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
public class WebappAuthenticationHandler extends CarbonTomcatValve { public class WebappAuthenticationValve extends CarbonTomcatValve {
private static final Log log = LogFactory.getLog(WebappAuthenticationHandler.class); private static final Log log = LogFactory.getLog(WebappAuthenticationValve.class);
private static final String BYPASS_URIS = "bypass-uris"; private static final String BYPASS_URIS = "bypass-uris";
@Override @Override
@ -44,16 +45,13 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve {
return; return;
} }
String byPassURIs = request.getContext().findParameter(WebappAuthenticationHandler.BYPASS_URIS); String byPassURIs = request.getContext().findParameter(WebappAuthenticationValve.BYPASS_URIS);
if(byPassURIs != null && !byPassURIs.isEmpty()) {
if (byPassURIs != null && !byPassURIs.isEmpty()) {
List<String> requestURI = Arrays.asList(byPassURIs.split(",")); List<String> requestURI = Arrays.asList(byPassURIs.split(","));
if (requestURI != null && requestURI.size() > 0) {
if(requestURI != null && requestURI.size() > 0) {
for (String pathURI : requestURI) { for (String pathURI : requestURI) {
pathURI = pathURI.replace("\n", "").replace("\r", "").trim(); pathURI = pathURI.replace("\n", "").replace("\r", "").trim();
if (request.getRequestURI().equals(pathURI)) { if (request.getRequestURI().equals(pathURI)) {
this.getNext().invoke(request, response, compositeValve); this.getNext().invoke(request, response, compositeValve);
return; return;
@ -68,8 +66,21 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve {
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
return; return;
} }
WebappAuthenticator.Status status = authenticator.authenticate(request, response); AuthenticationInfo authenticationInfo = authenticator.authenticate(request, response);
this.processResponse(request, response, compositeValve, status); if (authenticationInfo.getTenantId() != -1) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
privilegedCarbonContext.setTenantId(authenticationInfo.getTenantId());
privilegedCarbonContext.setTenantDomain(authenticationInfo.getTenantDomain());
privilegedCarbonContext.setUsername(authenticationInfo.getUsername());
this.processRequest(request, response, compositeValve, authenticationInfo.getStatus());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} else {
this.processRequest(request, response, compositeValve, authenticationInfo.getStatus());
}
} }
private boolean isAdminService(Request request) { private boolean isAdminService(Request request) {
@ -93,7 +104,7 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve {
} }
StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
if (!tokenizer.hasMoreTokens()) { if (!tokenizer.hasMoreTokens()) {
return false; return false;
} }
ctx = tokenizer.nextToken(); ctx = tokenizer.nextToken();
} }
@ -101,8 +112,8 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve {
return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services")); return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services"));
} }
private void processResponse(Request request, Response response, CompositeValve compositeValve, private void processRequest(Request request, Response response, CompositeValve compositeValve,
WebappAuthenticator.Status status) { WebappAuthenticator.Status status) {
switch (status) { switch (status) {
case SUCCESS: case SUCCESS:
case CONTINUE: case CONTINUE:
@ -111,7 +122,9 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve {
case FAILURE: case FAILURE:
String msg = "Failed to authorize incoming request"; String msg = "Failed to authorize incoming request";
log.error(msg); log.error(msg);
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); AuthenticationFrameworkUtil
.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED,
msg);
break; break;
} }
} }

@ -26,12 +26,12 @@ import java.util.Map;
public class WebappAuthenticatorFactory { public class WebappAuthenticatorFactory {
public static WebappAuthenticator getAuthenticator(String authScheme) { public static WebappAuthenticator getAuthenticator(String authScheme) {
return DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme); return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme);
} }
public static WebappAuthenticator getAuthenticator(Request request) { public static WebappAuthenticator getAuthenticator(Request request) {
Map<String, WebappAuthenticator> authenticators = Map<String, WebappAuthenticator> authenticators =
DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators();
for (WebappAuthenticator authenticator : authenticators.values()) { for (WebappAuthenticator authenticator : authenticators.values()) {
if (authenticator.canHandle(request)) { if (authenticator.canHandle(request)) {
return authenticator; return authenticator;

@ -1,71 +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.webapp.authenticator.framework;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve;
import org.wso2.carbon.tomcat.ext.valves.CompositeValve;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator;
import javax.servlet.http.HttpServletResponse;
public class WebappAuthenticatorFrameworkValve extends CarbonTomcatValve {
private static final String AUTHENTICATION_SCHEME = "authentication-scheme";
private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkValve.class);
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {
String authScheme = request.getContext().findParameter(WebappAuthenticatorFrameworkValve.AUTHENTICATION_SCHEME);
if (authScheme == null || authScheme.isEmpty()) {
this.getNext().invoke(request, response, compositeValve);
return;
}
WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(authScheme);
if (authenticator == null) {
String msg = "Failed to load an appropriate authenticator to authenticate the request";
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
return;
}
WebappAuthenticator.Status status = authenticator.authenticate(request, response);
this.processResponse(request, response, compositeValve, status);
}
private void processResponse(Request request, Response response, CompositeValve compositeValve,
WebappAuthenticator.Status status) {
switch (status) {
case SUCCESS:
case CONTINUE:
this.getNext().invoke(request, response, compositeValve);
break;
case FAILURE:
String msg = "Failed to authorize incoming request";
log.error(msg);
AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg);
break;
}
}
}

@ -25,6 +25,7 @@ import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Constants;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
public class BasicAuthAuthenticator implements WebappAuthenticator { public class BasicAuthAuthenticator implements WebappAuthenticator {
@ -45,8 +46,8 @@ public class BasicAuthAuthenticator implements WebappAuthenticator {
} }
@Override @Override
public Status authenticate(Request request, Response response) { public AuthenticationInfo authenticate(Request request, Response response) {
return Status.CONTINUE; return new AuthenticationInfo();
} }
@Override @Override

@ -5,13 +5,13 @@ 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.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.scep.SCEPException; import org.wso2.carbon.device.mgt.core.scep.SCEPException;
import org.wso2.carbon.device.mgt.core.scep.SCEPManager; import org.wso2.carbon.device.mgt.core.scep.SCEPManager;
import org.wso2.carbon.device.mgt.core.scep.TenantedDeviceWrapper; import org.wso2.carbon.device.mgt.core.scep.TenantedDeviceWrapper;
import org.wso2.carbon.webapp.authenticator.framework.DataHolder; import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
@ -27,56 +27,47 @@ public class CertificateAuthenticator implements WebappAuthenticator {
@Override @Override
public boolean canHandle(Request request) { public boolean canHandle(Request request) {
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) { if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) {
String certHeader = request.getHeader(certVerificationHeader); String certHeader = request.getHeader(certVerificationHeader);
return certHeader != null; return certHeader != null;
} }
return false; return false;
} }
@Override @Override
public Status authenticate(Request request, Response response) { public AuthenticationInfo authenticate(Request request, Response response) {
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
String requestUri = request.getRequestURI(); String requestUri = request.getRequestURI();
if (requestUri == null || requestUri.isEmpty()) { if (requestUri == null || requestUri.isEmpty()) {
return Status.CONTINUE; authenticationInfo.setStatus(Status.CONTINUE);
} }
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
try { try {
if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) { if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) {
String certHeader = request.getHeader(certVerificationHeader); String certHeader = request.getHeader(certVerificationHeader);
if (certHeader != null &&
AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService().
verifySignature(certHeader)) {
if (certHeader != null && DataHolder.getInstance().getCertificateManagementService(). X509Certificate certificate =
verifySignature(certHeader)) { AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService().
extractCertificateFromSignature(certHeader);
X509Certificate certificate = DataHolder.getInstance().getCertificateManagementService(). String challengeToken = AuthenticatorFrameworkDataHolder.getInstance().
extractCertificateFromSignature(certHeader); getCertificateManagementService().extractChallengeToken(certificate);
String challengeToken = DataHolder.getInstance().getCertificateManagementService().
extractChallengeToken(certificate);
if(challengeToken != null) {
if (challengeToken != null) {
challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim(); challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim();
SCEPManager scepManager = AuthenticatorFrameworkDataHolder.getInstance().getScepManager();
SCEPManager scepManager = DataHolder.getInstance().getScepManager();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(challengeToken); deviceIdentifier.setId(challengeToken);
deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS); deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier); TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier);
authenticationInfo.setTenantDomain(tenantedDeviceWrapper.getTenantDomain());
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); authenticationInfo.setTenantId(tenantedDeviceWrapper.getTenantId());
ctx.setTenantId(tenantedDeviceWrapper.getTenantId()); authenticationInfo.setStatus(Status.CONTINUE);
ctx.setTenantDomain(tenantedDeviceWrapper.getTenantDomain());
return Status.SUCCESS;
} }
} }
} }
@ -85,8 +76,7 @@ public class CertificateAuthenticator implements WebappAuthenticator {
} catch (SCEPException e) { } catch (SCEPException e) {
log.error("SCEPException occurred ", e); log.error("SCEPException occurred ", e);
} }
return authenticationInfo;
return Status.FAILURE;
} }
@Override @Override

@ -28,14 +28,14 @@ import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response; 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.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.core.util.KeyStoreManager;
import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.carbon.webapp.authenticator.framework.DataHolder; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder;
import java.security.interfaces.RSAPublicKey; import java.security.interfaces.RSAPublicKey;
import java.text.ParseException; import java.text.ParseException;
@ -49,26 +49,28 @@ public class JWTAuthenticator implements WebappAuthenticator {
private static final Log log = LogFactory.getLog(JWTAuthenticator.class); private static final Log log = LogFactory.getLog(JWTAuthenticator.class);
public static final String SIGNED_JWT_AUTH_USERNAME = "Username"; public static final String SIGNED_JWT_AUTH_USERNAME = "Username";
private static final String JWT_AUTHENTICATOR = "JWT"; private static final String JWT_AUTHENTICATOR = "JWT";
private static final String JWT_ASSERTION_HEADER = "X-JWT-Assertion";
@Override @Override
public boolean canHandle(Request request) { public boolean canHandle(Request request) {
String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER);
if(decodeAuthorizationHeader(authorizationHeader) != null){ if((authorizationHeader != null) && !authorizationHeader.isEmpty()){
return true; return true;
} }
return false; return false;
} }
@Override @Override
public Status authenticate(Request request, Response response) { public AuthenticationInfo authenticate(Request request, Response response) {
String requestUri = request.getRequestURI(); String requestUri = request.getRequestURI();
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
if (requestUri == null || "".equals(requestUri)) { if (requestUri == null || "".equals(requestUri)) {
return Status.CONTINUE; authenticationInfo.setStatus(Status.CONTINUE);
} }
StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
String context = tokenizer.nextToken(); String context = tokenizer.nextToken();
if (context == null || "".equals(context)) { if (context == null || "".equals(context)) {
return Status.CONTINUE; authenticationInfo.setStatus(Status.CONTINUE);
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -76,8 +78,7 @@ public class JWTAuthenticator implements WebappAuthenticator {
} }
//Get the filesystem keystore default primary certificate //Get the filesystem keystore default primary certificate
KeyStoreManager keyStoreManager = KeyStoreManager.getInstance( KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
MultitenantConstants.SUPER_TENANT_ID);
try { try {
keyStoreManager.getDefaultPrimaryCertificate(); keyStoreManager.getDefaultPrimaryCertificate();
String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
@ -89,38 +90,33 @@ public class JWTAuthenticator implements WebappAuthenticator {
String username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); String username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME);
String tenantDomain = MultitenantUtils.getTenantDomain(username); String tenantDomain = MultitenantUtils.getTenantDomain(username);
username = MultitenantUtils.getTenantAwareUsername(username); username = MultitenantUtils.getTenantAwareUsername(username);
TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager(); TenantManager tenantManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService().
getTenantManager();
int tenantId = tenantManager.getTenantId(tenantDomain); int tenantId = tenantManager.getTenantId(tenantDomain);
if (tenantId == -1) { if (tenantId == -1) {
log.error("tenantDomain is not valid. username : " + username + ", tenantDomain " + log.error("tenantDomain is not valid. username : " + username + ", tenantDomain " +
": " + tenantDomain); ": " + tenantDomain);
return Status.FAILURE; } else {
} UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService().
getTenantUserRealm(tenantId).getUserStoreManager();
UserStoreManager userStore = DataHolder.getInstance().getRealmService(). if (userStore.isExistingUser(username)) {
getTenantUserRealm(tenantId).getUserStoreManager(); authenticationInfo.setTenantId(tenantId);
if (userStore.isExistingUser(username)) { authenticationInfo.setUsername(username);
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); authenticationInfo.setTenantDomain(tenantDomain);
ctx.setTenantId(tenantId); authenticationInfo.setStatus(Status.CONTINUE);
ctx.setUsername(username); }
return Status.SUCCESS; }
} }
}
} catch (UserStoreException e) { } catch (UserStoreException e) {
log.error("Error occurred while obtaining the user.", e); log.error("Error occurred while obtaining the user.", e);
return Status.FAILURE;
} catch (ParseException e) { } catch (ParseException e) {
log.error("Error occurred while parsing the JWT header.", e); log.error("Error occurred while parsing the JWT header.", e);
return Status.FAILURE;
} catch (JOSEException e) { } catch (JOSEException e) {
log.error("Error occurred while verifying the JWT header.", e); log.error("Error occurred while verifying the JWT header.", e);
return Status.FAILURE;
} catch (Exception e) { } catch (Exception e) {
log.error("Error occurred while verifying the JWT header.", e); log.error("Error occurred while verifying the JWT header.", e);
return Status.FAILURE;
} }
return Status.CONTINUE; return authenticationInfo;
} }
private String decodeAuthorizationHeader(String authorizationHeader) { private String decodeAuthorizationHeader(String authorizationHeader) {

@ -25,16 +25,12 @@ 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.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.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 org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; import org.wso2.carbon.webapp.authenticator.framework.*;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
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;
@ -55,8 +51,7 @@ public class OAuthAuthenticator implements WebappAuthenticator {
@Override @Override
public boolean canHandle(Request request) { public boolean canHandle(Request request) {
MessageBytes authorization = MessageBytes authorization =
request.getCoyoteRequest().getMimeHeaders(). request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
String tokenValue; String tokenValue;
if (authorization != null) { if (authorization != null) {
authorization.toBytes(); authorization.toBytes();
@ -71,35 +66,34 @@ public class OAuthAuthenticator implements WebappAuthenticator {
} }
@Override @Override
public Status authenticate(Request request, Response response) { public AuthenticationInfo authenticate(Request request, Response response) {
String requestUri = request.getRequestURI(); String requestUri = request.getRequestURI();
String requestMethod = request.getMethod(); String requestMethod = request.getMethod();
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
if (requestUri == null || "".equals(requestUri)) { if (requestUri == null || "".equals(requestUri)) {
return Status.CONTINUE; authenticationInfo.setStatus(Status.CONTINUE);
return authenticationInfo;
} }
StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
String context = tokenizer.nextToken(); String context = tokenizer.nextToken();
if (context == null || "".equals(context)) { if (context == null || "".equals(context)) {
return Status.CONTINUE; authenticationInfo.setStatus(Status.CONTINUE);
} }
String apiVersion = tokenizer.nextToken(); String apiVersion = tokenizer.nextToken();
String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, requestUri, requestMethod);
requestUri, //String authLevel = "any";
requestMethod);
try { try {
if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) { if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) {
AuthenticationFrameworkUtil AuthenticationFrameworkUtil.handleNoMatchAuthScheme(request, response, requestMethod, apiVersion,
.handleNoMatchAuthScheme(request, response, requestMethod, context);
apiVersion, context); authenticationInfo.setStatus(Status.CONTINUE);
return Status.CONTINUE;
} else { } else {
String bearerToken = this.getBearerToken(request); String bearerToken = this.getBearerToken(request);
// Create a OAuth2TokenValidationRequestDTO object for validating access token // Create a OAuth2TokenValidationRequestDTO object for validating access token
OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
//Set the access token info //Set the access token info
OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken = OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken = dto.new OAuth2AccessToken();
dto.new OAuth2AccessToken();
oAuth2AccessToken.setTokenType(OAuthAuthenticator.BEARER_TOKEN_TYPE); oAuth2AccessToken.setTokenType(OAuthAuthenticator.BEARER_TOKEN_TYPE);
oAuth2AccessToken.setIdentifier(bearerToken); oAuth2AccessToken.setIdentifier(bearerToken);
dto.setAccessToken(oAuth2AccessToken); dto.setAccessToken(oAuth2AccessToken);
@ -109,36 +103,32 @@ public class OAuthAuthenticator implements WebappAuthenticator {
resourceContextParam.setKey(OAuthAuthenticator.RESOURCE_KEY); resourceContextParam.setKey(OAuthAuthenticator.RESOURCE_KEY);
resourceContextParam.setValue(requestUri + ":" + requestMethod); resourceContextParam.setValue(requestUri + ":" + requestMethod);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam [] OAuth2TokenValidationRequestDTO.TokenValidationContextParam[]
tokenValidationContextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1]; tokenValidationContextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
tokenValidationContextParams[0] = resourceContextParam; tokenValidationContextParams[0] = resourceContextParam;
dto.setContext(tokenValidationContextParams); dto.setContext(tokenValidationContextParams);
OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO =
DataHolder.getInstance(). AuthenticatorFrameworkDataHolder.getInstance().getoAuth2TokenValidationService().validate(dto);
getoAuth2TokenValidationService().validate(dto);
if (oAuth2TokenValidationResponseDTO.isValid()) { if (oAuth2TokenValidationResponseDTO.isValid()) {
String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser(); String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser();
try { try {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( authenticationInfo.setUsername(username);
IdentityUtil.getTenantIdOFUser(username)); authenticationInfo.setTenantDomain(MultitenantUtils.getTenantDomain(username));
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); authenticationInfo.setTenantId(IdentityUtil.getTenantIdOFUser(username));
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
MultitenantUtils.getTenantDomain(username));
} catch (IdentityException e) { } catch (IdentityException e) {
throw new AuthenticationException( throw new AuthenticationException(
"Error occurred while retrieving the tenant ID of user '" + "Error occurred while retrieving the tenant ID of user '" + username + "'", e);
username + "'", e); }
if (oAuth2TokenValidationResponseDTO.isValid()) {
authenticationInfo.setStatus(Status.CONTINUE);
} }
boolean isAuthenticated = oAuth2TokenValidationResponseDTO.isValid();
return (isAuthenticated) ? Status.SUCCESS : 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 authenticationInfo;
} }
@Override @Override

@ -20,6 +20,7 @@ package org.wso2.carbon.webapp.authenticator.framework.authenticator;
import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response; import org.apache.catalina.connector.Response;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
public interface WebappAuthenticator { public interface WebappAuthenticator {
@ -29,7 +30,7 @@ public interface WebappAuthenticator {
boolean canHandle(Request request); boolean canHandle(Request request);
Status authenticate(Request request, Response response); AuthenticationInfo authenticate(Request request, Response response);
String getName(); String getName();

@ -38,14 +38,13 @@ public class PermissionAuthorizationValve extends CarbonTomcatValve {
@Override @Override
public void invoke(Request request, Response response, CompositeValve compositeValve) { public void invoke(Request request, Response response, CompositeValve compositeValve) {
String permissionStatus = String permissionStatus = request.getContext().findParameter(AUTHORIZATION_ENABLED);
request.getContext().findParameter(AUTHORIZATION_ENABLED);
if (permissionStatus == null || permissionStatus.isEmpty()) { if (permissionStatus == null || permissionStatus.isEmpty()) {
this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE);
return; return;
} }
// check whether the permission checking function is enabled in web.xml // check whether the permission checking function is enabled in web.xml
boolean isEnabled = new Boolean(permissionStatus); boolean isEnabled = Boolean.valueOf(permissionStatus);
if (!isEnabled) { if (!isEnabled) {
this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE);
return; return;

@ -44,13 +44,11 @@ public class PermissionAuthorizer {
String requestUri = request.getRequestURI(); String requestUri = request.getRequestURI();
String requestMethod = request.getMethod(); String requestMethod = request.getMethod();
if (requestUri == null || requestUri.isEmpty() || if (requestUri == null || requestUri.isEmpty() || requestMethod == null || requestMethod.isEmpty()) {
requestMethod == null || requestMethod.isEmpty()) {
return WebappAuthenticator.Status.CONTINUE; return WebappAuthenticator.Status.CONTINUE;
} }
PermissionManagerServiceImpl PermissionManagerServiceImpl registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance();
registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance();
Properties properties = new Properties(); Properties properties = new Properties();
properties.put("",requestUri); properties.put("",requestUri);
properties.put("",requestMethod); properties.put("",requestMethod);

@ -27,8 +27,8 @@ 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;
import org.wso2.carbon.webapp.authenticator.framework.DataHolder; import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder;
import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationValve;
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.config.AuthenticatorConfig; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig;
@ -77,15 +77,14 @@ public class WebappAuthenticatorFrameworkServiceComponent {
WebappAuthenticatorConfig.init(); WebappAuthenticatorConfig.init();
WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository(); WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository();
for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) {
WebappAuthenticator authenticator = WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()).
(WebappAuthenticator) Class.forName(config.getClassName()).newInstance(); newInstance();
repository.addAuthenticator(authenticator); repository.addAuthenticator(authenticator);
} }
DataHolder.getInstance().setWebappAuthenticatorRepository(repository); AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository);
List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>(); List<CarbonTomcatValve> valves = new ArrayList<CarbonTomcatValve>();
valves.add(new WebappAuthenticationHandler()); valves.add(new WebappAuthenticationValve());
//valves.add(new PermissionAuthorizationValve());
TomcatValveContainer.addValves(valves); TomcatValveContainer.addValves(valves);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -105,18 +104,18 @@ public class WebappAuthenticatorFrameworkServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("RealmService acquired"); log.debug("RealmService acquired");
} }
DataHolder.getInstance().setRealmService(realmService); AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService);
} }
protected void unsetRealmService(RealmService realmService) { protected void unsetRealmService(RealmService realmService) {
DataHolder.getInstance().setRealmService(null); AuthenticatorFrameworkDataHolder.getInstance().setRealmService(null);
} }
protected void setCertificateManagementService(CertificateManagementService certificateManagementService) { protected void setCertificateManagementService(CertificateManagementService certificateManagementService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting certificate management service"); log.debug("Setting certificate management service");
} }
DataHolder.getInstance().setCertificateManagementService(certificateManagementService); AuthenticatorFrameworkDataHolder.getInstance().setCertificateManagementService(certificateManagementService);
} }
protected void unsetCertificateManagementService(CertificateManagementService certificateManagementService) { protected void unsetCertificateManagementService(CertificateManagementService certificateManagementService) {
@ -124,14 +123,14 @@ public class WebappAuthenticatorFrameworkServiceComponent {
log.debug("Removing certificate management service"); log.debug("Removing certificate management service");
} }
DataHolder.getInstance().setCertificateManagementService(null); AuthenticatorFrameworkDataHolder.getInstance().setCertificateManagementService(null);
} }
protected void setSCEPManagementService(SCEPManager scepManager) { protected void setSCEPManagementService(SCEPManager scepManager) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting SCEP management service"); log.debug("Setting SCEP management service");
} }
DataHolder.getInstance().setScepManager(scepManager); AuthenticatorFrameworkDataHolder.getInstance().setScepManager(scepManager);
} }
protected void unsetSCEPManagementService(SCEPManager scepManager) { protected void unsetSCEPManagementService(SCEPManager scepManager) {
@ -139,7 +138,7 @@ public class WebappAuthenticatorFrameworkServiceComponent {
log.debug("Removing SCEP management service"); log.debug("Removing SCEP management service");
} }
DataHolder.getInstance().setScepManager(null); AuthenticatorFrameworkDataHolder.getInstance().setScepManager(null);
} }
/** /**
@ -151,7 +150,7 @@ public class WebappAuthenticatorFrameworkServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting OAuth2TokenValidationService Service"); log.debug("Setting OAuth2TokenValidationService Service");
} }
DataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService); AuthenticatorFrameworkDataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService);
} }
/** /**
@ -163,6 +162,6 @@ public class WebappAuthenticatorFrameworkServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Unsetting OAuth2TokenValidationService Service"); log.debug("Unsetting OAuth2TokenValidationService Service");
} }
DataHolder.getInstance().setoAuth2TokenValidationService(null); AuthenticatorFrameworkDataHolder.getInstance().setoAuth2TokenValidationService(null);
} }
} }

@ -124,6 +124,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE (
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,

@ -152,10 +152,6 @@
<groupId>org.eclipse.osgi</groupId> <groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId> <artifactId>org.eclipse.osgi</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -316,6 +312,10 @@
<groupId>commons-pool.wso2</groupId> <groupId>commons-pool.wso2</groupId>
<artifactId>commons-pool</artifactId> <artifactId>commons-pool</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -390,6 +390,10 @@
<groupId>org.wso2.carbon.registry</groupId> <groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.extensions</artifactId> <artifactId>org.wso2.carbon.registry.extensions</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- End of Governance dependencies --> <!-- End of Governance dependencies -->
@ -410,6 +414,11 @@
<artifactId>org.eclipse.osgi.services</artifactId> <artifactId>org.eclipse.osgi.services</artifactId>
<version>3.3.100.v20120522-1822</version> <version>3.3.100.v20120522-1822</version>
</dependency> </dependency>
<dependency>
<groupId>org.osgi.ut</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<version>3.3.100.v20120522-1822</version>
</dependency>
<!-- End of OSGi dependencies --> <!-- End of OSGi dependencies -->
<dependency> <dependency>
@ -807,6 +816,10 @@
<groupId>org.wso2.carbon.registry</groupId> <groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.ws.client</artifactId> <artifactId>org.wso2.carbon.registry.ws.client</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -941,6 +954,21 @@
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId> <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
<version>${carbon.identity.version}</version> <version>${carbon.identity.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
<version>${carbon.identity.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
<version>${carbon.identity.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.application.common</artifactId>
<version>${carbon.identity.version}</version>
</dependency>
<!-- End of Carbon Identity dependencies --> <!-- End of Carbon Identity dependencies -->
<!-- CXF dependencies --> <!-- CXF dependencies -->
@ -1126,11 +1154,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
<version>${carbon.identity.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.identity</groupId> <groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.sso.saml</artifactId> <artifactId>org.wso2.carbon.identity.sso.saml</artifactId>

Loading…
Cancel
Save