forked from community/device-mgt-core
Merge branch 'master' of https://github.com/wso2/carbon-device-mgt into scope-impl
commit
ccdcea0109
@ -1,27 +0,0 @@
|
||||
<%
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
@Deprecated - new
|
||||
*/
|
||||
|
||||
// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"];
|
||||
// var tokenCookie = apiWrapperUtil.refreshToken();
|
||||
// print(tokenCookie);
|
||||
%>
|
@ -1,155 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* ----------------------------------------------------------------------------
|
||||
* Following module includes invokers
|
||||
* at Jaggery Layer for calling Backend Services, protected by OAuth Tokens.
|
||||
* These Services include both REST and SOAP Services.
|
||||
* ----------------------------------------------------------------------------
|
||||
*/
|
||||
var handlers = function () {
|
||||
var log = new Log("/app/modules/token-handlers.js");
|
||||
|
||||
var tokenUtil = require("/app/modules/util.js")["util"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
|
||||
|
||||
var privateMethods = {};
|
||||
var publicMethods = {};
|
||||
|
||||
privateMethods.setUpEncodedTenantBasedClientCredentials = function (username) {
|
||||
if (!username) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " +
|
||||
"client credentials to session context. No username is found as " +
|
||||
"input - setUpEncodedTenantBasedClientCredentials(x)");
|
||||
} else {
|
||||
var dynamicClientCredentials = tokenUtil.getDynamicClientCredentials();
|
||||
if (!dynamicClientCredentials) {
|
||||
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 " +
|
||||
"dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)");
|
||||
} else {
|
||||
var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials);
|
||||
if (!jwtToken) {
|
||||
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 " +
|
||||
"a jwt token - setUpEncodedTenantBasedClientCredentials(x)");
|
||||
} else {
|
||||
var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken);
|
||||
if (!tenantBasedClientCredentials) {
|
||||
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 such credentials - setUpEncodedTenantBasedClientCredentials(x)");
|
||||
} else {
|
||||
var encodedTenantBasedClientCredentials =
|
||||
tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" +
|
||||
tenantBasedClientCredentials["clientSecret"]);
|
||||
// setting up encoded tenant based client credentials to session context.
|
||||
session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) {
|
||||
if (!username || !password) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
|
||||
"password grant type. Either username, password or both are missing as " +
|
||||
"input - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
privateMethods.setUpEncodedTenantBasedClientCredentials(username);
|
||||
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
|
||||
if (!encodedClientCredentials) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
|
||||
"password grant type. Encoded client credentials are " +
|
||||
"missing - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
var accessTokenPair;
|
||||
// accessTokenPair will include current access token as well as current refresh token
|
||||
var arrayOfScopes = devicemgtProps["scopes"];
|
||||
var stringOfScopes = "";
|
||||
arrayOfScopes.forEach(function (entry) {
|
||||
stringOfScopes += entry + " ";
|
||||
});
|
||||
accessTokenPair = tokenUtil.
|
||||
getTokenWithPasswordGrantType(username,
|
||||
encodeURIComponent(password), encodedClientCredentials, stringOfScopes);
|
||||
if (!accessTokenPair) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access " +
|
||||
"token pair by password grant type. Error in token " +
|
||||
"retrieval - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
// setting up access token pair into session context as a string
|
||||
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) {
|
||||
if (!username || !samlToken) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " +
|
||||
"saml grant type. Either username, samlToken or both are missing as " +
|
||||
"input - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
privateMethods.setUpEncodedTenantBasedClientCredentials(username);
|
||||
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
|
||||
if (!encodedClientCredentials) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair " +
|
||||
"by saml grant type. Encoded client credentials are " +
|
||||
"missing - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
var accessTokenPair;
|
||||
// accessTokenPair will include current access token as well as current refresh token
|
||||
accessTokenPair = tokenUtil.
|
||||
getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION");
|
||||
if (!accessTokenPair) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Could not set up access token " +
|
||||
"pair by password grant type. Error in token " +
|
||||
"retrieval - setupAccessTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
// setting up access token pair into session context as a string
|
||||
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.refreshToken = function () {
|
||||
var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"]));
|
||||
// accessTokenPair includes current access token as well as current refresh token
|
||||
var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]);
|
||||
if (!accessTokenPair || !encodedClientCredentials) {
|
||||
throw new Error("{/app/modules/token-handlers.js} Error in refreshing tokens. Either the access " +
|
||||
"token pair, encoded client credentials or both input are not found under " +
|
||||
"session context - refreshToken()");
|
||||
} else {
|
||||
var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials);
|
||||
if (!newAccessTokenPair) {
|
||||
log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " +
|
||||
"session context with new access token pair - refreshToken()");
|
||||
} else {
|
||||
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newAccessTokenPair));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
@Deprecated - new
|
||||
*/
|
||||
|
||||
/**
|
||||
* This invokerRequestWrapper contains the wrappers for invoker util requests.
|
||||
*/
|
||||
//var invokerRequestWrapper = function () {
|
||||
//
|
||||
// var constants = require("/modules/constants.js");
|
||||
// var serviceInvokers = require("/modules/backend-service-invoker.js").backendServiceInvoker;
|
||||
//
|
||||
// var publicWrappers = [];
|
||||
//
|
||||
// publicWrappers.initiate = function (method, url, payload) {
|
||||
// switch (method) {
|
||||
// case constants.HTTP_GET:
|
||||
// var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload["responseContent"];
|
||||
// response.status = "success";
|
||||
// return response;
|
||||
// },
|
||||
// function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload;
|
||||
// response.status = "error";
|
||||
// return response;
|
||||
// });
|
||||
// return response;
|
||||
// break;
|
||||
// case constants.HTTP_POST:
|
||||
// var response = serviceInvokers.XMLHttp.post(url, payload, function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload["responseContent"];
|
||||
// response.status = "success";
|
||||
// return response;
|
||||
// },
|
||||
// function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload;
|
||||
// response.status = "error";
|
||||
// return response;
|
||||
// });
|
||||
// return response;
|
||||
// break;
|
||||
// case constants.HTTP_PUT:
|
||||
// var response = serviceInvokers.XMLHttp.put(url, payload, function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload["responseContent"];
|
||||
// response.status = "success";
|
||||
// return response;
|
||||
// },
|
||||
// function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload;
|
||||
// response.status = "error";
|
||||
// return response;
|
||||
// });
|
||||
// return response;
|
||||
// break;
|
||||
// case constants.HTTP_DELETE:
|
||||
// var response = serviceInvokers.XMLHttp.delete(url, function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload["responseContent"];
|
||||
// response.status = "success";
|
||||
// return response;
|
||||
// },
|
||||
// function (responsePayload) {
|
||||
// var response = {};
|
||||
// response.content = responsePayload;
|
||||
// response.status = "error";
|
||||
// return response;
|
||||
// });
|
||||
// return response;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//}();
|
@ -0,0 +1,286 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
var utils = function () {
|
||||
var log = new Log("/app/modules/oauth/token-handler-utils.js");
|
||||
|
||||
var deviceMgtProps = require("/app/conf/reader/main.js")["conf"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var carbon = require("carbon");
|
||||
|
||||
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
|
||||
var String = Packages.java.lang.String;
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
publicMethods.encode = function (payload) {
|
||||
return new String(Base64.encodeBase64(new String(payload).getBytes()));
|
||||
};
|
||||
|
||||
publicMethods.decode = function (payload) {
|
||||
return new String(Base64.decodeBase64(new String(payload).getBytes()));
|
||||
};
|
||||
|
||||
publicMethods.getDynamicClientAppCredentials = function () {
|
||||
// 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();
|
||||
xhr.open("POST", requestURL, false);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
xhr.send(stringify(requestPayload));
|
||||
|
||||
var dynamicClientAppCredentials = {};
|
||||
if (xhr["status"] == 201 && xhr["responseText"]) {
|
||||
var responsePayload = parse(xhr["responseText"]);
|
||||
dynamicClientAppCredentials["clientId"] = responsePayload["client_id"];
|
||||
dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"];
|
||||
} else if (xhr["status"] == 400) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
|
||||
"Bad request. Invalid data provided as dynamic client application properties.");
|
||||
dynamicClientAppCredentials = null;
|
||||
} else {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
|
||||
"Error in retrieving dynamic client credentials.");
|
||||
dynamicClientAppCredentials = null;
|
||||
}
|
||||
// returning dynamic client credentials
|
||||
return dynamicClientAppCredentials;
|
||||
};
|
||||
|
||||
publicMethods.getTokenPairByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) {
|
||||
if (!username || !password || !encodedClientAppCredentials || !scopes) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " +
|
||||
"grant type. No username, password, encoded client app credentials or scopes are " +
|
||||
"found - getTokenPairByPasswordGrantType(a, b, c, d)");
|
||||
return null;
|
||||
} else {
|
||||
// calling oauth provider token service endpoint
|
||||
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 " + encodedClientAppCredentials);
|
||||
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/oauth/token-handler-utils.js} Error in retrieving access token " +
|
||||
"by password grant type - getTokenPairByPasswordGrantType(a, b, c, d)");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getTokenPairBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) {
|
||||
if (!assertion || !encodedClientAppCredentials || !scopes) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " +
|
||||
"grant type. No assertion, encoded client app credentials or scopes are " +
|
||||
"found - getTokenPairBySAMLGrantType(x, y, z)");
|
||||
return null;
|
||||
} else {
|
||||
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);
|
||||
|
||||
var extractedAssertion;
|
||||
if (assertionStartIndex == -1 || assertionEndIndex == -1) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access " +
|
||||
"token by saml grant type. Issue in assertion format - getTokenPairBySAMLGrantType(x, y, z)");
|
||||
return null;
|
||||
} else {
|
||||
extractedAssertion = assertionXML.
|
||||
substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
|
||||
var encodedAssertion = publicMethods.encode(extractedAssertion);
|
||||
|
||||
// calling oauth provider token service endpoint
|
||||
var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"];
|
||||
var requestPayload = "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&" +
|
||||
"assertion=" + encodeURIComponent(encodedAssertion) + "&scope=" + scopes;
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", requestURL, false);
|
||||
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
|
||||
xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials);
|
||||
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/oauth/token-handler-utils.js} Error in retrieving access token " +
|
||||
"by password grant type - getTokenPairBySAMLGrantType(x, y, z)");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getNewTokenPairByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) {
|
||||
if (!refreshToken || !encodedClientAppCredentials) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
|
||||
"by current refresh token. No refresh token or encoded client app credentials are " +
|
||||
"found - getNewTokenPairByRefreshToken(x, y, z)");
|
||||
return null;
|
||||
} else {
|
||||
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 " + encodedClientAppCredentials);
|
||||
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/oauth/token-handler-utils.js} Error in retrieving new access token by " +
|
||||
"current refresh token - getNewTokenPairByRefreshToken(x, y, z)");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) {
|
||||
if (!clientAppCredentials) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " +
|
||||
"by current refresh token. No client app credentials are found " +
|
||||
"as input - getAccessTokenByJWTGrantType(x)");
|
||||
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(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
|
||||
deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"];
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) {
|
||||
if (!username || !jwtToken) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
|
||||
"based client app credentials. No username or jwt token is found " +
|
||||
"as input - getTenantBasedClientAppCredentials(x, y)");
|
||||
return null;
|
||||
} else {
|
||||
var tenantDomain = carbon.server.tenantDomain({username: username});
|
||||
if (!tenantDomain) {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
|
||||
"based client application credentials. Unable to obtain a valid tenant domain for provided " +
|
||||
"username - getTenantBasedClientAppCredentials(x, y)");
|
||||
return null;
|
||||
} else {
|
||||
var cachedTenantBasedClientAppCredentials = privateMethods.
|
||||
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"];
|
||||
privateMethods.
|
||||
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
|
||||
return tenantBasedClientAppCredentials;
|
||||
} else {
|
||||
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
|
||||
"based client application credentials from API " +
|
||||
"Manager - getTenantBasedClientAppCredentials(x, y)");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientAppCredentials) {
|
||||
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
|
||||
if (!cachedTenantBasedClientAppCredentialsMap) {
|
||||
cachedTenantBasedClientAppCredentialsMap = {};
|
||||
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
|
||||
application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap);
|
||||
} else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
|
||||
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
|
||||
}
|
||||
};
|
||||
|
||||
privateMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) {
|
||||
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]);
|
||||
if (!cachedTenantBasedClientAppCredentialsMap ||
|
||||
!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
|
||||
return null;
|
||||
} else {
|
||||
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
|
||||
}
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
* either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* -----------------------------------------------------
|
||||
* Following module includes handlers
|
||||
* at Jaggery Layer for handling OAuth tokens.
|
||||
* -----------------------------------------------------
|
||||
*/
|
||||
var handlers = function () {
|
||||
var log = new Log("/app/modules/oauth/token-handlers.js");
|
||||
|
||||
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
|
||||
|
||||
var publicMethods = {};
|
||||
var privateMethods = {};
|
||||
|
||||
publicMethods.setupTokenPairByPasswordGrantType = function (username, password) {
|
||||
if (!username || !password) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
|
||||
"password grant type. Either username of logged in user, password or both are missing " +
|
||||
"as input - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
|
||||
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
|
||||
if (!encodedClientAppCredentials) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
|
||||
"password grant type. Encoded client credentials are " +
|
||||
"missing - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
var tokenPair;
|
||||
// tokenPair will include current access token as well as current refresh token
|
||||
var arrayOfScopes = devicemgtProps["scopes"];
|
||||
var stringOfScopes = "";
|
||||
arrayOfScopes.forEach(function (entry) {
|
||||
stringOfScopes += entry + " ";
|
||||
});
|
||||
tokenPair = tokenUtil.
|
||||
getTokenPairByPasswordGrantType(username,
|
||||
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
|
||||
if (!tokenPair) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " +
|
||||
"token pair by password grant type. Error in token " +
|
||||
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
// setting up access token pair into session context as a string
|
||||
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.setupTokenPairBySamlGrantType = function (username, samlToken) {
|
||||
if (!username || !samlToken) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " +
|
||||
"saml grant type. Either username of logged in user, samlToken or both are missing " +
|
||||
"as input - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
|
||||
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
|
||||
if (!encodedClientAppCredentials) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " +
|
||||
"by saml grant type. Encoded client credentials are " +
|
||||
"missing - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
var tokenPair;
|
||||
// accessTokenPair will include current access token as well as current refresh token
|
||||
tokenPair = tokenUtil.
|
||||
getTokenPairBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION");
|
||||
if (!tokenPair) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " +
|
||||
"pair by password grant type. Error in token " +
|
||||
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
|
||||
} else {
|
||||
// setting up access token pair into session context as a string
|
||||
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
publicMethods.refreshTokenPair = function () {
|
||||
var currentTokenPair = parse(session.get(constants["TOKEN_PAIR"]));
|
||||
// currentTokenPair includes current access token as well as current refresh token
|
||||
var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]);
|
||||
if (!currentTokenPair || !encodedClientAppCredentials) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the " +
|
||||
"token pair, encoded client app credentials or both input are not found under " +
|
||||
"session context - refreshTokenPair()");
|
||||
} else {
|
||||
var newTokenPair = tokenUtil.
|
||||
getNewTokenPairByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials);
|
||||
if (!newTokenPair) {
|
||||
log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " +
|
||||
"Unable to update session context with new access token pair - refreshTokenPair()");
|
||||
} else {
|
||||
session.put(constants["TOKEN_PAIR"], stringify(newTokenPair));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) {
|
||||
if (!username) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
|
||||
"client credentials to session context. No username of logged in user is found as " +
|
||||
"input - setUpEncodedTenantBasedClientAppCredentials(x)");
|
||||
} else {
|
||||
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
|
||||
if (!dynamicClientAppCredentials) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
|
||||
"client credentials to session context as the server is unable to obtain " +
|
||||
"dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
|
||||
} else {
|
||||
var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials);
|
||||
if (!jwtToken) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
|
||||
"client credentials to session context as the server is unable to obtain " +
|
||||
"a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)");
|
||||
} else {
|
||||
var tenantBasedClientAppCredentials = tokenUtil.
|
||||
getTenantBasedClientAppCredentials(username, jwtToken);
|
||||
if (!tenantBasedClientAppCredentials) {
|
||||
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
|
||||
"based client credentials to session context as the server is unable " +
|
||||
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
|
||||
} else {
|
||||
var encodedTenantBasedClientAppCredentials =
|
||||
tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" +
|
||||
tenantBasedClientAppCredentials["clientSecret"]);
|
||||
// setting up encoded tenant based client credentials to session context.
|
||||
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
|
||||
encodedTenantBasedClientAppCredentials);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return publicMethods;
|
||||
}();
|
@ -1,74 +0,0 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
@Deprecated - new
|
||||
*/
|
||||
|
||||
//var serverAddress = function () {
|
||||
// var log = new Log("serverAddress.js");
|
||||
// var process = require("process"),
|
||||
// host = process.getProperty('server.host'),
|
||||
// ip = process.getProperty('carbon.local.ip');
|
||||
// var publicMethods = {};
|
||||
// publicMethods.getHTTPSAddress = function () {
|
||||
// var port = process.getProperty('mgt.transport.https.proxyPort');
|
||||
// if (!port) {
|
||||
// port = process.getProperty('mgt.transport.https.port');
|
||||
// }
|
||||
// if (host === "localhost") {
|
||||
// return "https://" + ip + ":" + port;
|
||||
// } else {
|
||||
// return "https://" + host + ":" + port;
|
||||
// }
|
||||
// };
|
||||
// publicMethods.getHPPTAddress = function () {
|
||||
// var port = process.getProperty('mgt.transport.http.proxyPort');
|
||||
// if (!port) {
|
||||
// port = process.getProperty('mgt.transport.http.port');
|
||||
// }
|
||||
// if (host === "localhost") {
|
||||
// return "http://" + ip + ":" + port;
|
||||
// } else {
|
||||
// return "http://" + host + ":" + port;
|
||||
// }
|
||||
// };
|
||||
// publicMethods.getWSSAddress = function () {
|
||||
// var port = process.getProperty('mgt.transport.https.proxyPort');
|
||||
// if (!port) {
|
||||
// port = process.getProperty('mgt.transport.https.port');
|
||||
// }
|
||||
// if (host === "localhost") {
|
||||
// return "wss://" + ip + ":" + port;
|
||||
// } else {
|
||||
// return "wss://" + host + ":" + port;
|
||||
// }
|
||||
// };
|
||||
// publicMethods.getWSAddress = function () {
|
||||
// var port = process.getProperty('mgt.transport.http.proxyPort');
|
||||
// if (!port) {
|
||||
// port = process.getProperty('mgt.transport.http.port');
|
||||
// }
|
||||
// if (host === "localhost") {
|
||||
// return "ws://" + ip + ":" + port;
|
||||
// } else {
|
||||
// return "ws://" + host + ":" + port;
|
||||
// }
|
||||
// };
|
||||
// return publicMethods;
|
||||
//}();
|
@ -1,226 +0,0 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
var util = function () {
|
||||
var log = new Log("/app/modules/util.js");
|
||||
var module = {};
|
||||
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
|
||||
var String = Packages.java.lang.String;
|
||||
var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
|
||||
var carbon = require('carbon');
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var adminUser = devicemgtProps["adminUser"];
|
||||
var clientName = devicemgtProps["clientName"];
|
||||
|
||||
module.getDynamicClientCredentials = function () {
|
||||
var payload = {
|
||||
"callbackUrl": devicemgtProps.callBackUrl,
|
||||
"clientName": clientName,
|
||||
"tokenScope": "admin",
|
||||
"owner": adminUser,
|
||||
"applicationType": "webapp",
|
||||
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
|
||||
"saasApp" :true
|
||||
};
|
||||
var xhr = new XMLHttpRequest();
|
||||
var tokenEndpoint = devicemgtProps.dynamicClientRegistrationEndPoint;
|
||||
xhr.open("POST", tokenEndpoint, false);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
xhr.send(payload);
|
||||
var clientData = {};
|
||||
if (xhr.status == 201) {
|
||||
var data = parse(xhr.responseText);
|
||||
clientData.clientId = data.client_id;
|
||||
clientData.clientSecret = data.client_secret;
|
||||
|
||||
} else if (xhr.status == 400) {
|
||||
throw "Invalid client meta data";
|
||||
} else {
|
||||
throw "Error in obtaining client id and secret";
|
||||
}
|
||||
return clientData;
|
||||
};
|
||||
|
||||
/**
|
||||
* Encode the payload in Base64
|
||||
* @param payload
|
||||
* @returns {Packages.java.lang.String}
|
||||
*/
|
||||
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;
|
||||
} else {
|
||||
log.error("Error in obtaining token with Password grant type");
|
||||
return null;
|
||||
}
|
||||
return tokenPair;
|
||||
};
|
||||
module.getTokenWithSAMLGrantType = function (assertion, clientKeys, scope) {
|
||||
|
||||
var assertionXML = module.decode(assertion) ;
|
||||
var encodedExtractedAssertion;
|
||||
var extractedAssertion;
|
||||
//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);
|
||||
if (assertionStartIndex != -1 && assertionEndIndex != -1) {
|
||||
extractedAssertion = assertionXML.substring(assertionStartIndex, assertionEndIndex) + assertionEndMarker;
|
||||
} else {
|
||||
throw "Invalid SAML response. SAML response has no valid assertion string";
|
||||
}
|
||||
|
||||
encodedExtractedAssertion = this.encode(extractedAssertion);
|
||||
|
||||
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 " + clientKeys);
|
||||
xhr.send("grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=" +
|
||||
encodeURIComponent(encodedExtractedAssertion) + "&scope=" + "PRODUCTION");
|
||||
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) {
|
||||
throw "Error in obtaining token with SAML extension grant type";
|
||||
} else {
|
||||
throw "Error in obtaining token with SAML extension grant type";
|
||||
}
|
||||
return tokenPair;
|
||||
};
|
||||
|
||||
module.refreshToken = function (tokenPair, clientData, 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 " + clientData);
|
||||
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 {
|
||||
throw "Error in obtaining token with Refresh Token Type";
|
||||
}
|
||||
return tokenPair;
|
||||
};
|
||||
|
||||
module.getTokenWithJWTGrantType = function (clientData) {
|
||||
var jwtService = carbon.server.osgiService('org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
|
||||
var jwtClient = jwtService.getJWTClient();
|
||||
var jwtToken = jwtClient.getAccessToken(clientData.clientId, clientData.clientSecret, adminUser, null);
|
||||
return jwtToken;
|
||||
};
|
||||
|
||||
module.getTenantBasedAppCredentials = function (uname, token) {
|
||||
var tenantDomain = carbonModule.server.tenantDomain({
|
||||
username: uname
|
||||
});
|
||||
var clientData = this.getCachedCredentials(tenantDomain);
|
||||
if (!clientData) {
|
||||
var applicationName = "webapp_" + tenantDomain;
|
||||
var xhr = new XMLHttpRequest();
|
||||
var endpoint = devicemgtProps["adminService"] + "/api-application-registration/register/tenants?tenantDomain=" +
|
||||
tenantDomain + "&applicationName=" + applicationName;
|
||||
xhr.open("POST", endpoint, false);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
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 {
|
||||
throw "Error in obtaining client id and secret from APIM";
|
||||
}
|
||||
}
|
||||
return clientData;
|
||||
};
|
||||
|
||||
module.setTenantBasedAppCredentials = function (tenantDomain, clientData) {
|
||||
var cachedMap = application.get(constants.CACHED_CREDENTIALS);
|
||||
if (!cachedMap) {
|
||||
cachedMap = new Object();
|
||||
cachedMap[tenantDomain] = clientData;
|
||||
application.put(constants.CACHED_CREDENTIALS, cachedMap);
|
||||
} else {
|
||||
cachedMap[tenantDomain] = clientData;
|
||||
}
|
||||
};
|
||||
|
||||
module.getCachedCredentials = function(tenantDomain) {
|
||||
var cachedMap = application.get(constants.CACHED_CREDENTIALS);
|
||||
if (cachedMap) {
|
||||
return cachedMap[tenantDomain];
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return module;
|
||||
}();
|
Loading…
Reference in new issue