Partial commit for APIM Gateway migration

revert-70aa11f8
mharindu 9 years ago
parent fe447f4325
commit 66ccad65cf

@ -47,7 +47,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
public Response register(@PathParam("tenantDomain") String tenantDomain, public Response register(@PathParam("tenantDomain") String tenantDomain,
@QueryParam("applicationName") String applicationName) { @QueryParam("applicationName") String applicationName) {
String authenticatedTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String authenticatedTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (authenticatedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { if (!authenticatedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
return Response.status(Response.Status.NOT_ACCEPTABLE).build(); return Response.status(Response.Status.NOT_ACCEPTABLE).build();
} }
try { try {

@ -2,7 +2,7 @@
"appContext" : "/devicemgt/", "appContext" : "/devicemgt/",
"webAgentContext" : "/devicemgt-web-agent/", "webAgentContext" : "/devicemgt-web-agent/",
"apiContext" : "api", "apiContext" : "api",
"httpsURL" : "%https.ip%", "httpsURL" : "https://localhost:8243",
"httpURL" : "%http.ip%", "httpURL" : "%http.ip%",
"enrollmentDir": "/emm-web-agent/enrollment", "enrollmentDir": "/emm-web-agent/enrollment",
"iOSConfigRoot" : "%https.ip%/ios-enrollment/", "iOSConfigRoot" : "%https.ip%/ios-enrollment/",

@ -21,6 +21,7 @@ var apiWrapperUtil = function () {
var tokenUtil = require("/app/modules/util.js").util; var tokenUtil = require("/app/modules/util.js").util;
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var log = new Log("/app/modules/api-wrapper-util.js");
module.refreshToken = function () { module.refreshToken = function () {
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
@ -31,6 +32,10 @@ var apiWrapperUtil = function () {
module.setupAccessTokenPair = function (type, properties) { module.setupAccessTokenPair = function (type, properties) {
var tokenPair; var tokenPair;
var clientData = tokenUtil.getDyanmicCredentials(properties); var clientData = tokenUtil.getDyanmicCredentials(properties);
log.info(">>>>>>>>>>>>>>>>>>>>");
var jwtToken = tokenUtil.getTokenWithJWTGrantType(clientData);
tokenUtil.getTenantBasedAppCredentials(jwtToken);
log.info("*******************");
var encodedClientKeys = tokenUtil.encode(clientData.clientId + ":" + clientData.clientSecret); var encodedClientKeys = tokenUtil.encode(clientData.clientId + ":" + clientData.clientSecret);
session.put(constants.ENCODED_CLIENT_KEYS_IDENTIFIER, encodedClientKeys); session.put(constants.ENCODED_CLIENT_KEYS_IDENTIFIER, encodedClientKeys);
if (type == constants.GRANT_TYPE_PASSWORD) { if (type == constants.GRANT_TYPE_PASSWORD) {

@ -35,7 +35,7 @@ var onFail;
} }
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var carbonServer = require("carbon").server; var carbonServer = require("carbon").server;
(new carbonServer.Server({url: devicemgtProps["httpsURL"]})) (new carbonServer.Server({url: devicemgtProps["adminService"]}))
.login(context.input.username, context.input.password); .login(context.input.username, context.input.password);
}; };

@ -23,16 +23,15 @@ var util = function () {
var String = Packages.java.lang.String; var String = Packages.java.lang.String;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var carbon = require('carbon'); var carbon = require('carbon');
var realmService = carbon.server.osgiService('org.wso2.carbon.user.core.service.RealmService');
var adminUserName = realmService.getBootstrapRealmConfiguration().getAdminUserName();
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var adminUser = devicemgtProps["adminUser"];
module.getDyanmicCredentials = function (owner) { module.getDyanmicCredentials = function (owner) {
var payload = { var payload = {
"callbackUrl": devicemgtProps.callBackUrl, "callbackUrl": devicemgtProps.callBackUrl,
"clientName": "devicemgt", "clientName": "devicemgt",
"tokenScope": "admin", "tokenScope": "admin",
"owner": adminUserName, "owner": adminUser,
"applicationType": "webapp", "applicationType": "webapp",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer", "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
"saasApp" :true "saasApp" :true
@ -47,6 +46,7 @@ var util = function () {
var data = parse(xhr.responseText); var data = parse(xhr.responseText);
clientData.clientId = data.client_id; clientData.clientId = data.client_id;
clientData.clientSecret = data.client_secret; clientData.clientSecret = data.client_secret;
} else if (xhr.status == 400) { } else if (xhr.status == 400) {
throw "Invalid client meta data"; throw "Invalid client meta data";
} else { } else {
@ -137,6 +137,7 @@ var util = function () {
} }
return tokenPair; return tokenPair;
}; };
module.refreshToken = function (tokenPair, clientData, scope) { module.refreshToken = function (tokenPair, clientData, scope) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer + "/oauth2/token"; var tokenEndpoint = devicemgtProps.idPServer + "/oauth2/token";
@ -163,5 +164,37 @@ var util = function () {
} }
return tokenPair; return tokenPair;
}; };
module.getTokenWithJWTGrantType = function (clientData) {
var jwtService = carbon.server.osgiService('org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
var jwtClient = jwtService.getJWTClient();
var jwtToken = jwtClient.getAccessToken(clientData.clientId, clientData.clientSecret, adminUser, null);
return jwtToken;
};
module.getTenantBasedAppCredentials = function (token) {
var tenantDomain = "carbon.super";
var applicationName = "webapp_" + tenantDomain;
var xhr = new XMLHttpRequest();
var endpoint = devicemgtProps["adminService"] + "/register/tenants/" + tenantDomain + "?applicationName=" +
applicationName;
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>APIM App Register endpoint: " + endpoint);
xhr.open("POST", endpoint, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "X-JWT-Assertion " + token.accessToken);
xhr.send();
var clientData = {};
if (xhr.status == 201) {
var data = parse(xhr.responseText);
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>lllllllllllllllllll: " + stringify(data));
//clientData.clientId = data.client_id;
//clientData.clientSecret = data.client_secret;
} else if (xhr.status == 400) {
throw "Invalid client meta data";
} else {
throw "Error in obtaining client id and secret from APIM";
}
}
return module; return module;
}(); }();

@ -41,128 +41,128 @@ import java.util.concurrent.ConcurrentHashMap;
/** /**
* This creates JWT Client for each tenant and implements the JWTClientManagerService interface. * This creates JWT Client for each tenant and implements the JWTClientManagerService interface.
*/ */
public class JWTClientManagerServiceImpl implements JWTClientManagerService{ public class JWTClientManagerServiceImpl implements JWTClientManagerService {
private static Map<String, JWTClient> jwtClientMap; private static Map<String, JWTClient> jwtClientMap;
private static final Log log = LogFactory.getLog(JWTClientManagerServiceImpl.class); private static final Log log = LogFactory.getLog(JWTClientManagerServiceImpl.class);
private static final String TENANT_JWT_CONFIG_LOCATION = "/jwt-config/jwt.properties"; private static final String TENANT_JWT_CONFIG_LOCATION = "/jwt-config/jwt.properties";
private static JWTClient defaultJWTClient; private static JWTClient defaultJWTClient;
public JWTClientManagerServiceImpl() { public JWTClientManagerServiceImpl() {
jwtClientMap = new ConcurrentHashMap<>(); jwtClientMap = new ConcurrentHashMap<>();
} }
/** /**
* this return the jwt based token client to generate token for the tenant. * this return the jwt based token client to generate token for the tenant.
*/ */
@Override @Override
public JWTClient getJWTClient() throws JWTClientException { public JWTClient getJWTClient() throws JWTClientException {
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (tenantId == -1) { if (tenantId == -1) {
throw new JWTClientException("Invalid tenant domain :" + tenantDomain); throw new JWTClientException("Invalid tenant domain :" + tenantDomain);
} }
//Get jwt client which has been registered for the tenant. //Get jwt client which has been registered for the tenant.
JWTClient jwtClient = getJWTClient(tenantDomain); JWTClient jwtClient = getJWTClient(tenantDomain);
if (jwtClient == null) { if (jwtClient == null) {
//Create a new jwt client for the tenant. //Create a new jwt client for the tenant.
try { try {
Properties properties = getJWTConfigProperties(tenantId); Properties properties = getJWTConfigProperties(tenantId);
if (properties == null) { if (properties == null) {
if (defaultJWTClient != null) { if (defaultJWTClient != null) {
return defaultJWTClient; return defaultJWTClient;
} else { } else {
throw new JWTClientException("JWT Configuration is not available for tenant " + tenantDomain); throw new JWTClientException("JWT Configuration is not available for tenant " + tenantDomain);
} }
} }
JWTConfig jwtConfig = new JWTConfig(properties); JWTConfig jwtConfig = new JWTConfig(properties);
jwtClient = new JWTClient(jwtConfig); jwtClient = new JWTClient(jwtConfig);
addJWTClient(tenantDomain, jwtClient); addJWTClient(tenantDomain, jwtClient);
} catch (JWTClientAlreadyExistsException e) { } catch (JWTClientAlreadyExistsException e) {
log.warn("Attempting to register a jwt client for the tenant " + tenantDomain + log.warn("Attempting to register a jwt client for the tenant " + tenantDomain +
" when one already exists. Returning existing jwt client"); " when one already exists. Returning existing jwt client");
return getJWTClient(tenantDomain); return getJWTClient(tenantDomain);
} catch (JWTClientConfigurationException e) { } catch (JWTClientConfigurationException e) {
throw new JWTClientException("Failed to parse jwt configuration for tenant " + tenantDomain, e); throw new JWTClientException("Failed to parse jwt configuration for tenant " + tenantDomain, e);
} }
} }
return jwtClient; return jwtClient;
} }
/** /**
* This will set the default JWT Client that will be used if there is any available for tenants. * This will set the default JWT Client that will be used if there is any available for tenants.
*/ */
@Override @Override
public void setDefaultJWTClient(Properties properties) throws JWTClientConfigurationException { public void setDefaultJWTClient(Properties properties) throws JWTClientConfigurationException {
if (properties == null) { if (properties == null) {
throw new JWTClientConfigurationException("Failed to load jwt configuration for super tenant."); throw new JWTClientConfigurationException("Failed to load jwt configuration for super tenant.");
} }
String defaultJWTClientMode = properties.getProperty(JWTConstants.DEFAULT_JWT_CLIENT); String defaultJWTClientMode = properties.getProperty(JWTConstants.DEFAULT_JWT_CLIENT);
boolean isDefaultJwtClient = false; boolean isDefaultJwtClient = false;
if (defaultJWTClientMode != null && !defaultJWTClientMode.isEmpty()) { if (defaultJWTClientMode != null && !defaultJWTClientMode.isEmpty()) {
isDefaultJwtClient = Boolean.parseBoolean(defaultJWTClientMode); isDefaultJwtClient = Boolean.parseBoolean(defaultJWTClientMode);
} }
if (isDefaultJwtClient) { if (isDefaultJwtClient) {
try { try {
JWTConfig jwtConfig = new JWTConfig(properties); JWTConfig jwtConfig = new JWTConfig(properties);
defaultJWTClient = new JWTClient(jwtConfig, true); defaultJWTClient = new JWTClient(jwtConfig, true);
addJWTClient(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, defaultJWTClient); addJWTClient(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, defaultJWTClient);
} catch (JWTClientAlreadyExistsException e) { } catch (JWTClientAlreadyExistsException e) {
log.warn("Attempting to register a jwt client for the super tenant" + log.warn("Attempting to register a jwt client for the super tenant" +
" when one already exists. Returning existing jwt client"); " when one already exists. Returning existing jwt client");
} }
} }
} }
/** /**
* Fetch the jwt client which has been registered under the tenant domain. * Fetch the jwt client which has been registered under the tenant domain.
* *
* @param tenantDomain - The tenant domain under which the jwt client is registered * @param tenantDomain - The tenant domain under which the jwt client is registered
* @return - Instance of the jwt client which was registered. Null if not registered. * @return - Instance of the jwt client which was registered. Null if not registered.
*/ */
private JWTClient getJWTClient(String tenantDomain) { private JWTClient getJWTClient(String tenantDomain) {
if (jwtClientMap.containsKey(tenantDomain)) { if (jwtClientMap.containsKey(tenantDomain)) {
return jwtClientMap.get(tenantDomain); return jwtClientMap.get(tenantDomain);
} }
return null; return null;
} }
/** /**
* Adds a jwt client to the jwt client map. * Adds a jwt client to the jwt client map.
* *
* @param tenantDomain - The tenant domain under which the jwt client will be registered. * @param tenantDomain - The tenant domain under which the jwt client will be registered.
* @param jwtClient - Instance of the jwt client * @param jwtClient - Instance of the jwt client
* @throws JWTClientAlreadyExistsException - If a jwt client has already been registered under the tenantdomain * @throws JWTClientAlreadyExistsException - If a jwt client has already been registered under the tenantdomain
*/ */
private void addJWTClient(String tenantDomain, JWTClient jwtClient) throws JWTClientAlreadyExistsException { private void addJWTClient(String tenantDomain, JWTClient jwtClient) throws JWTClientAlreadyExistsException {
synchronized (jwtClientMap) { synchronized (jwtClientMap) {
if (jwtClientMap.containsKey(tenantDomain)) { if (jwtClientMap.containsKey(tenantDomain)) {
throw new JWTClientAlreadyExistsException( throw new JWTClientAlreadyExistsException(
"A jwt client has already been created for the tenant " + tenantDomain); "A jwt client has already been created for the tenant " + tenantDomain);
} }
jwtClientMap.put(tenantDomain, jwtClient); jwtClientMap.put(tenantDomain, jwtClient);
} }
} }
/** /**
* Retrieve JWT configs from registry. * Retrieve JWT configs from registry.
*/ */
private Properties getJWTConfigProperties(int tenantId) throws JWTClientConfigurationException { private Properties getJWTConfigProperties(int tenantId) throws JWTClientConfigurationException {
try { try {
Resource config = JWTClientUtil.getConfigRegistryResourceContent(tenantId, TENANT_JWT_CONFIG_LOCATION); Resource config = JWTClientUtil.getConfigRegistryResourceContent(tenantId, TENANT_JWT_CONFIG_LOCATION);
Properties properties = null; Properties properties = null;
if (config != null) { if (config != null) {
properties = new Properties(); properties = new Properties();
properties.load(config.getContentStream()); properties.load(config.getContentStream());
} }
return properties; return properties;
} catch (RegistryException e) { } catch (RegistryException e) {
throw new JWTClientConfigurationException("Failed to load the content from registry for tenant " + throw new JWTClientConfigurationException("Failed to load the content from registry for tenant " +
tenantId, e); tenantId, e);
} catch (IOException e) { } catch (IOException e) {
throw new JWTClientConfigurationException( throw new JWTClientConfigurationException(
"Failed to parse the content from the registry for tenant " + tenantId, e); "Failed to parse the content from the registry for tenant " + tenantId, e);
} }
} }
} }

Loading…
Cancel
Save