Refactoring OAuth utilities at UI Layer

revert-70aa11f8
dilanua 8 years ago
parent 5e0f5cc406
commit 2efdc30177

@ -23,7 +23,7 @@ var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri)); var uriMatcher = new URIMatcher(String(uri));
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
function appendQueryParam (url, queryParam , value) { function appendQueryParam (url, queryParam , value) {
if (url.indexOf("?") > 0) { if (url.indexOf("?") > 0) {

@ -26,7 +26,7 @@ var deviceModule = require("/app/modules/device.js").deviceModule;
var utility = require("/app/modules/utility.js").utility; var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/user.js").userModule;
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY); var user = session.get(constants.USER_SESSION_KEY);
var result; var result;

@ -24,7 +24,7 @@ var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js").utility; var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var user = session.get(constants.USER_SESSION_KEY); var user = session.get(constants.USER_SESSION_KEY);
var result; var result;

@ -24,7 +24,7 @@ var uriMatcher = new URIMatcher(String(uri));
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
if (uriMatcher.match("/{context}/api/invoker/execute/")) { if (uriMatcher.match("/{context}/api/invoker/execute/")) {
var restAPIRequestDetails = request.getContent(); var restAPIRequestDetails = request.getContent();
@ -97,8 +97,8 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) {
break; break;
} }
} catch (e) { } catch (e) {
log.error("Exception occurred while trying to access backend " + throw new Error("Exception occurred while trying to access " +
"REST API services from Jaggery API invoker layer", e); "backend REST API services from Jaggery API invoker layer", e);
} }
} }
%> %>

@ -22,7 +22,7 @@ var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/operation-api.jag"); var log = new Log("api/operation-api.jag");
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/operation/paginate")) { if (uriMatcher.match("/{context}/api/operation/paginate")) {

@ -21,7 +21,7 @@
@Deprecated - new @Deprecated - new
*/ */
// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; // var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"];
// var tokenCookie = apiWrapperUtil.refreshToken(); // var tokenCookie = apiWrapperUtil.refreshToken();
// print(tokenCookie); // print(tokenCookie);
%> %>

@ -27,7 +27,7 @@ var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/user.js").userModule;
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/device.js").deviceModule;
var utility = require("/app/modules/utility.js").utility; var utility = require("/app/modules/utility.js").utility;
var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"];
var util = require("/app/modules/util.js").util; var util = require("/app/modules/util.js").util;
var responseProcessor = require('utils').response; var responseProcessor = require('utils').response;

