Refactored dynamic client code & add tenancy handling to authenticators

revert-70aa11f8
harshanl 9 years ago
parent d2df5a749a
commit b0d6038b69

@ -26,11 +26,8 @@ import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationServ
*/ */
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;
} }
} }

@ -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);
} }

@ -38,12 +38,13 @@ import org.wso2.carbon.identity.sso.saml.admin.SAMLSSOConfigAdmin;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO;
import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.Arrays; 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";
@ -54,12 +55,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
private static final String ASSERTION_CONSUMER_URI = "https://localhost:9443/mdm/sso/acs"; 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 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;
@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 +77,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 +96,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 +113,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.
@ -152,27 +151,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 = DynamicClientRegistrationDataHolder. getApplicationManagementService();
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, tenantDomain, userName); 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);
@ -187,8 +181,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
log.debug("Creating OAuth App " + applicationName); log.debug("Creating OAuth App " + applicationName);
} }
if ((existingServiceProvider == null) || (existingServiceProvider. if ((existingServiceProvider == null) || (existingServiceProvider.getInboundAuthenticationConfig().
getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs().length == 0)) { getInboundAuthenticationRequestConfigs().length == 0)) {
oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp);
} }
@ -210,14 +204,13 @@ 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);
} }
@ -225,7 +218,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
samlssoServiceProviderDTO.setIssuer(MDM); samlssoServiceProviderDTO.setIssuer(MDM);
samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI); samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI);
samlssoServiceProviderDTO.setDoSignResponse(true); samlssoServiceProviderDTO.setDoSignResponse(true);
samlssoServiceProviderDTO.setRequestedAudiences(new String[]{AUDIENCE}); samlssoServiceProviderDTO.setRequestedAudiences(new String[] { AUDIENCE });
SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry()); SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry());
configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO); configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO);
@ -240,15 +233,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;
@ -263,15 +256,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) {
@ -287,20 +278,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();
@ -312,9 +302,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);
} }
@ -325,17 +315,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS
try { try {
oAuthAdminService.removeOAuthApplicationData(consumerKey); oAuthAdminService.removeOAuthApplicationData(consumerKey);
ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance().
ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. getApplicationManagementService();
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);
@ -346,38 +334,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 = DynamicClientRegistrationDataHolder. ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance().
getInstance().getApplicationManagementService(); 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 (appMgtService.getServiceProvider(applicationName, return appMgtService.getServiceProvider(applicationName,
CarbonContext.getThreadLocalCarbonContext() CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) !=
.getTenantDomain()) != null) { null;
return true;
}
} 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;
} }
} }

@ -45,7 +45,7 @@ public class DynamicClientRegistrationDataHolder {
return applicationManagementService; return applicationManagementService;
} }
public void setApplicationManagementService(ApplicationManagementService realmService) { public void setApplicationManagementService(ApplicationManagementService applicationManagementService) {
this.applicationManagementService = realmService; this.applicationManagementService = applicationManagementService;
} }
} }

