{{unit "cdmf.unit.device.operation-mod"}}
{{#if deviceCount}}
-
@@ -324,7 +324,7 @@
{{/zone}}
{{#zone "bottomJs"}}
-
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js
index 88cb32d704e..6a376bb0282 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js
@@ -31,25 +31,13 @@ function onRequest(context) {
page.groupName = groupName;
}
page.title = title;
- page.permissions = {};
var currentUser = session.get(constants.USER_SESSION_KEY);
- var permissions = [];
if (currentUser) {
- if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) {
- permissions.push("LIST_DEVICES");
- } else if (userModule.isAuthorized("/permission/admin/device-mgt/user/devices/list")) {
- permissions.push("LIST_OWN_DEVICES");
- } else if (userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/policies/list")) {
- permissions.push("LIST_POLICIES");
- }
+ page.permissions = {};
+ page.permissions.list = stringify(userModule.getUIPermissions());
if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/add")) {
permissions.enroll = true;
}
- if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/remove")) {
- permissions.push("REMOVE_DEVICE");
- }
-
- page.permissions.list = permissions;
page.currentUser = currentUser;
var deviceCount = 0;
if (groupName && groupOwner) {
@@ -64,15 +52,17 @@ function onRequest(context) {
var utility = require("/app/modules/utility.js").utility;
var data = deviceModule.getDeviceTypes();
var deviceTypes = [];
- if (data.data) {
- for (var i = 0; i < data.data.length; i++) {
+ if (data) {
+ for (var i = 0; i < data.length; i++) {
+ var deviceType = utility.getDeviceTypeConfig(data[i].name).deviceType;
deviceTypes.push({
- "type": data.data[i].name,
- "category": utility.getDeviceTypeConfig(data.data[i].name).deviceType.category
- });
+ "type": data[i].name,
+ "category": deviceType.category,
+ "label": deviceType.label
+ });
}
}
- page.deviceTypes = deviceTypes;
+ page.deviceTypes = stringify(deviceTypes);
}
}
return page;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js
index 2711b2b29c5..767c37f6848 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js
@@ -72,8 +72,10 @@ $(document).ready(function () {
var i;
var permissionList = $("#permission").data("permission");
- for (i = 0; i < permissionList.length; i++) {
- $.setPermission(permissionList[i]);
+ for (var key in permissionList) {
+ if (permissionList.hasOwnProperty(key)) {
+ $.setPermission(key);
+ }
}
/* for device list sorting drop down */
@@ -171,7 +173,7 @@ function loadDevices(searchType, searchParam){
serviceURL = "/devicemgt_admin/devices";
} else if ($.hasPermission("LIST_OWN_DEVICES")) {
//Get authenticated users devices
- serviceURL = "/devicemgt_admin/users/devices?username="+currentUser;
+ serviceURL = "/devicemgt_admin/users/devices?username=" + currentUser;
} else {
$("#loading-content").remove();
$('#device-table').addClass('hidden');
@@ -181,8 +183,11 @@ function loadDevices(searchType, searchParam){
}
function getPropertyValue(deviceProperties, propertyName) {
+ if (!deviceProperties) {
+ return;
+ }
var property;
- for (var i =0; i < deviceProperties.length; i++) {
+ for (var i = 0; i < deviceProperties.length; i++) {
property = deviceProperties[i];
if (property.name == propertyName) {
return property.value;
@@ -191,6 +196,16 @@ function loadDevices(searchType, searchParam){
return {};
}
+ function getDeviceTypeLabel(type){
+ var deviceTypes = deviceListing.data("deviceTypes");
+ for (var i = 0; i < deviceTypes.length; i++){
+ if (deviceTypes[i].type == type){
+ return deviceTypes[i].label;
+ }
+ }
+ return type;
+ }
+
$('#device-grid').datatables_extended ({
serverSide: true,
processing: false,
@@ -242,7 +257,10 @@ function loadDevices(searchType, searchParam){
}
return html;
}},
- { targets: 4, data: 'type' , className: 'fade-edge remove-padding-top' },
+ { targets: 4, data: 'type' , className: 'fade-edge remove-padding-top' ,
+ render: function ( status, type, row, meta ) {
+ return getDeviceTypeLabel(row.type);
+ }},
{ targets: 5, data: 'enrolmentInfo.ownership' , className: 'fade-edge remove-padding-top' },
{ targets: 6, data: 'enrolmentInfo.status' , className: 'text-right content-fill text-left-on-grid-view no-wrap' ,
render: function ( status, type, row, meta ) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js
index 00aa67e7d58..15679db0630 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js
@@ -22,33 +22,42 @@ var invokerUtil = function () {
var END_POINT = window.location.origin+"/devicemgt/api/invoker/execute/";
- module.get = function (url, successCallback, errorCallback) {
+ module.get = function (url, successCallback, errorCallback, contentType, acceptType) {
var payload = null;
- execute("GET", url, payload, successCallback, errorCallback);
+ execute("GET", url, payload, successCallback, errorCallback, contentType, acceptType);
};
- module.post = function (url, payload, successCallback, errorCallback) {
- execute("POST", url, payload, successCallback, errorCallback);
+ module.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
+ execute("POST", url, payload, successCallback, errorCallback, contentType, acceptType);
};
- module.put = function (url, payload, successCallback, errorCallback) {
- execute("PUT", url, payload, successCallback, errorCallback);
+ module.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) {
+ execute("PUT", url, payload, successCallback, errorCallback, contentType, acceptType);
};
- module.delete = function (url, successCallback, errorCallback) {
+ module.delete = function (url, successCallback, errorCallback, contentType, acceptType) {
var payload = null;
- execute("DELETE", url, payload, successCallback, errorCallback);
+ execute("DELETE", url, payload, successCallback, errorCallback, contentType, acceptType);
};
- function execute (methoad, url, payload, successCallback, errorCallback) {
+ function execute (methoad, url, payload, successCallback, errorCallback, contentType, acceptType) {
+ if(contentType == undefined){
+ contentType = "application/json";
+ }
+ if(acceptType == undefined){
+ acceptType = "application/json";
+ }
var data = {
url: END_POINT,
type: "POST",
- contentType: "application/json",
- accept: "application/json",
+ contentType: contentType,
+ accept: acceptType,
success: successCallback
};
console.log(data);
var paramValue = {};
paramValue.actionMethod = methoad;
paramValue.actionUrl = url;
- paramValue.actionPayload = JSON.stringify(payload);
+ paramValue.actionPayload = payload;
+ if(contentType == "application/json"){
+ paramValue.actionPayload = JSON.stringify(payload);
+ }
data.data = JSON.stringify(paramValue);
$.ajax(data).fail(function (jqXHR) {
if (jqXHR.status == "401") {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js
index 73563a8c57b..922563ed6bf 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/lib/modules/auth/auth.js
@@ -56,7 +56,7 @@ var module = {};
cachedAuthModuleConfigs = authModuleConfigs;
} else {
log.error("Cannot find User module configurations in application configuration file '"
- + constants.FILE_APP_CONF + "'.");
+ + constants.FILE_APP_CONF + "'.");
cachedAuthModuleConfigs = {};
}
return cachedAuthModuleConfigs;
@@ -85,7 +85,7 @@ var module = {};
return (rv) ? rv : {};
} else {
log.error("Cannot find login configurations in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF + "'.");
+ + "application configuration file '" + constants.FILE_APP_CONF + "'.");
return {};
}
}
@@ -113,7 +113,7 @@ var module = {};
return (rv) ? rv : {};
} else {
log.error("Cannot find logout configurations in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF + "'.");
+ + "application configuration file '" + constants.FILE_APP_CONF + "'.");
return {};
}
}
@@ -133,7 +133,7 @@ var module = {};
cachedSsoConfigs = ssoConfigs;
} else {
log.error("Cannot find SSO configurations in Auth module configurations in application "
- + "configuration file '" + constants.FILE_APP_CONF + "'.");
+ + "configuration file '" + constants.FILE_APP_CONF + "'.");
cachedSsoConfigs = {};
}
return cachedSsoConfigs;
@@ -156,13 +156,13 @@ var module = {};
if (operation == OPERATION_LOGIN) {
configs = getLoginConfigurations(event);
pageFullName = (event == EVENT_SUCCESS) ?
- configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_PAGE] :
- configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_PAGE];
+ configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_PAGE] :
+ configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_PAGE];
} else {
configs = getLogoutConfigurations(event);
pageFullName = (event == EVENT_SUCCESS) ?
- configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_PAGE] :
- configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_PAGE];
+ configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_PAGE] :
+ configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_PAGE];
}
if (pageFullName) {
@@ -173,13 +173,13 @@ var module = {};
return page.definition[constants.PAGE_DEFINITION_URI];
}
log.warn("Page '" + pageFullName + "' mentioned in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF
- + "' is disabled.");
+ + "application configuration file '" + constants.FILE_APP_CONF
+ + "' is disabled.");
} else {
log.error("Page '" + pageFullName + "' mentioned in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF
- + "' does not exists.");
+ + "application configuration file '" + constants.FILE_APP_CONF
+ + "' does not exists.");
}
}
return "/";
@@ -207,13 +207,13 @@ var module = {};
if (operation == OPERATION_LOGIN) {
configs = getLoginConfigurations(event);
scriptFilePath = (event == EVENT_SUCCESS) ?
- configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_SCRIPT] :
- configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_SCRIPT];
+ configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_SUCCESS_SCRIPT] :
+ configs[constants.APP_CONF_AUTH_MODULE_LOGIN_ON_FAIL_SCRIPT];
} else {
configs = getLogoutConfigurations(event);
scriptFilePath = (event == EVENT_SUCCESS) ?
- configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_SCRIPT] :
- configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_SCRIPT];
+ configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_SUCCESS_SCRIPT] :
+ configs[constants.APP_CONF_AUTH_MODULE_LOGOUT_ON_FAIL_SCRIPT];
}
if (!scriptFilePath || (scriptFilePath.length == 0)) {
@@ -222,8 +222,8 @@ var module = {};
var scriptFile = new File(scriptFilePath);
if (!scriptFile.isExists() || scriptFile.isDirectory()) {
log.error("Script '" + scriptFilePath + "' mentioned in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF
- + "' does not exists.");
+ + "application configuration file '" + constants.FILE_APP_CONF
+ + "' does not exists.");
return true;
}
@@ -265,7 +265,7 @@ var module = {};
} else {
// event == EVENT_FAIL
redirectUri = getRedirectUri(operation, EVENT_FAIL) + "?error=" + scriptArgument.message
- + "&" + constants.URL_PARAM_REFERER + "=" + getRelayState(operation);
+ + "&" + constants.URL_PARAM_REFERER + "=" + getRelayState(operation);
}
response.sendRedirect(encodeURI(module.getAppContext() + redirectUri));
}
@@ -276,8 +276,8 @@ var module = {};
var identityProviderUrl = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_IDENTITY_PROVIDER_URL];
if (!identityProviderUrl || (identityProviderUrl.length == 0)) {
var msg = "Identity Provider URL is not given in SSO configurations in Auth module "
- + "configurations in application configuration file '"
- + constants.FILE_APP_CONF + "'.";
+ + "configurations in application configuration file '"
+ + constants.FILE_APP_CONF + "'.";
log.error(msg);
response.sendError(500, msg);
return null;
@@ -286,7 +286,7 @@ var module = {};
var issuer = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_ISSUER];
if (!issuer || (issuer.length == 0)) {
var msg = "Issuer is not given in SSO configurations in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF + "'.";
+ + "application configuration file '" + constants.FILE_APP_CONF + "'.";
log.error(msg);
response.sendError(500, msg);
return null;
@@ -316,8 +316,8 @@ var module = {};
var identityProviderUrl = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_IDENTITY_PROVIDER_URL];
if (!identityProviderUrl || (identityProviderUrl.length == 0)) {
var msg = "Identity Provider URL is not given in SSO configurations in Auth module "
- + "configurations in application configuration file '"
- + constants.FILE_APP_CONF + "'.";
+ + "configurations in application configuration file '"
+ + constants.FILE_APP_CONF + "'.";
log.error(msg);
response.sendError(500, msg);
return null;
@@ -331,7 +331,7 @@ var module = {};
var issuer = ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_ISSUER];
if (!issuer || (issuer.length == 0)) {
var msg = "Issuer is not given in SSO configurations in Auth module configurations in "
- + "application configuration file '" + constants.FILE_APP_CONF + "'.";
+ + "application configuration file '" + constants.FILE_APP_CONF + "'.";
log.error(msg);
response.sendError(500, msg);
return null;
@@ -341,10 +341,10 @@ var module = {};
try {
var ssoClient = require("sso").client;
encodedSAMLAuthRequest = ssoClient.getEncodedSAMLLogoutRequest(username,
- ssoSessionIndex, issuer);
+ ssoSessionIndex, issuer);
} catch (e) {
log.error("Cannot create SAML logout authorization token for user '" + username
- + "' with issuer '" + issuer + "'.");
+ + "' with issuer '" + issuer + "'.");
log.error(e.message, e);
response.sendError(500, e.message);
return null;
@@ -446,17 +446,17 @@ var module = {};
intermediatePage = utils.getFurthestChild(intermediatePage);
if (!intermediatePage.disabled) {
renderer.renderUiComponent(intermediatePage, requestParams, renderingContext,
- lookupTable, response);
+ lookupTable, response);
return;
}
log.warn("Intermediate page '" + intermediatePageName + " mentioned in Auth module "
- + "configurations in application configuration file '"
- + constants.FILE_APP_CONF + "' is disabled.");
+ + "configurations in application configuration file '"
+ + constants.FILE_APP_CONF + "' is disabled.");
} else {
log.error("Intermediate page '" + intermediatePageName
- + " mentioned in Auth module "
- + "configurations in application configuration file '"
- + constants.FILE_APP_CONF + "' does not exists.");
+ + " mentioned in Auth module "
+ + "configurations in application configuration file '"
+ + constants.FILE_APP_CONF + "' does not exists.");
}
}
@@ -528,13 +528,13 @@ var module = {};
* string}}
*/
var ssoSession = ssoClient.decodeSAMLLoginResponse(samlResponseObj, samlResponse,
- session.getId());
+ session.getId());
if (ssoSession.sessionId) {
var ssoSessions = getSsoSessions();
ssoSessions[ssoSession.sessionId] = ssoSession;
var carbonUser = (require("carbon")).server.tenantUser(ssoSession.loggedInUser);
utils.setCurrentUser(carbonUser.username, carbonUser.domain, carbonUser.tenantId);
- var scriptArgument = {input: {}, user: module.getCurrentUser()};
+ var scriptArgument = {input: {samlToken: ssoSession.samlToken}, user: module.getCurrentUser()};
handleEvent(OPERATION_LOGIN, EVENT_SUCCESS, scriptArgument);
} else {
var msg = "Cannot decode SAML login response.";
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
index 0f86757cea3..5592ee46a39 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
@@ -90,10 +90,6 @@
commons-lang.wso2
commons-lang
-
- org.wso2.carbon.analytics
- org.wso2.carbon.analytics.api
-
org.wso2.carbon.registry
org.wso2.carbon.registry.indexing
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java
index fc50292de54..8251a1bceed 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java
@@ -18,13 +18,6 @@
package org.wso2.carbon.identity.jwt.client.extension;
-import com.nimbusds.jose.JOSEException;
-import com.nimbusds.jose.JWSAlgorithm;
-import com.nimbusds.jose.JWSHeader;
-import com.nimbusds.jose.JWSSigner;
-import com.nimbusds.jose.crypto.RSASSASigner;
-import com.nimbusds.jwt.JWTClaimsSet;
-import com.nimbusds.jwt.SignedJWT;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -36,32 +29,21 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
-import org.json.simple.parser.ParseException;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.core.util.KeyStoreManager;
+import org.json.simple.parser.ParseException;;
import org.wso2.carbon.identity.jwt.client.extension.constant.JWTConstants;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil;
-import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.net.MalformedURLException;
-import java.net.URI;
import java.net.URL;
import java.security.KeyManagementException;
-import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.interfaces.RSAPrivateKey;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
-import java.util.Random;
/**
* this class represents an implementation of Token Client which is based on JWT
@@ -69,12 +51,6 @@ import java.util.Random;
public class JWTClient {
private static Log log = LogFactory.getLog(JWTClient.class);
- private static final String JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
- private static final String GRANT_TYPE_PARAM_NAME = "grant_type";
- private static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
- private static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token";
- private static final String JWT_PARAM_NAME = "assertion";
- private static final String SCOPE_PARAM_NAME = "scope";
private JWTConfig jwtConfig;
public JWTClient(JWTConfig jwtConfig) {
@@ -87,13 +63,13 @@ public class JWTClient {
public AccessTokenInfo getAccessToken(String consumerKey, String consumerSecret, String username, String scopes)
throws JWTClientException {
List params = new ArrayList<>();
- params.add(new BasicNameValuePair(GRANT_TYPE_PARAM_NAME, JWT_GRANT_TYPE));
- String assertion = generateSignedJWTAssertion(username);
+ params.add(new BasicNameValuePair(JWTConstants.GRANT_TYPE_PARAM_NAME, JWTConstants.JWT_GRANT_TYPE));
+ String assertion = JWTClientUtil.generateSignedJWTAssertion(username, jwtConfig);
if (assertion == null) {
throw new JWTClientException("JWT is not configured properly for user : " + username);
}
- params.add(new BasicNameValuePair(JWT_PARAM_NAME, assertion));
- params.add(new BasicNameValuePair(SCOPE_PARAM_NAME, scopes));
+ params.add(new BasicNameValuePair(JWTConstants.JWT_PARAM_NAME, assertion));
+ params.add(new BasicNameValuePair(JWTConstants.SCOPE_PARAM_NAME, scopes));
return getTokenInfo(params, consumerKey, consumerSecret);
}
@@ -104,9 +80,9 @@ public class JWTClient {
String consumerKey, String consumerSecret)
throws JWTClientException {
List params = new ArrayList<>();
- params.add(new BasicNameValuePair(GRANT_TYPE_PARAM_NAME, REFRESH_TOKEN_GRANT_TYPE));
- params.add(new BasicNameValuePair(REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken));
- params.add(new BasicNameValuePair(SCOPE_PARAM_NAME, scopes));
+ params.add(new BasicNameValuePair(JWTConstants.GRANT_TYPE_PARAM_NAME, JWTConstants.REFRESH_TOKEN_GRANT_TYPE));
+ params.add(new BasicNameValuePair(JWTConstants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken));
+ params.add(new BasicNameValuePair(JWTConstants.SCOPE_PARAM_NAME, scopes));
return getTokenInfo(params, consumerKey, consumerSecret);
}
@@ -132,10 +108,10 @@ public class JWTClient {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
- accessTokenInfo.setAccess_token((String) jsonObject.get(JWTConstants.OAUTH_ACCESS_TOKEN));
- accessTokenInfo.setRefresh_token((String) jsonObject.get(JWTConstants.OAUTH_REFRESH_TOKEN));
- accessTokenInfo.setExpires_in((Long) jsonObject.get(JWTConstants.OAUTH_EXPIRES_IN));
- accessTokenInfo.setToken_type((String) jsonObject.get(JWTConstants.OAUTH_TOKEN_TYPE));
+ accessTokenInfo.setAccessToken((String) jsonObject.get(JWTConstants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME));
+ accessTokenInfo.setRefreshToken((String) jsonObject.get(JWTConstants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME));
+ accessTokenInfo.setExpiresIn((Long) jsonObject.get(JWTConstants.OAUTH_EXPIRES_IN));
+ accessTokenInfo.setTokenType((String) jsonObject.get(JWTConstants.OAUTH_TOKEN_TYPE));
return accessTokenInfo;
} catch (MalformedURLException e) {
throw new JWTClientException("Invalid URL for token endpoint " + jwtConfig.getTokenEndpoint(), e);
@@ -156,92 +132,7 @@ public class JWTClient {
return new String(Base64.encodeBase64((consumerKey + ":" + consumerSecret).getBytes()));
}
- public String generateSignedJWTAssertion(String username) throws JWTClientException {
- try {
- String subject = username;
- long currentTimeMillis = System.currentTimeMillis();
- // add the skew between servers
- String iss = jwtConfig.getIssuer();
- if (iss == null || iss.isEmpty()) {
- return null;
- }
- currentTimeMillis += jwtConfig.getSkew();
- long iat = currentTimeMillis + jwtConfig.getIssuedInternal() * 60 * 1000;
- long exp = currentTimeMillis + jwtConfig.getExpirationTime() * 60 * 1000;
- long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000;
- String jti = jwtConfig.getJti();
- if (jti == null) {
- String defaultTokenId = currentTimeMillis + "" + new Random().nextInt();
- jti = defaultTokenId;
- }
- List aud = jwtConfig.getAudiences();
- //set up the basic claims
- JWTClaimsSet claimsSet = new JWTClaimsSet();
- claimsSet.setIssueTime(new Date(iat));
- claimsSet.setExpirationTime(new Date(exp));
- claimsSet.setIssuer(iss);
- claimsSet.setSubject(username);
- claimsSet.setNotBeforeTime(new Date(nbf));
- claimsSet.setJWTID(jti);
- claimsSet.setAudience(aud);
-
- // get Keystore params
- String keyStorePath = jwtConfig.getKeyStorePath();
- String privateKeyAlias = jwtConfig.getPrivateKeyAlias();
- String privateKeyPassword = jwtConfig.getPrivateKeyPassword();
- KeyStore keyStore;
- RSAPrivateKey rsaPrivateKey;
- if (keyStorePath != null && !keyStorePath.isEmpty()) {
- String keyStorePassword = jwtConfig.getKeyStorePassword();
- keyStore = loadKeyStore(new File(keyStorePath), keyStorePassword, "JKS");
- rsaPrivateKey = (RSAPrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword.toCharArray());
- } else {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- KeyStoreManager tenantKeyStoreManager = KeyStoreManager.getInstance(tenantId);
- rsaPrivateKey = (RSAPrivateKey) tenantKeyStoreManager.getDefaultPrivateKey();
- }
- JWSSigner signer = new RSASSASigner(rsaPrivateKey);
- SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
- signedJWT.sign(signer);
- String assertion = signedJWT.serialize();
- return assertion;
- } catch (KeyStoreException e) {
- throw new JWTClientException("Failed loading the keystore.", e);
- } catch (IOException e) {
- throw new JWTClientException("Failed parsing the keystore file.", e);
- } catch (NoSuchAlgorithmException e) {
- throw new JWTClientException("No such algorithm found RS256.", e);
- } catch (CertificateException e) {
- throw new JWTClientException("Failed loading the certificate from the keystore.", e);
- } catch (UnrecoverableKeyException e) {
- throw new JWTClientException("Failed loading the keys from the keystore.", e);
- } catch (JOSEException e) {
- throw new JWTClientException(e);
- } catch (Exception e) {
- //This is thrown when loading default private key.
- throw new JWTClientException("Failed loading the private key.", e);
- }
- }
- private KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
- throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
- if (null == keystoreFile) {
- throw new IllegalArgumentException("Keystore url may not be null");
- }
- URI keystoreUri = keystoreFile.toURI();
- URL keystoreUrl = keystoreUri.toURL();
- KeyStore keystore = KeyStore.getInstance(keyStoreType);
- InputStream is = null;
- try {
- is = keystoreUrl.openStream();
- keystore.load(is, null == password ? null : password.toCharArray());
- } finally {
- if (null != is) {
- is.close();
- }
- }
- return keystore;
- }
}
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java
index 106c5228009..ab6a4b142d1 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java
@@ -21,8 +21,15 @@ package org.wso2.carbon.identity.jwt.client.extension.constant;
* This holds the constants related JWT client component.
*/
public class JWTConstants {
- public static final String OAUTH_ACCESS_TOKEN = "access_token";
- public static final String OAUTH_REFRESH_TOKEN = "refresh_token";
public static final String OAUTH_EXPIRES_IN = "expires_in";
public static final String OAUTH_TOKEN_TYPE = "token_type";
+ public static final String JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
+ public static final String GRANT_TYPE_PARAM_NAME = "grant_type";
+ public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
+ public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token";
+ public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token";
+ public static final String JWT_PARAM_NAME = "assertion";
+ public static final String SCOPE_PARAM_NAME = "scope";
+ public static final String DEFAULT_JWT_CLIENT = "default-jwt-client";
}
+
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java
index 146ddf128a1..c1adb813fd4 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java
@@ -23,40 +23,40 @@ package org.wso2.carbon.identity.jwt.client.extension.dto;
*/
public class AccessTokenInfo {
- private String token_type;
- private long expires_in;
- private String refresh_token;
- private String access_token;
+ private String tokenType;
+ private long expiresIn;
+ private String refreshToken;
+ private String accessToken;
- public String getToken_type() {
- return token_type;
+ public String getTokenType() {
+ return tokenType;
}
- public void setToken_type(String token_type) {
- this.token_type = token_type;
+ public void setTokenType(String tokenType) {
+ this.tokenType = tokenType;
}
- public long getExpires_in() {
- return expires_in;
+ public long getExpiresIn() {
+ return expiresIn;
}
- public void setExpires_in(long expres_in) {
- this.expires_in = expres_in;
+ public void setExpiresIn(long expiresIn) {
+ this.expiresIn = expiresIn;
}
- public String getRefresh_token() {
- return refresh_token;
+ public String getRefreshToken() {
+ return refreshToken;
}
- public void setRefresh_token(String refresh_token) {
- this.refresh_token = refresh_token;
+ public void setRefreshToken(String refreshToken) {
+ this.refreshToken = refreshToken;
}
- public String getAccess_token() {
- return access_token;
+ public String getAccessToken() {
+ return accessToken;
}
- public void setAccess_token(String access_token) {
- this.access_token = access_token;
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
}
}
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java
index ff59df5fd32..3ca17170896 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java
@@ -20,7 +20,11 @@ package org.wso2.carbon.identity.jwt.client.extension.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException;
+import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
+import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerServiceImpl;
import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
@@ -66,11 +70,16 @@ public class JWTClientExtensionServiceComponent {
log.debug("Initializing jwt extension bundle");
}
try {
- JWTClientUtil.initialize();
+ JWTClientManagerService jwtClientManagerService = new JWTClientManagerServiceImpl();
+ JWTClientUtil.initialize(jwtClientManagerService);
+ BundleContext bundleContext = componentContext.getBundleContext();
+ bundleContext.registerService(JWTClientManagerService.class.getName(), jwtClientManagerService, null);
} catch (RegistryException e) {
log.error("Failed loading the jwt config from registry.", e);
} catch (IOException e) {
log.error("Failed loading the jwt config from the file system.", e);
+ } catch (JWTClientConfigurationException e) {
+ log.error("Failed to set default jwt configurations.", e);
}
}
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerService.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerService.java
new file mode 100644
index 00000000000..83e4ca8884f
--- /dev/null
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerService.java
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.wso2.carbon.identity.jwt.client.extension.service;
+
+import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
+
+import java.util.Properties;
+
+/**
+ * This is the JWTClientManagerServiceImpl Service that can be used to have JWT Client for tenant specific.
+ */
+public interface JWTClientManagerService {
+
+ /**
+ * This return the jwt based token client to generate token for the tenant.
+ * @return JWTClient that can be used to generate token.
+ * @throws JWTClientException when the JWT Client creation fails
+ */
+ JWTClient getJWTClient() throws JWTClientException;
+
+ /**
+ * This will set the default JWT Client that will be used if there is any available for tenants.
+ * @param properties required to configure jwt client.
+ * @throws JWTClientConfigurationException throws when the configuration is invalid.
+ */
+ void setDefaultJWTClient(Properties properties) throws JWTClientConfigurationException;
+}
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java
similarity index 62%
rename from components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java
rename to components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java
index bea6664a108..eee439d7685 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/service/JWTClientManagerServiceImpl.java
@@ -16,12 +16,15 @@
* under the License.
*/
-package org.wso2.carbon.identity.jwt.client.extension;
+package org.wso2.carbon.identity.jwt.client.extension.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
+import org.wso2.carbon.identity.jwt.client.extension.constant.JWTConstants;
import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientAlreadyExistsException;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException;
@@ -36,42 +39,44 @@ import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
- * This creates JWT Client for each tenant.
+ * This creates JWT Client for each tenant and implements the JWTClientManagerService interface.
*/
-public class JWTClientManager {
+public class JWTClientManagerServiceImpl implements JWTClientManagerService{
private static Map jwtClientMap;
- private static JWTClientManager jwtClientCreator;
- private static final Log log = LogFactory.getLog(JWTClientManager.class);
+ private static final Log log = LogFactory.getLog(JWTClientManagerServiceImpl.class);
private static final String TENANT_JWT_CONFIG_LOCATION = "/jwt-config/jwt.properties";
+ private static JWTClient defaultJWTClient;
- public static JWTClientManager getInstance() {
- if (jwtClientCreator == null) {
- synchronized (JWTClientManager.class) {
- if (jwtClientCreator == null) {
- jwtClientCreator = new JWTClientManager();
- }
- }
- }
- return jwtClientCreator;
- }
- private JWTClientManager() {
+ public JWTClientManagerServiceImpl() {
jwtClientMap = new ConcurrentHashMap<>();
}
/**
* this return the jwt based token client to generate token for the tenant.
*/
+ @Override
public JWTClient getJWTClient() throws JWTClientException {
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ if (tenantId == -1) {
+ throw new JWTClientException("Invalid tenant domain :" + tenantDomain);
+ }
//Get jwt client which has been registered for the tenant.
JWTClient jwtClient = getJWTClient(tenantDomain);
if (jwtClient == null) {
- //Create new jwt client for the tenant.
+ //Create a new jwt client for the tenant.
try {
- JWTConfig jwtConfig = new JWTConfig(getJWTConfig(tenantId));
+ Properties properties = getJWTConfigProperties(tenantId);
+ if (properties == null) {
+ if (defaultJWTClient != null) {
+ return defaultJWTClient;
+ } else {
+ throw new JWTClientException("JWT Configuration is not available for tenant " + tenantDomain);
+ }
+ }
+ JWTConfig jwtConfig = new JWTConfig(properties);
jwtClient = new JWTClient(jwtConfig);
addJWTClient(tenantDomain, jwtClient);
} catch (JWTClientAlreadyExistsException e) {
@@ -85,6 +90,31 @@ public class JWTClientManager {
return jwtClient;
}
+ /**
+ * This will set the default JWT Client that will be used if there is any available for tenants.
+ */
+ @Override
+ public void setDefaultJWTClient(Properties properties) throws JWTClientConfigurationException {
+ if (properties == null) {
+ throw new JWTClientConfigurationException("Failed to load jwt configuration for super tenant.");
+ }
+ String defaultJWTClientMode = properties.getProperty(JWTConstants.DEFAULT_JWT_CLIENT);
+ boolean isDefaultJwtClient = false;
+ if (defaultJWTClientMode != null && !defaultJWTClientMode.isEmpty()) {
+ isDefaultJwtClient = Boolean.parseBoolean(defaultJWTClientMode);
+ }
+ if (isDefaultJwtClient) {
+ try {
+ JWTConfig jwtConfig = new JWTConfig(properties);
+ defaultJWTClient = new JWTClient(jwtConfig);
+ addJWTClient(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, defaultJWTClient);
+ } catch (JWTClientAlreadyExistsException e) {
+ log.warn("Attempting to register a jwt client for the super tenant" +
+ " when one already exists. Returning existing jwt client");
+ }
+ }
+ }
+
/**
* Fetch the jwt client which has been registered under the tenant domain.
*
@@ -106,23 +136,25 @@ public class JWTClientManager {
* @throws JWTClientAlreadyExistsException - If a jwt client has already been registered under the tenantdomain
*/
private void addJWTClient(String tenantDomain, JWTClient jwtClient) throws JWTClientAlreadyExistsException {
- if (jwtClientMap.containsKey(tenantDomain)) {
- throw new JWTClientAlreadyExistsException("A jwt client has already been created for the tenant " + tenantDomain);
+ synchronized (jwtClientMap) {
+ if (jwtClientMap.containsKey(tenantDomain)) {
+ throw new JWTClientAlreadyExistsException(
+ "A jwt client has already been created for the tenant " + tenantDomain);
+ }
+ jwtClientMap.put(tenantDomain, jwtClient);
}
- jwtClientMap.put(tenantDomain, jwtClient);
}
/**
* Retrieve JWT configs from registry.
*/
- private Properties getJWTConfig(int tenantId) throws JWTClientConfigurationException {
+ private Properties getJWTConfigProperties(int tenantId) throws JWTClientConfigurationException {
try {
Resource config = JWTClientUtil.getConfigRegistryResourceContent(tenantId, TENANT_JWT_CONFIG_LOCATION);
- Properties properties = new Properties();
- if(config != null) {
+ Properties properties = null;
+ if (config != null) {
+ properties = new Properties();
properties.load(config.getContentStream());
- } else {
- throw new JWTClientConfigurationException("Failed to load jwt configuration for tenant id : " + tenantId);
}
return properties;
} catch (RegistryException e) {
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java
index 9cb0792487e..352e8177aa7 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java
@@ -17,7 +17,13 @@
*/
package org.wso2.carbon.identity.jwt.client.extension.util;
-import org.apache.commons.io.FileUtils;
+import com.nimbusds.jose.JOSEException;
+import com.nimbusds.jose.JWSAlgorithm;
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jose.JWSSigner;
+import com.nimbusds.jose.crypto.RSASSASigner;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.SignedJWT;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
@@ -27,8 +33,12 @@ import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
-import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.util.KeyStoreManager;
+import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
+import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException;
+import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
@@ -36,13 +46,25 @@ import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
import org.wso2.carbon.utils.CarbonUtils;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
+import java.net.URI;
+import java.net.URL;
import java.security.KeyManagementException;
+import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.security.interfaces.RSAPrivateKey;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
/**
* This is the utility class that is used for JWT Client.
@@ -55,8 +77,10 @@ public class JWTClientUtil {
private static final String JWT_CONFIG_FILE_NAME = "jwt.properties";
private static final String SUPERTENANT_JWT_CONFIG_LOCATION =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + JWT_CONFIG_FILE_NAME;
+
/**
* Return a http client instance
+ *
* @param protocol- service endpoint protocol http/https
* @return
*/
@@ -96,12 +120,14 @@ public class JWTClientUtil {
}
}
- public static void initialize() throws RegistryException, IOException {
- Resource resource = getConfigRegistryResourceContent(MultitenantConstants.SUPER_TENANT_ID, TENANT_JWT_CONFIG_LOCATION);
- if (resource == null) {
- File configFile = new File(SUPERTENANT_JWT_CONFIG_LOCATION);
- String contents = FileUtils.readFileToString(configFile, "UTF-8");
- addJWTConfigResourceToRegistry(MultitenantConstants.SUPER_TENANT_ID, contents);
+ public static void initialize(JWTClientManagerService jwtClientManagerService)
+ throws RegistryException, IOException, JWTClientConfigurationException {
+ File configFile = new File(SUPERTENANT_JWT_CONFIG_LOCATION);
+ if (configFile.exists()) {
+ InputStream propertyStream = configFile.toURI().toURL().openStream();
+ Properties properties = new Properties();
+ properties.load(propertyStream);
+ jwtClientManagerService.setDefaultJWTClient(properties);
}
}
@@ -136,7 +162,7 @@ public class JWTClientUtil {
/**
* Get the jwt details from the registry for tenants.
*
- * @param tenantId for accesing tenant space.
+ * @param tenantId for accesing tenant space.
* @return the config for tenant
* @throws RegistryException
*/
@@ -161,8 +187,96 @@ public class JWTClientUtil {
}
private static void loadTenantRegistry(int tenantId) throws RegistryException {
- TenantRegistryLoader tenantRegistryLoader = JWTClientExtensionDataHolder.getInstance().getTenantRegistryLoader();
+ TenantRegistryLoader tenantRegistryLoader =
+ JWTClientExtensionDataHolder.getInstance().getTenantRegistryLoader();
JWTClientExtensionDataHolder.getInstance().getIndexLoaderService().loadTenantIndex(tenantId);
tenantRegistryLoader.loadTenantRegistry(tenantId);
}
+
+ public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig) throws JWTClientException {
+ try {
+ String subject = username;
+ long currentTimeMillis = System.currentTimeMillis();
+ // add the skew between servers
+ String iss = jwtConfig.getIssuer();
+ if (iss == null || iss.isEmpty()) {
+ return null;
+ }
+ currentTimeMillis += jwtConfig.getSkew();
+ long iat = currentTimeMillis + jwtConfig.getIssuedInternal() * 60 * 1000;
+ long exp = currentTimeMillis + jwtConfig.getExpirationTime() * 60 * 1000;
+ long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000;
+ String jti = jwtConfig.getJti();
+ if (jti == null) {
+ String defaultTokenId = currentTimeMillis + "" + new Random().nextInt();
+ jti = defaultTokenId;
+ }
+ List aud = jwtConfig.getAudiences();
+ //set up the basic claims
+ JWTClaimsSet claimsSet = new JWTClaimsSet();
+ claimsSet.setIssueTime(new Date(iat));
+ claimsSet.setExpirationTime(new Date(exp));
+ claimsSet.setIssuer(iss);
+ claimsSet.setSubject(username);
+ claimsSet.setNotBeforeTime(new Date(nbf));
+ claimsSet.setJWTID(jti);
+ claimsSet.setAudience(aud);
+
+ // get Keystore params
+ String keyStorePath = jwtConfig.getKeyStorePath();
+ String privateKeyAlias = jwtConfig.getPrivateKeyAlias();
+ String privateKeyPassword = jwtConfig.getPrivateKeyPassword();
+ KeyStore keyStore;
+ RSAPrivateKey rsaPrivateKey;
+ if (keyStorePath != null && !keyStorePath.isEmpty()) {
+ String keyStorePassword = jwtConfig.getKeyStorePassword();
+ keyStore = loadKeyStore(new File(keyStorePath), keyStorePassword, "JKS");
+ rsaPrivateKey = (RSAPrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword.toCharArray());
+ } else {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ KeyStoreManager tenantKeyStoreManager = KeyStoreManager.getInstance(tenantId);
+ rsaPrivateKey = (RSAPrivateKey) tenantKeyStoreManager.getDefaultPrivateKey();
+ }
+ JWSSigner signer = new RSASSASigner(rsaPrivateKey);
+ SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
+ signedJWT.sign(signer);
+ String assertion = signedJWT.serialize();
+ return assertion;
+ } catch (KeyStoreException e) {
+ throw new JWTClientException("Failed loading the keystore.", e);
+ } catch (IOException e) {
+ throw new JWTClientException("Failed parsing the keystore file.", e);
+ } catch (NoSuchAlgorithmException e) {
+ throw new JWTClientException("No such algorithm found RS256.", e);
+ } catch (CertificateException e) {
+ throw new JWTClientException("Failed loading the certificate from the keystore.", e);
+ } catch (UnrecoverableKeyException e) {
+ throw new JWTClientException("Failed loading the keys from the keystore.", e);
+ } catch (JOSEException e) {
+ throw new JWTClientException(e);
+ } catch (Exception e) {
+ //This is thrown when loading default private key.
+ throw new JWTClientException("Failed loading the private key.", e);
+ }
+ }
+
+ private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
+ if (null == keystoreFile) {
+ throw new IllegalArgumentException("Keystore url may not be null");
+ }
+ URI keystoreUri = keystoreFile.toURI();
+ URL keystoreUrl = keystoreUri.toURL();
+ KeyStore keystore = KeyStore.getInstance(keyStoreType);
+ InputStream is = null;
+ try {
+ is = keystoreUrl.openStream();
+ keystore.load(is, null == password ? null : password.toCharArray());
+ } finally {
+ if (null != is) {
+ is.close();
+ }
+ }
+ return keystore;
+ }
}
diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java
index f7211fef132..93ab9c32a3b 100644
--- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java
+++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java
@@ -45,8 +45,6 @@ public class WebappAuthenticationValve extends CarbonTomcatValve {
return;
}
-
-
WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request);
if (authenticator == null) {
String msg = "Failed to load an appropriate authenticator to authenticate the request";
diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml
index 791f382a9c3..b728ed51ea1 100644
--- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml
+++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml
@@ -59,7 +59,7 @@
${project.build.directory}/maven-shared-archive-resources/webapps
- mdm-admin.war
+ devicemgt_admin.war
diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf
index ff61b588ecd..91d8294fa2b 100644
--- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf
+++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf
@@ -1,3 +1,3 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
-org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/mdm-admin.war,target:${installFolder}/../../deployment/server/webapps/mdm-admin.war,overwrite:true);\
\ No newline at end of file
+org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/devicemgt_admin.war,target:${installFolder}/../../deployment/server/webapps/devicemgt_admin.war,overwrite:true);\
\ No newline at end of file
diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml
index 175e970d1e8..ec7962494d4 100644
--- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml
+++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml
@@ -1,18 +1,18 @@
@@ -44,6 +44,11 @@
org.wso2.carbon.devicemgt
org.wso2.carbon.device.mgt.common
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.device.mgt.api.feature
+ zip
+
org.wso2.carbon.commons
org.wso2.carbon.email.verification
@@ -97,6 +102,11 @@
org.eclipse.equinox.p2.type.group:false
+
+
+ org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.api.feature:${carbon.device.mgt.version}
+
+
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.core:${carbon.device.mgt.version}
diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml
index 35d65d89f89..061dbdfdf61 100644
--- a/features/device-mgt/pom.xml
+++ b/features/device-mgt/pom.xml
@@ -1,21 +1,21 @@
+ ~ Copyright (c) 2016, 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.
+ -->
diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml
deleted file mode 100644
index 2741e45be00..00000000000
--- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/CDMF_DEFAULT_IDP.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-
- CDMF_DEFAULT_IDP
- CDMF_DEFAULT_IDP
-
- https://localhost:9443/oauth2/token
- true
-
-
-
-
-
-
-
-
-
-
-
-
- MIIFkzCCA3sCBAKkVfcwDQYJKoZIhvcNAQEFBQAwgY0xCzAJBgNVBAYTAlNMMRAwDgYDVQQIEwdXZXN0ZXJuMRAwDgYDVQQHEwdDb2xvbWJvMQ0wCwYDVQQKEwRXU08yMRQwEgYDVQQLEwtFbmdpbmVlcmluZzESMBAGA1UEAxMJbG9jYWxob3N0MSEwHwYJKoZIhvcNAQkBFhJpb3RzZXJ2ZXJAd3NvMi5jb20wHhcNMTUxMjE3MTMxMTA0WhcNMTcxMjE2MTMxMTA0WjCBjTELMAkGA1UEBhMCU0wxEDAOBgNVBAgTB1dlc3Rlcm4xEDAOBgNVBAcTB0NvbG9tYm8xDTALBgNVBAoTBFdTTzIxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRIwEAYDVQQDEwlsb2NhbGhvc3QxITAfBgkqhkiG9w0BCQEWEmlvdHNlcnZlckB3c28yLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALkiGVQ9tZOKIi/gD/toV+enq+neqOBGYQ8Fq/ABOWnK2QpGWm81+Rets5GbQ6W//D8C5TOBGqK7z+LAgdmILr1XLkvrXWoan0GPdDJ1wpc2/6XDZvM5f7Y8cmRqVPJv7AF+ImgF9dqv97gYCiujy+nNHd5Nk/60pco2LBV5SyLqqrzKXEnSGrS4zoYWpPeJ9YrXPEkW7A6AxTQK0yU9Ej4TktgafbTueythrLomKiZJj4wPxm2lA2lAZscDdws9NWrI5z/LUVLbUMxrY10Nig1liX5b1mrUk5bb1d2tqwkPrpRILKoOBJtI674SQS3GziiUiCJGIO/EGGRn1AJsC/SvnnEez3WKY/DgJ6102MWK/yWtY8NYHUX2anwMBS7UpT5A4BXdsfBz3R+iPF99FxdAGGsS4GQuuPocZaycLqoPCxpTSSxBsKMUcKpn3yaiQRd6uDuiTNt7odDOQj0Tno7uokh/HILgbzvj9EExDOsdwLVvqYmUHBPeLmiICWXfi4kyH/twPOZtV9eVnfWYx5Kwg+2Y4fIb3q4ABr0hzxaMYHQo6NOukSH1BcdAWiQIXbSFFaTZD8p6OfiZpHcQ59HT/Z8GBlCFL2xkYJFmOhXI/Cu+xrcwqEIInv7d8w3eiNQ7MneomEptLbBk9+kMsP0ubo34oOGHR9qk3Lj580c/AgMBAAEwDQYJKoZIhvcNAQEFBQADggIBADw70g2/wrgzrAM8OXBlthGbCEaXZpKwq9IJN0qu+/l+PNwF7csQhj+qW+zMrWaH1DGWJroaei1+NFFrj/pvp61rF/ZeTPGVJd7puCq++SevqIrzKyAEBtwtpXmcFhBpV/FrQAv3ODOJ3bN2wSRPZHUvARTBB3RaUI06g1jCaBzjDEGoMfSxdr5/Ty2WxTI9u9RlIs3Q52AiOmROtLPiEQZQIqfNO3cxCEWojHxPqVEZA/kQYy+rryj4H0zzSrj7QFlQhsMDw5j8bv9AcvTEGmwp29avsgnceDWinI6lwtd8zqh0ZW9QJdH0BRNCM/EkTlTUHeEg04/sOgOrlWcvEfVxDqNEtbUzU9UFxl0lkQkuRn1UdxZlvhWaFnel5iRC9b7OZvi2mkVujLyxEWlJB1tuyMLQxu6PfabBVODP5V8/+uyiiK/gwrB5rYl8RHxGoznJnI1Y3HVzKlA849CrMBaY5vnhE03cNja7QroPzLmmuXBLk2LbI1lu5nJAqKpBUPMI/IU3pF4Q7VTD2ZANI+ktGgGlM8AK4OJHWOhj8W289pWTHVjG8syPLTsaYkhgLjzZl/g9cUwn/96NJNvzd3dkT+7VgE+BJOLofq25CjZcN1M7MhWdl3vbWNj9vzL0+FCnwca8UecfvFS39PIekIvqbtP+Gw8NiYOUGIllZ0JH
-
-
-
-
\ No newline at end of file
diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties
index 503301fb80b..d6a1f0fc2be 100644
--- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties
+++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties
@@ -41,7 +41,7 @@ skew=0
#jti=token123
#KeyStore to cryptographic credentials
-#KeyStore=src/main/resources/wso2carbon.jks
+#KeyStore=repository/resources/security/wso2carbon.jks
#Password of the KeyStore
#KeyStorePassword=wso2carbon
@@ -52,3 +52,6 @@ skew=0
#Private key password to retrieve the private key used to sign
#AuthnRequest and LogoutRequest messages
#PrivateKeyPassword=wso2carbon
+
+#this will be used as the default IDP config if there isn't any config available for tenants.
+default-jwt-client=true
diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf
index 9e8c8bd070b..5678ff874ef 100644
--- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf
+++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/p2.inf
@@ -1,3 +1,2 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/jwt.properties,target:${installFolder}/../../conf/etc/jwt.properties,overwrite:true);\
-org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/CDMF_DEFAULT_IDP.xml,target:${installFolder}/../../conf/identity/identity-providers/CDMF_DEFAULT_IDP.xml,overwrite:true);\
diff --git a/pom.xml b/pom.xml
index ad4400d1584..c71293b0494 100644
--- a/pom.xml
+++ b/pom.xml
@@ -280,6 +280,12 @@
zip
${carbon.device.mgt.version}
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.device.mgt.api.feature
+ zip
+ ${carbon.device.mgt.version}
+
org.wso2.carbon.devicemgt
org.wso2.carbon.device.mgt.ui.feature
@@ -1390,13 +1396,6 @@
${carbon.analytics.common.version}
-
-
- org.wso2.carbon.analytics
- org.wso2.carbon.analytics.api
- ${carbon.analytics.version}
-
-
org.wso2.carbon.registry
@@ -1749,10 +1748,6 @@
5.0.11
[5.0.11,6.0.0)
-
- 1.0.5
- [1.0.5,2.0.0]
-
4.4.8
[4.4.8, 5.0.0)