@ -1,68 +1,89 @@
{ {
"appContext" : "/devicemgt/", "appContext": "/emm/",
"webAgentContext" : "/devicemgt-web-agent/", "webAgentContext" : "/emm-web-agent/",
"apiContext" : "api", "apiContext": "api",
"httpsURL" : "https://localhost:8243", "httpsURL" : "%https.ip%",
"httpURL" : "%http.ip%", "httpURL" : "%http.ip%",
"httpsWebURL" : "%https.ip%", "httpsWebURL" : "%https.ip%",
"wssURL" : "%https.ip%", "wssURL" : "%https.ip%",
"wsURL" : "%http.ip%", "wsURL" : "%http.ip%",
"dashboardserverURL" : "%https.ip%", "dashboardServerURL" : "%https.ip%",
"enrollmentDir": "/emm-web-agent/enrollment", "enrollmentDir": "/emm-web-agent/enrollment",
"iOSConfigRoot" : "%https.ip%/ios-enrollment/", "iOSConfigRoot" : "%https.ip%/ios-enrollment/",
"iOSAPIRoot" : "%https.ip%/ios/", "iOSAPIRoot" : "%https.ip%/ios/",
"dynamicClientRegistrationEndPoint" : "https://localhost:8243/dynamic-client-web/register/", "adminService": "%https.ip%",
"adminService":"%https.ip%", "oauthProvider": {
"idPServer":"https://localhost:8243", "appRegistration": {
"callBackUrl":"%https.ip%/devicemgt_admin", "appType": "webapp",
"adminUser":"admin@carbon.super", "clientName": "emm",
"adminRole":"admin", "owner": "admin@carbon.super",
"usernameLength":30, "dynamicClientAppRegistrationServiceURL": "%https.ip%/dynamic-client-web/register",
"ssoConfiguration" : { "apiManagerClientAppRegistrationServiceURL": "%https.ip%/api-application-registration/register/tenants",
"enabled" : false, "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
"issuer" : "devicemgt", "tokenScope": "admin",
"appName" : "devicemgt", "callbackUrl": "%https.ip%/api/device-mgt/v1.0"
"identityProviderURL" : "%https.ip%/sso/samlsso.jag", },
"responseSigningEnabled" : "true", "tokenServiceURL": "%https.ip%/oauth2/token"
"keyStorePassword" : "wso2carbon", },
"identityAlias" : "wso2carbon", "adminUser":"admin@carbon.super",
"keyStoreName" : "/repository/resources/security/wso2carbon.jks" "adminRole":"admin",
}, "usernameLength":30,
"userValidationConfig" : { "pageSize":10,
"usernameJSRegEx" : "^[\\S]{3,30}$", "ssoConfiguration" : {
"usernameRegExViolationErrorMsg" : "Provided username is invalid.", "enabled" : false,
"usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.", "issuer" : "devicemgt",
"firstnameJSRegEx" : "^[\\S]{3,30}$", "appName" : "devicemgt",
"firstnameRegExViolationErrorMsg" : "Provided first name is invalid.", "identityProviderURL" : "%https.ip%/sso/samlsso.jag",
"lastnameJSRegEx" : "^[\\S]{3,30}$", "responseSigningEnabled" : "true",
"lastnameRegExViolationErrorMsg" : "Provided last name is invalid.", "keyStorePassword" : "wso2carbon",
"emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", "identityAlias" : "wso2carbon",
"emailRegExViolationErrorMsg" : "Provided email is invalid." "keyStoreName" : "/repository/resources/security/wso2carbon.jks"
}, },
"groupValidationConfig": { "userValidationConfig" : {
"groupNameJSRegEx": "^[\\S]{3,30}$", "usernameJSRegEx" : "^[\\S]{3,30}$",
"groupNameRegExViolationErrorMsg": "Provided group name is invalid.", "usernameRegExViolationErrorMsg" : "Provided username is invalid.",
"groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." "usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.",
}, "firstnameJSRegEx" : "^[\\S]{3,30}$",
"roleValidationConfig" : { "firstnameRegExViolationErrorMsg" : "Provided first name is invalid.",
"rolenameJSRegEx" : "^[\\S]{3,30}$", "lastnameJSRegEx" : "^[\\S]{3,30}$",
"rolenameRegExViolationErrorMsg" : "Provided role name is invalid.", "lastnameRegExViolationErrorMsg" : "Provided last name is invalid.",
"rolenameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces." "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",
}, "emailRegExViolationErrorMsg" : "Provided email is invalid."
"generalConfig" : { },
"host" : "https://localhost:9443", "groupValidationConfig": {
"companyName" : "WSO2 Carbon Device Manager", "groupNameJSRegEx": "^[\\S]{3,30}$",
"browserTitle" : "WSO2 Device Manager", "groupNameRegExViolationErrorMsg": "Provided group name is invalid.",
"copyrightPrefix" : "\u00A9 %date-year%, ", "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces."
"copyrightOwner" : "WSO2 Inc.", },
"copyrightOwnersSite" : "http://www.wso2.org", "roleValidationConfig" : {
"copyrightSuffix" : " All Rights Reserved." "roleNameJSRegEx" : "^[\\S]{3,30}$",
}, "roleNameRegExViolationErrorMsg" : "Provided role name is invalid.",
"scopes" : ["license-add", "license-view", "device-view", "device-info", "device-list", "device-view-own", "roleNameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces."
"device-modify", "device-search", "operation-install", "operation-view", "operation-modify", "operation-uninstall", },
"group-add", "group-share", "group-modify", "group-view", "group-remove", "certificate-modify", "certificate-view", "generalConfig" : {
"configuration-view", "configuration-modify", "policy-view", "policy-modify", "device-notification-view", "host" : "https://localhost:9443",
"device-notification-modify", "feature-view", "arduino_device", "arduino_user", " android_sense_user", "companyName" : "WSO2 Carbon Device Manager",
"virtual_firealarm_user", "raspberrypi_user", "roles-view", "roles-modify", "roles-remove", "roles-add", "browserTitle" : "WSO2 Device Manager",
"user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"] "copyrightPrefix" : "\u00A9 %date-year%, ",
"copyrightOwner" : "WSO2 Inc.",
"copyrightOwnersSite" : "http://www.wso2.org",
"copyrightSuffix" : " All Rights Reserved."
},
"scopes" : [
"license-add", "license-view", "device-view",
"device-info", "device-list", "device-view-own", "device-modify", "device-search",
"operation-install", "operation-view", "operation-modify", "operation-uninstall",
"group-add", "group-share", "group-modify", "group-view", "group-remove",
"certificate-modify", "certificate-view",
"configuration-view", "configuration-modify",
"policy-view", "policy-modify",
"device-notification-view", "device-notification-modify",
"feature-view",
"roles-view", "roles-modify", "roles-remove", "roles-add",
"user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"
],
"isOAuthEnabled" : true,
"backendRestEndpoints" : {
"deviceMgt" : "/api/device-mgt/v1.0"
}
} }