@ -20,9 +20,10 @@ package org.wso2.carbon.dynamic.client.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.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService;
import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationServiceImpl;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
/** /**
@ -44,9 +45,9 @@ public class DynamicClientRegistrationServiceComponent {
log.debug("Starting DynamicClientRegistrationServiceComponent"); log.debug("Starting DynamicClientRegistrationServiceComponent");
} }
DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientRegistrationService dynamicClientRegistrationService =
new DynamicClientRegistrationImpl(); new DynamicClientRegistrationServiceImpl();
componentContext.getBundleContext().registerService(DynamicClientRegistrationService.class.getName(), componentContext.getBundleContext().registerService(
dynamicClientRegistrationService, null); DynamicClientRegistrationService.class.getName(), dynamicClientRegistrationService, null);
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

@ -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,11 +41,9 @@ import java.util.*;
public class DynamicClientWebAppRegistrationManager { public class DynamicClientWebAppRegistrationManager {
private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager;
private static List<RegistrationProfile> registrationProfileList = new ArrayList<>();
private static Map<String, ServletContext> webAppContexts = new HashMap<>(); private static Map<String, ServletContext> webAppContexts = new HashMap<>();
private static final Log log = private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class);
LogFactory.getLog(DynamicClientWebAppRegistrationManager.class);
private DynamicClientWebAppRegistrationManager() { private DynamicClientWebAppRegistrationManager() {
} }
@ -64,17 +62,14 @@ public class DynamicClientWebAppRegistrationManager {
public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) { public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Registering OAuth application for web app : " + log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName());
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(); OAuthAppDetails oAuthAppDetails = new OAuthAppDetails();
oAuthAppDetails.setWebAppName(registrationProfile.getClientName()); oAuthAppDetails.setWebAppName(registrationProfile.getClientName());
oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName()); oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName());
@ -84,19 +79,17 @@ public class DynamicClientWebAppRegistrationManager {
if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) { if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) {
return oAuthAppDetails; return oAuthAppDetails;
} else { } else {
dynamicClientRegistrationService dynamicClientRegistrationService.unregisterOAuthApplication(registrationProfile.getOwner(),
.unregisterOAuthApplication(registrationProfile.getOwner(),
oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientName(),
oAuthApplicationInfo.getClientId()); oAuthApplicationInfo.getClientId());
log.warn( log.warn("Error occurred while persisting the OAuth application data in registry.");
"Error occurred while persisting the OAuth application data in registry.");
} }
} catch (DynamicClientRegistrationException e) { } catch (DynamicClientRegistrationException e) {
log.error("Error occurred while registering the OAuth application : " + log.error("Error occurred while registering the OAuth application : " +
registrationProfile.getClientName(), e); registrationProfile.getClientName(), e);
} }
} }
return new OAuthAppDetails(); return null;
} }
public OAuthAppDetails getOAuthApplicationData(String clientName) { public OAuthAppDetails getOAuthApplicationData(String clientName) {
@ -106,12 +99,13 @@ public class DynamicClientWebAppRegistrationManager {
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 OAuthAppDetails(); return null;
} }
public boolean isRegisteredOAuthApplication(String clientName) { public boolean isRegisteredOAuthApplication(String clientName) {
OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName); OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName);
if (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != null) { if (oAuthAppDetails != null && (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() !=
null)) {
return true; return true;
} }
return false; return false;
@ -119,66 +113,66 @@ public class DynamicClientWebAppRegistrationManager {
public void saveServletContextToCache(StandardContext context) { public void saveServletContextToCache(StandardContext context) {
DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(), DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(),
context.getServletContext()); context.getServletContext());
} }
public void initiateDynamicClientRegistration() { public void initiateDynamicClientRegistration() {
String requiredDynamicClientRegistration, webAppName; String requiredDynamicClientRegistration, webAppName;
ServletContext servletContext; ServletContext servletContext;
RegistrationProfile registrationProfile; RegistrationProfile registrationProfile;
OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); OAuthAppDetails oAuthAppDetails = null;
DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager =
DynamicClientWebAppRegistrationManager.getInstance(); DynamicClientWebAppRegistrationManager.getInstance();
//todo move enumeration to while loop
Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager. Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager.
webAppContexts.keySet().iterator()); webAppContexts.keySet().iterator());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Initiating the DynamicClientRegistration service for web-apps"); log.debug("Initiating the DynamicClientRegistration service for web-apps");
} }
while (enumeration.hasMoreElements()){ while (enumeration.hasMoreElements()) {
oAuthAppDetails = new OAuthAppDetails();
webAppName = (String) enumeration.nextElement(); webAppName = (String) enumeration.nextElement();
servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName); servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName);
requiredDynamicClientRegistration = servletContext.getInitParameter( requiredDynamicClientRegistration = servletContext.getInitParameter(
DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG);
//Java web-app section //Java web-app section
if ((requiredDynamicClientRegistration != null) && if ((requiredDynamicClientRegistration != null) && (Boolean.
(Boolean.parseBoolean(requiredDynamicClientRegistration))) { parseBoolean(
requiredDynamicClientRegistration))) {
//Check whether this is an already registered application //Check whether this is an already registered application
if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
//Construct the RegistrationProfile //Construct the RegistrationProfile
registrationProfile = DynamicClientWebAppRegistrationUtil. registrationProfile = DynamicClientWebAppRegistrationUtil.
constructRegistrationProfile(servletContext, constructRegistrationProfile(servletContext, webAppName);
webAppName);
//Register the OAuth application //Register the OAuth application
oAuthAppDetails = dynamicClientWebAppRegistrationManager.registerOAuthApplication( oAuthAppDetails =
registrationProfile); dynamicClientWebAppRegistrationManager.registerOAuthApplication(registrationProfile);
} else { } else {
oAuthAppDetails = oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
} }
} else if (requiredDynamicClientRegistration == null) { } else if (requiredDynamicClientRegistration == null) {
//Jaggery apps //Jaggery apps
JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = DynamicClientWebAppRegistrationUtil JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings =
.getJaggeryAppOAuthSettings(servletContext); DynamicClientWebAppRegistrationUtil.getJaggeryAppOAuthSettings(servletContext);
if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) { if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) {
if (!dynamicClientWebAppRegistrationManager if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) {
.isRegisteredOAuthApplication(webAppName)) { registrationProfile = DynamicClientWebAppRegistrationUtil.
registrationProfile = DynamicClientWebAppRegistrationUtil constructRegistrationProfile(jaggeryOAuthConfigurationSettings,
.constructRegistrationProfile(jaggeryOAuthConfigurationSettings, webAppName); webAppName);
oAuthAppDetails = dynamicClientWebAppRegistrationManager oAuthAppDetails = dynamicClientWebAppRegistrationManager.
.registerOAuthApplication(registrationProfile); registerOAuthApplication(registrationProfile);
} else { } else {
oAuthAppDetails = dynamicClientWebAppRegistrationManager oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName);
.getOAuthApplicationData(webAppName);
} }
} }
} }
//Add client credentials to the web-context //Add client credentials to the web-context
if (oAuthAppDetails.getClientKey() != null) { if ((oAuthAppDetails != null && oAuthAppDetails.getClientKey() != null) && !oAuthAppDetails.getClientKey().isEmpty()) {
DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails, DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails,
servletContext); servletContext);
log.info("Added OAuth application credentials to webapp context of webapp : " + webAppName); log.info("Added OAuth application credentials to webapp context of webapp : " +
webAppName);
} }
} }
} }

@ -22,7 +22,7 @@ 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 JaggeryOAuthConfigurationSettings { public class JaggeryOAuthConfigurationSettings {

@ -22,7 +22,7 @@ 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 = "OAuthAppDetails") @XmlRootElement(name = "OAuthAppDetails")
public class OAuthAppDetails { public class OAuthAppDetails {

@ -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");

@ -58,114 +58,119 @@ import org.wso2.carbon.utils.ConfigurationContextService;
*/ */
public class DynamicClientWebAppRegistrationServiceComponent { public class DynamicClientWebAppRegistrationServiceComponent {
private ServiceTracker serviceTracker; private static Log log =
private static Log log = LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class);
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) { protected void activate(ComponentContext componentContext) {
componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(), componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(),
new WebAppRegistrationServerStartupObserver(), null) ; new WebAppRegistrationServerStartupObserver(), null);
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) { protected void deactivate(ComponentContext componentContext) {
} }
/** /**
* Sets Realm Service. * Sets Realm Service.
* *
* @param realmService An instance of RealmService * @param realmService An instance of RealmService
*/ */
protected void setRealmService(RealmService realmService) { protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Realm Service"); log.debug("Setting Realm Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService);
} }
/** /**
* Unsets Realm Service. * Unsets Realm Service.
* *
* @param realmService An instance of RealmService * @param realmService An instance of RealmService
*/ */
protected void unsetRealmService(RealmService realmService) { protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Unsetting Realm Service"); log.debug("Unsetting Realm Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null);
} }
/** /**
* Sets Registry Service. * Sets Registry Service.
* *
* @param registryService An instance of RegistryService * @param registryService An instance of RegistryService
*/ */
protected void setRegistryService(RegistryService registryService) { protected void setRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Registry Service"); log.debug("Setting Registry Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService);
} }
/** /**
* Unsets Registry Service. * Unsets Registry Service.
* *
* @param registryService An instance of RegistryService * @param registryService An instance of RegistryService
*/ */
protected void unsetRegistryService(RegistryService registryService) { protected void unsetRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Un setting Registry Service"); log.debug("Un setting Registry Service");
} }
DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null);
} }
/** /**
* Sets Dynamic Client Registration Service. * Sets Dynamic Client Registration Service.
* *
* @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService
*/ */
protected void setDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { protected void setDynamicClientService(
if (log.isDebugEnabled()) { DynamicClientRegistrationService dynamicClientRegistrationService) {
log.debug("Setting Dynamic Client Registration Service"); if (log.isDebugEnabled()) {
} log.debug("Setting Dynamic Client Registration Service");
DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( }
dynamicClientRegistrationService); DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(
} dynamicClientRegistrationService);
}
/** /**
* Unsets Dynamic Client Registration Service. * Unsets Dynamic Client Registration Service.
* *
* @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService
*/ */
protected void unsetDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { protected void unsetDynamicClientService(
if (log.isDebugEnabled()) { DynamicClientRegistrationService dynamicClientRegistrationService) {
log.debug("Un setting Dynamic Client Registration Service"); if (log.isDebugEnabled()) {
} log.debug("Un setting Dynamic Client Registration Service");
DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); }
} DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null);
}
/** /**
* Sets ConfigurationContext Service. * Sets ConfigurationContext Service.
* *
* @param configurationContextService An instance of ConfigurationContextService * @param configurationContextService An instance of ConfigurationContextService
*/ */
protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { protected void setConfigurationContextService(
if (log.isDebugEnabled()) { ConfigurationContextService configurationContextService) {
log.debug("Setting ConfigurationContextService"); if (log.isDebugEnabled()) {
} log.debug("Setting ConfigurationContextService");
DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService); }
} DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(
configurationContextService);
}
/** /**
* Unsets ConfigurationContext Service. * Unsets ConfigurationContext Service.
* *
* @param configurationContextService An instance of ConfigurationContextService * @param configurationContextService An instance of ConfigurationContextService
*/ */
protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { protected void unsetConfigurationContextService(
if (log.isDebugEnabled()) { ConfigurationContextService configurationContextService) {
log.debug("Un-setting ConfigurationContextService"); if (log.isDebugEnabled()) {
} log.debug("Un-setting ConfigurationContextService");
DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); }
} 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().saveServletContextToCache( DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache(context);
context);
} }
} }
} }

@ -62,9 +62,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: " +
@ -75,8 +74,7 @@ public class DynamicClientWebAppRegistrationUtil {
public static OAuthAppDetails 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");
@ -86,9 +84,8 @@ public class DynamicClientWebAppRegistrationUtil {
JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class); JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class);
Unmarshaller unmarshaller = context.createUnmarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller();
return (OAuthAppDetails) 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 OAuthAppDetails(); return new OAuthAppDetails();
} catch (JAXBException e) { } catch (JAXBException e) {
@ -96,13 +93,12 @@ public class DynamicClientWebAppRegistrationUtil {
"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(OAuthAppDetails oAuthAppDetails) public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws
throws DynamicClientRegistrationException { DynamicClientRegistrationException {
boolean status; boolean status;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -113,15 +109,12 @@ public class DynamicClientWebAppRegistrationUtil {
Marshaller marshaller = context.createMarshaller(); Marshaller marshaller = context.createMarshaller();
marshaller.marshal(oAuthAppDetails, 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(); oAuthAppDetails.getWebAppName();
status = status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource);
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 : " +
@ -134,53 +127,42 @@ public class DynamicClientWebAppRegistrationUtil {
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,18 +175,16 @@ 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
JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings, String webAppName) { jaggeryOAuthConfigurationSettings, String webAppName) {
RegistrationProfile registrationProfile = new RegistrationProfile(); RegistrationProfile registrationProfile = new RegistrationProfile();
if (jaggeryOAuthConfigurationSettings != null) { if (jaggeryOAuthConfigurationSettings != null) {
registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType()); registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType());
@ -215,18 +195,17 @@ public class DynamicClientWebAppRegistrationUtil {
if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) { if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) {
registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL()); 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 " +
@ -241,14 +220,11 @@ public class DynamicClientWebAppRegistrationUtil {
} }
public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) {
JaggeryOAuthConfigurationSettings JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new 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();
@ -307,7 +283,7 @@ public class DynamicClientWebAppRegistrationUtil {
public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails, public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails,
ServletContext servletContext) { ServletContext servletContext) {
if(oAuthAppDetails != null){ if (oAuthAppDetails != null) {
//Check for client credentials //Check for client credentials
if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) && if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) &&
(oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) { (oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) {

@ -46,6 +46,7 @@ public class PermissionBasedScopeValidator 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";
@ -70,12 +71,13 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator {
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) {

@ -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);
} }
} }

Loading…
Cancel
Save