@ -23,7 +23,7 @@ deviceModule = function () {
var utility = require('/app/modules/utility.js').utility; var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js'); var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var ArrayList = Packages.java.util.ArrayList; var ArrayList = Packages.java.util.ArrayList;
var Properties = Packages.java.util.Properties; var Properties = Packages.java.util.Properties;

@ -24,7 +24,7 @@ var groupModule = {};
var constants = require('/app/modules/constants.js'); var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var utility = require("/app/modules/utility.js").utility; var utility = require("/app/modules/utility.js").utility;
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups"; var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups";

@ -26,7 +26,7 @@
//var invokerRequestWrapper = function () { //var invokerRequestWrapper = function () {
// //
// var constants = require("/modules/constants.js"); // var constants = require("/modules/constants.js");
// var serviceInvokers = require("/modules/backend-service-invoker.js").backendServiceInvoker; // var serviceInvokers = require("/modules/token-protected-service-invokers.js").backendServiceInvoker;
// //
// var publicWrappers = []; // var publicWrappers = [];
// //

@ -24,7 +24,7 @@ var onFail;
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
onSuccess = function (context) { onSuccess = function (context) {
var utility = require("/app/modules/utility.js").utility; var utility = require("/app/modules/utility.js").utility;
var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"];
if (context.input.samlToken) { if (context.input.samlToken) {
apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken);
} else { } else {

@ -21,7 +21,7 @@ var operationModule = function () {
var utility = require('/app/modules/utility.js').utility; var utility = require('/app/modules/utility.js').utility;
var constants = require('/app/modules/constants.js'); var constants = require('/app/modules/constants.js');
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];;
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};

@ -26,7 +26,7 @@ policyModule = function () {
var constants = require('/app/modules/constants.js'); var constants = require('/app/modules/constants.js');
var utility = require("/app/modules/utility.js")["utility"]; var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};

@ -17,11 +17,10 @@
*/ */
/** /**
* ---------------------------------------------------------------------------- * -----------------------------------------------------
* Following module includes invokers * Following module includes handlers
* at Jaggery Layer for calling Backend Services, protected by OAuth Tokens. * at Jaggery Layer for handling OAuth tokens.
* These Services include both REST and SOAP Services. * -----------------------------------------------------
* ----------------------------------------------------------------------------
*/ */
var handlers = function () { var handlers = function () {
var log = new Log("/app/modules/token-handlers.js"); var log = new Log("/app/modules/token-handlers.js");
@ -39,19 +38,20 @@ var handlers = function () {
"client credentials to session context. No username is found as " + "client credentials to session context. No username is found as " +
"input - setUpEncodedTenantBasedClientCredentials(x)"); "input - setUpEncodedTenantBasedClientCredentials(x)");
} else { } else {
var dynamicClientCredentials = tokenUtil.getDynamicClientCredentials(); var dynamicClientCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientCredentials) { if (!dynamicClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " + "client credentials to session context as the server is unable to obtain " +
"dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)"); "dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)");
} else { } else {
var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientCredentials);
if (!jwtToken) { if (!jwtToken) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " + "client credentials to session context as the server is unable to obtain " +
"a jwt token - setUpEncodedTenantBasedClientCredentials(x)"); "a jwt token - setUpEncodedTenantBasedClientCredentials(x)");
} else { } else {
var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken); var tenantBasedClientCredentials = tokenUtil.
getTenantBasedClientAppCredentials(username, jwtToken);
if (!tenantBasedClientCredentials) { if (!tenantBasedClientCredentials) {
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " + throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " + "based client credentials to session context as the server is unable " +
@ -89,7 +89,7 @@ var handlers = function () {
stringOfScopes += entry + " "; stringOfScopes += entry + " ";
}); });
accessTokenPair = tokenUtil. accessTokenPair = tokenUtil.
getTokenWithPasswordGrantType(username, getAccessTokenByPasswordGrantType(username,
encodeURIComponent(password), encodedClientCredentials, stringOfScopes); encodeURIComponent(password), encodedClientCredentials, stringOfScopes);
if (!accessTokenPair) { if (!accessTokenPair) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access " + throw new Error("{/app/modules/token-handlers.js} Could not set up access " +
@ -119,7 +119,7 @@ var handlers = function () {
var accessTokenPair; var accessTokenPair;
// accessTokenPair will include current access token as well as current refresh token // accessTokenPair will include current access token as well as current refresh token
accessTokenPair = tokenUtil. accessTokenPair = tokenUtil.
getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); getAccessTokenBySAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION");
if (!accessTokenPair) { if (!accessTokenPair) {
throw new Error("{/app/modules/token-handlers.js} Could not set up access token " + throw new Error("{/app/modules/token-handlers.js} Could not set up access token " +
"pair by password grant type. Error in token " + "pair by password grant type. Error in token " +
@ -141,7 +141,7 @@ var handlers = function () {
"token pair, encoded client credentials or both input are not found under " + "token pair, encoded client credentials or both input are not found under " +
"session context - refreshToken()"); "session context - refreshToken()");
} else { } else {
var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair["refreshToken"], encodedClientCredentials);
if (!newAccessTokenPair) { if (!newAccessTokenPair) {
log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " + log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " +
"session context with new access token pair - refreshToken()"); "session context with new access token pair - refreshToken()");

@ -24,7 +24,7 @@
* ---------------------------------------------------------------------------- * ----------------------------------------------------------------------------
*/ */
var invokers = function () { var invokers = function () {
var log = new Log("/app/modules/backend-service-invoker.js"); var log = new Log("/app/modules/token-protected-service-invokers.js");
var publicXMLHTTPInvokers = {}; var publicXMLHTTPInvokers = {};
var publicHTTPClientInvokers = {}; var publicHTTPClientInvokers = {};
@ -38,7 +38,7 @@ var invokers = function () {
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/user.js")["userModule"];
var tokenUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; var tokenUtil = require("/app/modules/token-handlers.js")["handlers"];
/** /**
* This method reads the token pair from the session and return the access token. * This method reads the token pair from the session and return the access token.

@ -25,7 +25,7 @@ var userModule = function () {
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js")["utility"]; var utility = require("/app/modules/utility.js")["utility"];
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];
/* Initializing user manager */ /* Initializing user manager */
var carbon = require("carbon"); var carbon = require("carbon");

@ -1,226 +1,285 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* KIND, either express or implied. See the License for the * either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
var util = function () { var util = function () {
var log = new Log("/app/modules/util.js"); var log = new Log("/app/modules/util.js");
var module = {};
var privateMethods = {};
var publicMethods = {};
var Base64 = Packages.org.apache.commons.codec.binary.Base64; var Base64 = Packages.org.apache.commons.codec.binary.Base64;
var String = Packages.java.lang.String; var String = Packages.java.lang.String;
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var deviceMgtProps = require("/app/conf/reader/main.js")["conf"];
var carbon = require('carbon');
var adminUser = deviceMgtProps["adminUser"];
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var adminUser = devicemgtProps["adminUser"]; var carbon = require("carbon");
var clientName = devicemgtProps["clientName"];
publicMethods.encode = function (payload) {
module.getDynamicClientCredentials = function () { return new String(Base64.encodeBase64(new String(payload).getBytes()));
var payload = { };
"callbackUrl": devicemgtProps.callBackUrl,
"clientName": clientName, publicMethods.decode = function (payload) {
"tokenScope": "admin", return new String(Base64.decodeBase64(new String(payload).getBytes()));
"owner": adminUser, };
"applicationType": "webapp",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer", publicMethods.getDynamicClientAppCredentials = function () {
"saasApp" :true // setting up dynamic client application properties
var dcAppProperties = {
"applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"],
"clientName": deviceMgtProps["oauthProvider"]["appRegistration"]["clientName"],
"owner": deviceMgtProps["oauthProvider"]["appRegistration"]["owner"],
"tokenScope": deviceMgtProps["oauthProvider"]["appRegistration"]["tokenScope"],
"grantType": deviceMgtProps["oauthProvider"]["appRegistration"]["grantType"],
"callbackUrl": deviceMgtProps["oauthProvider"]["appRegistration"]["callbackUrl"],
"saasApp" : true
}; };
// calling dynamic client app registration service endpoint
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["dynamicClientAppRegistrationServiceURL"];
var requestPayload = dcAppProperties;
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.dynamicClientRegistrationEndPoint; xhr.open("POST", requestURL, false);
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(payload); xhr.send(stringify(requestPayload));
var clientData = {};
if (xhr.status == 201) { var dynamicClientCredentials = {};
var data = parse(xhr.responseText); if (xhr["status"] == 201 && xhr["responseText"]) {
clientData.clientId = data.client_id; var responsePayload = parse(xhr["responseText"]);
clientData.clientSecret = data.client_secret; dynamicClientCredentials["clientId"] = responsePayload["client_id"];
dynamicClientCredentials["clientSecret"] = responsePayload["client_secret"];
} else if (xhr.status == 400) { } else if (xhr["status"] == 400) {
throw "Invalid client meta data"; log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " +
"Bad request. Invalid data provided as dynamic client application properties.");
dynamicClientCredentials = null;
} else { } else {
throw "Error in obtaining client id and secret"; log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " +
"Error in retrieving dynamic client credentials.");
dynamicClientCredentials = null;
} }
return clientData; // returning dynamic client credentials
return dynamicClientCredentials;
}; };
/** publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientCredentials, scopes) {
* Encode the payload in Base64 if (!username || !password || !encodedClientCredentials || !scopes) {
* @param payload log.error("{/app/modules/util.js} Error in retrieving access token by password " +
* @returns {Packages.java.lang.String} "grant type. No username, password, encoded client credentials or scopes are " +
*/ "found - getAccessTokenByPasswordGrantType(a, b, c, d)");
module.encode = function (payload) {
return new String(Base64.encodeBase64(new String(payload).getBytes()));
}
module.decode = function (payload) {
return new String(Base64.decodeBase64(new String(payload).getBytes()));
}
/**
* Get an AccessToken pair based on username and password
* @param username
* @param password
* @param clientId
* @param clientSecret
* @param scope
* @returns {{accessToken: "", refreshToken: ""}}
*/
module.getTokenWithPasswordGrantType = function (username, password, encodedClientKeys, scope) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = devicemgtProps.idPServer;
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys);
xhr.send("grant_type=password&username=" + username + "&password=" + password + "&scope=" + scope);
delete password, delete clientSecret, delete encodedClientKeys;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 403) {
log.error("Error in obtaining token with Password grant type");
return null; return null;
} else { } else {
log.error("Error in obtaining token with Password grant type"); // calling oauth provider token service endpoint
return null; var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=password&username=" +
username + "&password=" + password + "&scope=" + scopes;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/util.js} Error in retrieving access token by password " +
"grant type - getAccessTokenByPasswordGrantType(a, b, c, d)");
return null;
}
} }
return tokenPair;
}; };
module.getTokenWithSAMLGrantType = function (assertion, clientKeys, scope) {
publicMethods.getAccessTokenBySAMLGrantType = function (assertion, encodedClientCredentials, scopes) {
var assertionXML = module.decode(assertion) ; if (!assertion || !encodedClientCredentials || !scopes) {
var encodedExtractedAssertion; log.error("{/app/modules/util.js} Error in retrieving access token by saml " +
var extractedAssertion; "grant type. No assertion, encoded client credentials or scopes are " +
//TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem to add formatting "found - getAccessTokenBySAMLGrantType(x, y, z)");
//which causes signature verification to fail. return null;
var assertionStartMarker = "<saml2:Assertion";
var assertionEndMarker = "<\/saml2:Assertion>";
var assertionStartIndex = assertionXML.indexOf(assertionStartMarker);
var assertionEndIndex = assertionXML.indexOf(assertionEndMarker);
if (assertionStartIndex != -1 && assertionEndIndex != -1) {
extractedAssertion = assertionXML.substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
} else { } else {
throw "Invalid SAML response. SAML response has no valid assertion string"; var assertionXML = publicMethods.decode(assertion);
} /*
TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem
to add formatting which causes signature verification to fail.
*/
var assertionStartMarker = "<saml2:Assertion";
var assertionEndMarker = "<\/saml2:Assertion>";
var assertionStartIndex = assertionXML.indexOf(assertionStartMarker);
var assertionEndIndex = assertionXML.indexOf(assertionEndMarker);
encodedExtractedAssertion = this.encode(extractedAssertion); var extractedAssertion;
if (assertionStartIndex == -1 || assertionEndIndex == -1) {
log.error("{/app/modules/util.js} Error in retrieving access token by saml grant type. " +
"Issue in assertion format - getAccessTokenBySAMLGrantType(x, y, z)");
return null;
} else {
extractedAssertion = assertionXML.
substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
var encodedAssertion = publicMethods.encode(extractedAssertion);
var xhr = new XMLHttpRequest(); // calling oauth provider token service endpoint
var tokenEndpoint = devicemgtProps.idPServer; var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
xhr.open("POST", tokenEndpoint, false); var requestPayload = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&" +
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); "assertion=" + encodeURIComponent(encodedAssertion) + "&scope=" + scopes;
xhr.setRequestHeader("Authorization", "Basic " + clientKeys);
xhr.send("grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" + var xhr = new XMLHttpRequest();
encodeURIComponent(encodedExtractedAssertion) + "&scope=" + "PRODUCTION"); xhr.open("POST", requestURL, false);
var tokenPair = {}; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (xhr.status == 200) { xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials);
var data = parse(xhr.responseText); xhr.send(requestPayload);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token; if (xhr["status"] == 200 && xhr["responseText"]) {
} else if (xhr.status == 403) { var responsePayload = parse(xhr["responseText"]);
throw "Error in obtaining token with SAML extension grant type"; var tokenPair = {};
} else { tokenPair["accessToken"] = responsePayload["access_token"];
throw "Error in obtaining token with SAML extension grant type"; tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/util.js} Error in retrieving access token by password " +
"grant type - getAccessTokenBySAMLGrantType(x, y, z)");
return null;
}
}
} }
return tokenPair;
}; };
module.refreshToken = function (tokenPair, clientData, scope) { publicMethods.getNewAccessTokenByRefreshToken = function (refreshToken, encodedClientCredentials, scopes) {
var xhr = new XMLHttpRequest(); if (!refreshToken || !encodedClientCredentials) {
var tokenEndpoint = devicemgtProps.idPServer; log.error("{/app/modules/util.js} Error in retrieving new access token by current " +
xhr.open("POST", tokenEndpoint, false); "refresh token. No refresh token or encoded client credentials are " +
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); "found - getNewAccessTokenByRefreshToken(x, y, z)");
xhr.setRequestHeader("Authorization", "Basic " + clientData); return null;
var url = "grant_type=refresh_token&refresh_token=" + tokenPair.refreshToken;
if (scope) {
url = url + "&scope=" + scope
}
xhr.send(url);
delete clientData;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 400) {
tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
} else if (xhr.status == 403) {
throw "Error in obtaining token with Refresh Token Grant Type";
} else { } else {
throw "Error in obtaining token with Refresh Token Type"; var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
var requestPayload = "grant_type=refresh_token&refresh_token=" + refreshToken;
if (scopes) {
requestPayload = requestPayload + "&scope=" + scopes;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials);
xhr.send(requestPayload);
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tokenPair = {};
tokenPair["accessToken"] = responsePayload["access_token"];
tokenPair["refreshToken"] = responsePayload["refresh_token"];
return tokenPair;
} else {
log.error("{/app/modules/util.js} Error in retrieving new access token by " +
"current refresh token - getNewAccessTokenByRefreshToken(x, y, z)");
return null;
}
} }
return tokenPair;
}; };
module.getTokenWithJWTGrantType = function (clientData) { publicMethods.getAccessTokenByJWTGrantType = function (clientCredentials) {
var jwtService = carbon.server.osgiService('org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService'); if (!clientCredentials) {
var jwtClient = jwtService.getJWTClient(); log.error("{/app/modules/util.js} Error in retrieving new access token by current refresh " +
var jwtToken = jwtClient.getAccessToken(clientData.clientId, clientData.clientSecret, adminUser, null); "token. No client credentials are found as input - getAccessTokenByJWTGrantType(x)");
return jwtToken; return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
return jwtClient.getAccessToken(clientCredentials["clientId"], clientCredentials["clientSecret"],
deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"];
}
}; };
module.getTenantBasedAppCredentials = function (uname, token) { publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) {
var tenantDomain = carbonModule.server.tenantDomain({ if (!username || !jwtToken) {
username: uname log.error("{/app/modules/util.js} Error in retrieving tenant based client application credentials. " +
}); "No username or jwt token is found as input - getTenantBasedClientAppCredentials(x, y)");
var clientData = this.getCachedCredentials(tenantDomain); return null;
if (!clientData) { } else {
var applicationName = "webapp_" + tenantDomain; var tenantDomain = carbon.server.tenantDomain({username: username});
var xhr = new XMLHttpRequest(); if (!tenantDomain) {
var endpoint = devicemgtProps["adminService"] + "/api-application-registration/register/tenants?tenantDomain=" + log.error("{/app/modules/util.js} Error in retrieving tenant based client application " +
tenantDomain + "&applicationName=" + applicationName; "credentials. Unable to obtain a valid tenant domain for provided " +
xhr.open("POST", endpoint, false); "username - getTenantBasedClientAppCredentials(x, y)");
xhr.setRequestHeader("Content-Type", "application/json"); return null;
xhr.setRequestHeader("Authorization", "Bearer " + token.accessToken);
xhr.send();
if (xhr.status == 201) {
var data = parse(xhr.responseText);
clientData = {};
clientData.clientId = data.client_id;
clientData.clientSecret = data.client_secret;
this.setTenantBasedAppCredentials(tenantDomain, clientData);
} else if (xhr.status == 400) {
throw "Invalid client meta data";
} else { } else {
throw "Error in obtaining client id and secret from APIM"; var cachedTenantBasedClientAppCredentials = publicMethods.
getCachedTenantBasedClientAppCredentials(tenantDomain);
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} else {
// register a tenant based client app at API Manager
var applicationName = "webapp_" + tenantDomain;
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"] +
"?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + jwtToken);
xhr.send();
if (xhr["status"] == 201 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantBasedClientAppCredentials = {};
tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"];
tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
publicMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
return tenantBasedClientAppCredentials;
} else {
log.error("{/app/modules/util.js} Error in retrieving tenant based client " +
"application credentials from API Manager - getTenantBasedClientAppCredentials(x, y)");
return null;
}
}
} }
} }
return clientData;
}; };
module.setTenantBasedAppCredentials = function (tenantDomain, clientData) { publicMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientCredentials) {
var cachedMap = application.get(constants.CACHED_CREDENTIALS); var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (!cachedMap) { if (!cachedTenantBasedClientAppCredentialsMap) {
cachedMap = new Object(); cachedTenantBasedClientAppCredentialsMap = {};
cachedMap[tenantDomain] = clientData; cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientCredentials;
application.put(constants.CACHED_CREDENTIALS, cachedMap); application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap);
} else { } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
cachedMap[tenantDomain] = clientData; cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientCredentials;
} }
}; };
module.getCachedCredentials = function(tenantDomain) { publicMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) {
var cachedMap = application.get(constants.CACHED_CREDENTIALS); var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
if (cachedMap) { if (!cachedTenantBasedClientAppCredentialsMap ||
return cachedMap[tenantDomain]; !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
} }
return null;
}; };
return module; return publicMethods;
}(); }();

Loading…
Cancel
Save