used jwt grant type instead of saml

application-manager-new
ayyoob 8 years ago
parent 2da70ad50a
commit ecda000395

@ -47,6 +47,8 @@
<exclude>**/repository/conf/security/cipher-text.properties</exclude>
<exclude>**/repository/conf/security/Owasp.CsrfGuard.Carbon.properties</exclude>
<exclude>**/repository/conf/security/cipher-tool.properties</exclude>
<exclude>**/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handler-utils.js</exclude>
<exclude>**/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handlers.js</exclude>
</excludes>
</fileSet>
<fileSet>
@ -723,10 +725,6 @@
<source>src/repository/conf/security/Owasp.CsrfGuard.Carbon.properties</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/conf/security</outputDirectory>
</file>
<file>
<source>src/repository/conf/etc/jwt.properties</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/conf/etc</outputDirectory>
</file>
<file>
<source>src/repository/conf/analytics/spark/spark-udf-config.xml</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/conf/analytics/spark</outputDirectory>
@ -798,6 +796,21 @@
<filtered>true</filtered>
<fileMode>644</fileMode>
</file>
<file>
<source>src/repository/jaggeryapps/portal/modules/oauth/token-handler-utils.js</source>
<outputDirectory>
${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth
</outputDirectory>
<fileMode>755</fileMode>
</file>
<file>
<source>src/repository/jaggeryapps/portal/modules/oauth/token-handlers.js</source>
<outputDirectory>
${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth
</outputDirectory>
<fileMode>755</fileMode>
</file>
<!-- Adding IoT Analytics Dashboard and gadget CApps -->
<file>
<source>

@ -1,57 +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.
#
#issuer of the JWT
iss=wso2.org/products/iot
TokenEndpoint=https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token
#audience of JWT claim
#comma seperated values
aud=devicemgt
#expiration time of JWT (number of minutes from the current time)
exp=1000
#issued at time of JWT (number of minutes from the current time)
iat=0
#nbf time of JWT (number of minutes from current time)
nbf=0
#skew between IDP and issuer(seconds)
skew=0
# JWT Id
#jti=token123
#KeyStore to cryptographic credentials
#KeyStore=repository/resources/security/wso2carbon.jks
#Password of the KeyStore
#KeyStorePassword=wso2carbon
#Alias of the SP's private key
#PrivateKeyAlias=wso2carbon
#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

@ -0,0 +1,598 @@
/*
* 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 utils = function () {
var log = new Log("/modules/oauth/token-handler-utils.js");
var configs = require('/configs/portal.js').config();
var constants = require("/modules/constants.js");
var carbon = require("carbon");
//noinspection JSUnresolvedVariable
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
//noinspection JSUnresolvedVariable
var String = Packages.java.lang.String;
var publicMethods = {};
var privateMethods = {};
publicMethods["encode"] = function (payload) {
return String(Base64.encodeBase64(String(payload).getBytes()));
};
publicMethods["decode"] = function (payload) {
return String(Base64.decodeBase64(String(payload).getBytes()));
};
/**
* Check whether this application is oauth enable or not
* @returns boolean if oauth enable
*/
publicMethods["checkOAuthEnabled"] = function () {
if (constants.AUTHORIZATION_TYPE_OAUTH === configs["authorization"]["activeMethod"]) {
return true;
}
return false;
};
/**
* Set access token into xml http request header
* @param xhr xml http request
* @returns {*} xhr which has access token it's header
*/
publicMethods["setAccessToken"] = function (xhr, callback) {
var accessToken;
if (publicMethods.checkOAuthEnabled()) {
try {
accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"];
xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken);
} catch (exception) {
log.error("Access token hasn't been set yet, " + exception);
} finally {
callback(xhr);
}
}
callback(xhr);
};
/**
* Get access token of current logged user
* @param callBack response with access token
*/
publicMethods["getAccessToken"] = function (callBack) {
var accessToken = null;
if (publicMethods.checkOAuthEnabled()) {
try {
accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"];
} catch (exception) {
log.error("Access token hasn't been set yet, " + exception);
} finally {
callBack(accessToken);
}
}
callBack(accessToken);
};
/**
* Create error message which adhere to xml http response object
* @param statusCode response status code
* @param status response status
* @param responseText response message
* @returns {{statusCode: *, status: *, responseText: *}}
*/
publicMethods["createXHRObject"] = function (statusCode, status, responseText) {
return {"statusCode": statusCode, "status": status, "responseText": responseText};
};
/**
* check whether user already logged to system before invoking any apis
* @param callBack
*/
publicMethods["isUserAuthorized"] = function (callBack) {
if (session.get("Loged") !== constants.LOGIN_MESSAGE) {
callBack(false);
} else {
callBack(true);
}
};
/**
* Get identity provider uir
* @returns {*}
*/
publicMethods["getIdPServerURL"] = function () {
return configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["tokenServiceURL"];
};
/**
* Get an Access token pair based on client secret
* @param encodedClientKeys {{clientId:"", clientSecret:""}}
* @param scope eg: PRODUCTION
* @param idPServer identity provider url
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenWithClientSecretType"] = function (encodedClientKeys, scope, idPServer) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = idPServer;
xhr.open(constants.HTTP_POST, tokenEndpoint, false);
xhr.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_X_WWW_FOR_URLENCODED);
xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BASIC_PREFIX + encodedClientKeys);
xhr.send("grant_type=client_credentials&scope=" + scope);
var tokenPair = {};
if (xhr.status == constants.HTTP_ACCEPTED) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == constants.HTTP_USER_NOT_AUTHENTICATED) {
log.error("Error in obtaining token with client secret grant type, You are not authenticated yet");
return null;
} else {
log.error("Error in obtaining token with client secret grant type, This might be a problem with client meta " +
"data which required for client secret grant type");
return null;
}
return tokenPair;
};
/**
* This will create client id and client secret for a given application
* @param properties "callbackUrl": "",
* "clientName": "",
* "owner": "",
* "applicationType": "",
* "grantType": "",
* "saasApp" :"",
* "dynamicClientRegistrationEndPoint" : ""
*
* @returns {{clientId:*, clientSecret:*}}
*/
publicMethods["getDynamicClientAppCredentials"] = function (username) {
// setting up dynamic client application properties
var dcAppProperties = {
"applicationType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["appType"],
"clientName": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["clientName"],
"owner": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"],
"tokenScope": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["tokenScope"],
"grantType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["grantType"],
"callbackUrl": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["callbackUrl"],
"saasApp" : configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["saasApp"]
};
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials. Unable to obtain a valid tenant domain for provided username "+
username +"- getDynamicClientAppCredentials(x)");
return null;
} else {
var cachedTenantBasedClientAppCredentials = privateMethods.
getCachedTenantBasedClientAppCredentials(tenantDomain);
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} else {
// calling dynamic client app registration service endpoint
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]
["dynamicClientAppRegistrationServiceURL"];
var requestPayload = dcAppProperties;
var token = publicMethods.encode(configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["owner"] + ":" + configs["authorization"]["methods"]["oauth"]["attributes"]
["oauthProvider"]["appRegistration"]["password"]);
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Basic "+ token);
xhr.send(stringify(requestPayload));
var dynamicClientAppCredentials = {};
if (xhr["status"] == 201 || xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var clientId = responsePayload["client_id"];
var clientSecret = responsePayload["client_secret"];
if(typeof clientId == "undefined"){
clientId = responsePayload["clientId"];
}
if(typeof clientSecret == "undefined"){
clientSecret = responsePayload["clientSecret"];
}
dynamicClientAppCredentials["clientId"] = clientId;
dynamicClientAppCredentials["clientSecret"] = clientSecret;
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, dynamicClientAppCredentials);
} else if (xhr["status"] == 400) {
log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Bad request. Invalid data provided as dynamic client application properties.");
dynamicClientAppCredentials = null;
} else {
log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Error in retrieving dynamic client credentials.");
dynamicClientAppCredentials = null;
}
// returning dynamic client credentials
return dynamicClientAppCredentials;
}
}
};
/**
* If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create oauth application
* @param username username of current logged user
* @returns {{clientId:*, clientSecret:*}}
*/
publicMethods["getTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username " +
"as input - getTenantBasedClientAppCredentials(x)");
return null;
} else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/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 {
var adminUsername = configs["authorization"]["methods"]["oauth"]["attributes"]["adminUser"];
var adminUserTenantId = configs["authorization"]["methods"]["oauth"]["attributes"]
["adminUserTenantId"];
//claims required for jwtAuthenticator.
var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId,
"http://wso2.org/claims/enduser": adminUsername};
var jwtToken = publicMethods.getJwtToken(adminUsername, claims);
// register a tenant based client app at API Manager
var applicationName = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["clientName"] + "_" + tenantDomain;
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["apiManagerClientAppRegistrationServiceURL"] +
"?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send();
if ((xhr["status"] == 201 || xhr["status"] == 200) && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantBasedClientAppCredentials = {};
var clientId = responsePayload["client_id"];
var clientSecret = responsePayload["client_secret"];
if(typeof clientId == "undefined"){
clientId = responsePayload["clientId"];
}
if(typeof clientSecret == "undefined"){
clientSecret = responsePayload["clientSecret"];
}
tenantBasedClientAppCredentials["clientId"] = clientId;
tenantBasedClientAppCredentials["clientSecret"] = clientSecret;
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
return tenantBasedClientAppCredentials;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials from API " +
"Manager - getTenantBasedClientAppCredentials(x, y)");
return null;
}
}
}
}
};
/**
* Caching oauth application credentials
* @param tenantDomain tenant domain where application is been created
* @param clientAppCredentials {{clientId:*, clientSecret:*}}
*/
privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]);
if (!cachedTenantBasedClientAppCredentialsMap) {
cachedTenantBasedClientAppCredentialsMap = {};
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
application.put(constants["CACHED_CREDENTIALS_PORTAL_APP"], cachedTenantBasedClientAppCredentialsMap);
} else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
}
};
/**
* Get oauth application credentials from cache
* @param tenantDomain tenant domain where application is been created
* @returns {{clientId:*, clientSecret:*}}
*/
privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]);
if (!cachedTenantBasedClientAppCredentialsMap ||
!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
}
};
/**
* Get access token and refresh token using password grant type
* @param username username of the logged user
* @param password password of the logged user
* @param encodedClientAppCredentials {{clientId:*, clientSecret:*}}
* @param scopes scopes list
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password
, encodedClientAppCredentials, scopes) {
if (!username || !password || !encodedClientAppCredentials || !scopes) {
log.error("{/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 - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
} else {
// calling oauth provider token service endpoint
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["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 tokenData = {};
tokenData["accessToken"] = responsePayload["access_token"];
tokenData["refreshToken"] = responsePayload["refresh_token"];
tokenData["scopes"] = responsePayload["scope"];
return tokenData;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
}
}
};
/**
* Get access token and refresh token using SAML grant type
* @param assertion
* @param encodedClientAppCredentials
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (username, encodedClientAppCredentials, scopes) {
if (!username || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " +
"grant type. No assertion, encoded client app credentials or scopes are " +
"found - getTokenPairAndScopesByJWTGrantType(x, y, z)");
return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials,
username, scopes);
var tokenData = {};
tokenData["accessToken"] = tokenInfo.getAccessToken();
tokenData["refreshToken"] = tokenInfo.getRefreshToken();
tokenData["scopes"] = tokenInfo.getScopes();
return tokenData;
}
};
/**
* Get access token and refresh token using SAML grant type
* @param assertion
* @param encodedClientAppCredentials
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) {
if (!assertion || !encodedClientAppCredentials || !scopes) {
log.error("{/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 - getTokenPairAndScopesBySAMLGrantType(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("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml grant " +
"type. Issue in assertion format - getTokenPairAndScopesBySAMLGrantType(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 = configs["authorization"]["methods"]["oauth"]["attributes"]["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 tokenData = {};
tokenData["accessToken"] = responsePayload["access_token"];
tokenData["refreshToken"] = responsePayload["refresh_token"];
tokenData["scopes"] = responsePayload["scope"];
return tokenData;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairAndScopesBySAMLGrantType(x, y, z)");
return null;
}
}
}
};
/**
* If access token is expired, try to refresh it using existing refresh token
* @param callback
*/
publicMethods["refreshAccessToken"] = function (callback) {
try {
if (publicMethods.checkOAuthEnabled()) {
var currentTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials
= session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
callback(false);
throw new Error("{/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 = publicMethods.
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()");
callback(false);
} else {
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(newTokenPair));
callback(true);
}
}
} else {
log.error("You have not enable dynamic client yet");
callback(false);
}
} catch (exception) {
callback(false);
throw "Error while refreshing existing access token, " + exception;
}
};
/**
* Get access token and refresh token using refresh token grant type
* @param refreshToken refresh token
* @param encodedClientAppCredentials {{clientId:*, clientSecret:*}}
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getNewTokenPairByRefreshToken"] = function (refreshToken, encodedClientAppCredentials, scopes) {
if (!refreshToken || !encodedClientAppCredentials) {
log.error("{/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 = configs["authorization"]["methods"]["oauth"]["attributes"]["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("{/modules/oauth/token-handler-utils.js} Error in retrieving new access token by " +
"current refresh token - getNewTokenPairByRefreshToken(x, y, z)");
return null;
}
}
};
/**
* Get access token using JWT grant type
* @param clientAppCredentials {{clientId:*, clientSecret:*}}
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getAccessTokenByJWTGrantType"] = function (clientAppCredentials) {
if (!clientAppCredentials) {
log.error("{/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";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"],
null)["accessToken"];
}
};
/**
* Get jwt token
* @param username username of logged user
* @param claims claims which are required
* @returns {"jwtToken"}
*/
publicMethods["getJwtToken"] = function (username, claims) {
if (!username) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token");
return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
if (claims) {
return jwtClient.getJwtToken(username, claims);
} else {
return jwtClient.getJwtToken(username);
}
}
};
return publicMethods;
}();

@ -0,0 +1,192 @@
/*
* 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.
*/
/**
* -----------------------------------------------------
* Following module includes handlers
* at Jaggery Layer for handling OAuth tokens.
* -----------------------------------------------------
*/
var handlers = function () {
var log = new Log("/modules/oauth/token-handlers.js");
var tokenUtil = require("/modules/oauth/token-handler-utils.js")["utils"];
var constants = require("/modules/constants.js");
var configs = require('/configs/portal.js').config();
var publicMethods = {};
var privateMethods = {};
/**
* Get an AccessToken pair based on username and password
* @param username username of the logged user
* @param password password of the logged user
*/
publicMethods["setupTokenPairByPasswordGrantType"] = function (username, password) {
if (!username || !password) {
throw new Error("{/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_PORTAL_APP"]);
if (!encodedClientAppCredentials) {
throw new Error("{/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 tokenData;
// tokenPair will include current access token as well as current refresh token
var arrayOfScopes = configs["authorization"]["methods"]["oauth"]["attributes"]["scopes"];
var stringOfScopes = "";
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
tokenData = tokenUtil.
getTokenPairAndScopesByPasswordGrantType(username,
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
if (!tokenData) {
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 {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
/**
* Get an AccessToken pair based on SAML assertion
* @param samlToken SAML assertion
* @param username {{clientId:"", clientSecret:""}}
*/
publicMethods["setupTokenPairBySamlGrantType"] = function (username, samlToken) {
if (!username || !samlToken) {
throw new Error("{/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 - setupTokenPairBySamlGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
var encodedClientAppCredentials =
session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
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 - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenData;
// accessTokenPair will include current access token as well as current refresh token
tokenData = tokenUtil.
getTokenPairAndScopesByJWTGrantType(username, encodedClientAppCredentials, "PRODUCTION");
if (!tokenData) {
throw new Error("{/modules/oauth/token-handlers.js} Could not set up token " +
"pair by saml grant type. Error in token " +
"retrieval - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up access token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
/**
* Set access token and refresh token using refresh token grant type
*/
publicMethods["refreshTokenPair"] = function () {
var currentTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials
= session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
throw new Error("{/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["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(newTokenPair));
}
}
};
/**
* If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create an oauth application or
* else DCR endpoint is used to create an oauth application
* @param username username of current logged user
*/
privateMethods["setUpEncodedTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
throw new Error("{/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 {
if (configs["authorization"]["methods"]["oauth"]["attributes"]["apimgt-gateway"]) {
var tenantBasedClientAppCredentials = tokenUtil.getTenantBasedClientAppCredentials(username);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/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_PORTAL_APP"],
encodedTenantBasedClientAppCredentials);
}
} else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(username);
if (!dynamicClientAppCredentials) {
throw new Error("{/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)");
}
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(dynamicClientAppCredentials["clientId"] + ":" +
dynamicClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"],
encodedTenantBasedClientAppCredentials);
}
}
};
return publicMethods;
}();

@ -34,7 +34,7 @@
"methods": {
"oauth": {
"attributes": {
"apimgt-gateway": false,
"apimgt-gateway": true,
"oauthProvider": {
"appRegistration": {
"appType": "webapp",
@ -43,11 +43,10 @@
"password":"admin",
"dynamicClientAppRegistrationServiceURL": "https://localhost:9443/dynamic-client-web/register",
"apiManagerClientAppRegistrationServiceURL": "https://localhost:9443/api-application-registration/register/tenants",
"grantType": "password refresh_token urn:ietf:urn:ietf:params:oauth:grant-type:saml2-bearer urn:ietf:params:oauth:grant-type:jwt-bearer",
"grantType": "urn:ietf:urn:ietf:params:oauth:grant-type:saml2-bearer",
"tokenScope": "admin",
"callbackUrl": "https://localhost:9445/portal",
"saasApp":true,
"samlGrantTypeName":"urn:ietf:params:oauth:grant-type:saml2-bearer"
"saasApp":true
},
"tokenServiceURL": "https://localhost:9443/oauth2/token"

@ -25,7 +25,7 @@
<value>
<![CDATA[<SupportedGrantType>
<GrantTypeName>urn:ietf:params:oauth:grant-type:jwt-bearer</GrantTypeName>
<GrantTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.grant.jwt.JWTBearerGrantHandler</GrantTypeHandlerImplClass>
<GrantTypeHandlerImplClass>org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant.ExtendedJWTGrantHandler</GrantTypeHandlerImplClass>
<GrantTypeValidatorImplClass>org.wso2.carbon.identity.oauth2.grant.jwt.JWTGrantValidator</GrantTypeValidatorImplClass>
</SupportedGrantType>]]></value>
</add>

@ -128,7 +128,7 @@
<replacement>
<xpath>/Server/OAuth/SupportedGrantTypes/SupportedGrantType</xpath>
<token>(org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler)</token>
<value>org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant.ExtendedSAML2BearerGrantHandler</value>
<value>org.wso2.carbon.apimgt.keymgt.handlers.ExtendedSAML2BearerGrantHandler</value>
</replacement>
<replacement>
<xpath>/Server/OAuth/SupportedGrantTypes/SupportedGrantType</xpath>

@ -116,6 +116,10 @@
<exclude>**/repository/components/plugins/httpclient_4.3.2.wso2v1.jar</exclude>
<exclude>**/conf/tomcat/carbon/WEB-INF/web.xml</exclude>
<exclude>**/repository/components/plugins/org.wso2.carbon.hostobjects.sso_4.5.4.jar</exclude>
<exclude>**/bin/wso2server.sh</exclude>
<exclude>**/bin/wso2server.bat</exclude>
<exclude>**/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handler-utils.js</exclude>
<exclude>**/repository/deployment/server/jaggeryapps/portal/modules/oauth/plugins/token-handlers.js</exclude>
</excludes>
</fileSet>
@ -129,18 +133,6 @@
<include>*/**</include>
</includes>
</fileSet>
<fileSet>
<directory>target/wso2carbon-core-${carbon.kernel.version}</directory>
<outputDirectory>${pom.artifactId}-${pom.version}</outputDirectory>
<includes>
<include>**/*.sh</include>
</includes>
<excludes>
<exclude>bin/wso2server.sh</exclude>
<exclude>bin/wso2server.bat</exclude>
</excludes>
<fileMode>755</fileMode>
</fileSet>
<!-- Multi-tenancy related file -->
<fileSet>
@ -798,6 +790,20 @@
</outputDirectory>
<fileMode>755</fileMode>
</file>
<file>
<source>src/repository/jaggeryapps/portal/modules/oauth/token-handler-utils.js</source>
<outputDirectory>
${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth
</outputDirectory>
<fileMode>755</fileMode>
</file>
<file>
<source>src/repository/jaggeryapps/portal/modules/oauth/token-handlers.js</source>
<outputDirectory>
${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/modules/oauth
</outputDirectory>
<fileMode>755</fileMode>
</file>
<!-- End of "portal" app specific modifications -->
<!-- Copying config file for enabling sso in api-store-->
@ -995,7 +1001,7 @@
-->
<file>
<source>
src/repository/conf/cdm-config.xml
../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/cdm-config.xml
</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/conf</outputDirectory>
<filtered>true</filtered>

@ -253,10 +253,10 @@
<ApplicationTokenScope>am_application_scope</ApplicationTokenScope>
<!-- All scopes under the ScopeWhitelist element are not validating against roles that has assigned to it.
By default ^device_.* and openid scopes have been white listed internally. -->
<!--ScopeWhitelist>
<ScopeWhitelist>
<Scope>^device_.*</Scope>
<Scope>openid</Scope>
</ScopeWhitelist-->
<!--<Scope>openid</Scope>-->
</ScopeWhitelist>
<!-- Name of the token API -->
<TokenEndPointName>/oauth2/token</TokenEndPointName>
<!-- This the API URL for revoke API. When we revoke tokens revoke requests should go through this

@ -1,63 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<DeviceMgtConfiguration>
<ManagementRepository>
<DataSourceConfiguration>
<JndiLookupDefinition>
<Name>jdbc/DM_DS</Name>
</JndiLookupDefinition>
</DataSourceConfiguration>
</ManagementRepository>
<PushNotificationProviders>
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider</Provider>
<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider</Provider>
<!--<Provider>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.GCMBasedPushNotificationProvider</Provider>-->
<!--<Provider>org.wso2.carbon.device.mgt.mobile.impl.ios.apns.APNSBasedPushNotificationProvider</Provider>-->
</PushNotificationProviders>
<IdentityConfiguration>
<ServerUrl>https://localhost:9443</ServerUrl>
<AdminUsername>admin</AdminUsername>
<AdminPassword>admin</AdminPassword>
</IdentityConfiguration>
<PolicyConfiguration>
<MonitoringClass>org.wso2.carbon.policy.mgt</MonitoringClass>
<MonitoringEnable>false</MonitoringEnable>
<MonitoringFrequency>60000</MonitoringFrequency>
<MaxRetries>5</MaxRetries>
<MinRetriesToMarkUnreachable>8</MinRetriesToMarkUnreachable>
<MinRetriesToMarkInactive>20</MinRetriesToMarkInactive>
<!--Set the policy evaluation point name (Simple/Merged)-->
<!--Simple - Simple policy evaluation point-->
<!--Merged - Merged policy evaluation point -->
<PolicyEvaluationPoint>Simple</PolicyEvaluationPoint>
</PolicyConfiguration>
<TaskConfiguration>
<Enable>true</Enable>
<Frequency>60000</Frequency>
<TaskClass>org.wso2.carbon.device.mgt.core.task.impl.DeviceDetailsRetrieverTask</TaskClass>
</TaskConfiguration>
<!-- Default Page size configuration for paginated DM APIs-->
<PaginationConfiguration>
<DeviceListPageSize>20</DeviceListPageSize>
<NotificationListPageSize>20</NotificationListPageSize>
<ActivityListPageSize>20</ActivityListPageSize>
<OperationListPageSize>20</OperationListPageSize>
</PaginationConfiguration>
</DeviceMgtConfiguration>

@ -0,0 +1,598 @@
/*
* 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 utils = function () {
var log = new Log("/modules/oauth/token-handler-utils.js");
var configs = require('/configs/portal.js').config();
var constants = require("/modules/constants.js");
var carbon = require("carbon");
//noinspection JSUnresolvedVariable
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
//noinspection JSUnresolvedVariable
var String = Packages.java.lang.String;
var publicMethods = {};
var privateMethods = {};
publicMethods["encode"] = function (payload) {
return String(Base64.encodeBase64(String(payload).getBytes()));
};
publicMethods["decode"] = function (payload) {
return String(Base64.decodeBase64(String(payload).getBytes()));
};
/**
* Check whether this application is oauth enable or not
* @returns boolean if oauth enable
*/
publicMethods["checkOAuthEnabled"] = function () {
if (constants.AUTHORIZATION_TYPE_OAUTH === configs["authorization"]["activeMethod"]) {
return true;
}
return false;
};
/**
* Set access token into xml http request header
* @param xhr xml http request
* @returns {*} xhr which has access token it's header
*/
publicMethods["setAccessToken"] = function (xhr, callback) {
var accessToken;
if (publicMethods.checkOAuthEnabled()) {
try {
accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"];
xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken);
} catch (exception) {
log.error("Access token hasn't been set yet, " + exception);
} finally {
callback(xhr);
}
}
callback(xhr);
};
/**
* Get access token of current logged user
* @param callBack response with access token
*/
publicMethods["getAccessToken"] = function (callBack) {
var accessToken = null;
if (publicMethods.checkOAuthEnabled()) {
try {
accessToken = parse(session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL))["accessToken"];
} catch (exception) {
log.error("Access token hasn't been set yet, " + exception);
} finally {
callBack(accessToken);
}
}
callBack(accessToken);
};
/**
* Create error message which adhere to xml http response object
* @param statusCode response status code
* @param status response status
* @param responseText response message
* @returns {{statusCode: *, status: *, responseText: *}}
*/
publicMethods["createXHRObject"] = function (statusCode, status, responseText) {
return {"statusCode": statusCode, "status": status, "responseText": responseText};
};
/**
* check whether user already logged to system before invoking any apis
* @param callBack
*/
publicMethods["isUserAuthorized"] = function (callBack) {
if (session.get("Loged") !== constants.LOGIN_MESSAGE) {
callBack(false);
} else {
callBack(true);
}
};
/**
* Get identity provider uir
* @returns {*}
*/
publicMethods["getIdPServerURL"] = function () {
return configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["tokenServiceURL"];
};
/**
* Get an Access token pair based on client secret
* @param encodedClientKeys {{clientId:"", clientSecret:""}}
* @param scope eg: PRODUCTION
* @param idPServer identity provider url
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenWithClientSecretType"] = function (encodedClientKeys, scope, idPServer) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = idPServer;
xhr.open(constants.HTTP_POST, tokenEndpoint, false);
xhr.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, constants.APPLICATION_X_WWW_FOR_URLENCODED);
xhr.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BASIC_PREFIX + encodedClientKeys);
xhr.send("grant_type=client_credentials&scope=" + scope);
var tokenPair = {};
if (xhr.status == constants.HTTP_ACCEPTED) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == constants.HTTP_USER_NOT_AUTHENTICATED) {
log.error("Error in obtaining token with client secret grant type, You are not authenticated yet");
return null;
} else {
log.error("Error in obtaining token with client secret grant type, This might be a problem with client meta " +
"data which required for client secret grant type");
return null;
}
return tokenPair;
};
/**
* This will create client id and client secret for a given application
* @param properties "callbackUrl": "",
* "clientName": "",
* "owner": "",
* "applicationType": "",
* "grantType": "",
* "saasApp" :"",
* "dynamicClientRegistrationEndPoint" : ""
*
* @returns {{clientId:*, clientSecret:*}}
*/
publicMethods["getDynamicClientAppCredentials"] = function (username) {
// setting up dynamic client application properties
var dcAppProperties = {
"applicationType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["appType"],
"clientName": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["clientName"],
"owner": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"],
"tokenScope": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["tokenScope"],
"grantType": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["grantType"],
"callbackUrl": configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["callbackUrl"],
"saasApp" : configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["saasApp"]
};
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials. Unable to obtain a valid tenant domain for provided username "+
username +"- getDynamicClientAppCredentials(x)");
return null;
} else {
var cachedTenantBasedClientAppCredentials = privateMethods.
getCachedTenantBasedClientAppCredentials(tenantDomain);
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} else {
// calling dynamic client app registration service endpoint
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]
["dynamicClientAppRegistrationServiceURL"];
var requestPayload = dcAppProperties;
var token = publicMethods.encode(configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["owner"] + ":" + configs["authorization"]["methods"]["oauth"]["attributes"]
["oauthProvider"]["appRegistration"]["password"]);
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Basic "+ token);
xhr.send(stringify(requestPayload));
var dynamicClientAppCredentials = {};
if (xhr["status"] == 201 || xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var clientId = responsePayload["client_id"];
var clientSecret = responsePayload["client_secret"];
if(typeof clientId == "undefined"){
clientId = responsePayload["clientId"];
}
if(typeof clientSecret == "undefined"){
clientSecret = responsePayload["clientSecret"];
}
dynamicClientAppCredentials["clientId"] = clientId;
dynamicClientAppCredentials["clientSecret"] = clientSecret;
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, dynamicClientAppCredentials);
} else if (xhr["status"] == 400) {
log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Bad request. Invalid data provided as dynamic client application properties.");
dynamicClientAppCredentials = null;
} else {
log.error("{/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " +
"Error in retrieving dynamic client credentials.");
dynamicClientAppCredentials = null;
}
// returning dynamic client credentials
return dynamicClientAppCredentials;
}
}
};
/**
* If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create oauth application
* @param username username of current logged user
* @returns {{clientId:*, clientSecret:*}}
*/
publicMethods["getTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username " +
"as input - getTenantBasedClientAppCredentials(x)");
return null;
} else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/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 {
var adminUsername = configs["authorization"]["methods"]["oauth"]["attributes"]["adminUser"];
var adminUserTenantId = configs["authorization"]["methods"]["oauth"]["attributes"]
["adminUserTenantId"];
//claims required for jwtAuthenticator.
var claims = {"http://wso2.org/claims/enduserTenantId": adminUserTenantId,
"http://wso2.org/claims/enduser": adminUsername};
var jwtToken = publicMethods.getJwtToken(adminUsername, claims);
// register a tenant based client app at API Manager
var applicationName = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["clientName"] + "_" + tenantDomain;
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]
["appRegistration"]["apiManagerClientAppRegistrationServiceURL"] +
"?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName;
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send();
if ((xhr["status"] == 201 || xhr["status"] == 200) && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
var tenantBasedClientAppCredentials = {};
var clientId = responsePayload["client_id"];
var clientSecret = responsePayload["client_secret"];
if(typeof clientId == "undefined"){
clientId = responsePayload["clientId"];
}
if(typeof clientSecret == "undefined"){
clientSecret = responsePayload["clientSecret"];
}
tenantBasedClientAppCredentials["clientId"] = clientId;
tenantBasedClientAppCredentials["clientSecret"] = clientSecret;
privateMethods.
setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials);
return tenantBasedClientAppCredentials;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client application credentials from API " +
"Manager - getTenantBasedClientAppCredentials(x, y)");
return null;
}
}
}
}
};
/**
* Caching oauth application credentials
* @param tenantDomain tenant domain where application is been created
* @param clientAppCredentials {{clientId:*, clientSecret:*}}
*/
privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]);
if (!cachedTenantBasedClientAppCredentialsMap) {
cachedTenantBasedClientAppCredentialsMap = {};
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
application.put(constants["CACHED_CREDENTIALS_PORTAL_APP"], cachedTenantBasedClientAppCredentialsMap);
} else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials;
}
};
/**
* Get oauth application credentials from cache
* @param tenantDomain tenant domain where application is been created
* @returns {{clientId:*, clientSecret:*}}
*/
privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) {
var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS_PORTAL_APP"]);
if (!cachedTenantBasedClientAppCredentialsMap ||
!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) {
return null;
} else {
return cachedTenantBasedClientAppCredentialsMap[tenantDomain];
}
};
/**
* Get access token and refresh token using password grant type
* @param username username of the logged user
* @param password password of the logged user
* @param encodedClientAppCredentials {{clientId:*, clientSecret:*}}
* @param scopes scopes list
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesByPasswordGrantType"] = function (username, password
, encodedClientAppCredentials, scopes) {
if (!username || !password || !encodedClientAppCredentials || !scopes) {
log.error("{/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 - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
} else {
// calling oauth provider token service endpoint
var requestURL = configs["authorization"]["methods"]["oauth"]["attributes"]["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 tokenData = {};
tokenData["accessToken"] = responsePayload["access_token"];
tokenData["refreshToken"] = responsePayload["refresh_token"];
tokenData["scopes"] = responsePayload["scope"];
return tokenData;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairAndScopesByPasswordGrantType(a, b, c, d)");
return null;
}
}
};
/**
* Get access token and refresh token using SAML grant type
* @param assertion
* @param encodedClientAppCredentials
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesByJWTGrantType"] = function (username, encodedClientAppCredentials, scopes) {
if (!username || !encodedClientAppCredentials || !scopes) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by jwt " +
"grant type. No assertion, encoded client app credentials or scopes are " +
"found - getTokenPairAndScopesByJWTGrantType(x, y, z)");
return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
var tokenInfo = jwtClient.getAccessToken(encodedClientAppCredentials,
username, scopes);
var tokenData = {};
tokenData["accessToken"] = tokenInfo.getAccessToken();
tokenData["refreshToken"] = tokenInfo.getRefreshToken();
tokenData["scopes"] = tokenInfo.getScopes();
return tokenData;
}
};
/**
* Get access token and refresh token using SAML grant type
* @param assertion
* @param encodedClientAppCredentials
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getTokenPairAndScopesBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) {
if (!assertion || !encodedClientAppCredentials || !scopes) {
log.error("{/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 - getTokenPairAndScopesBySAMLGrantType(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("{/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml grant " +
"type. Issue in assertion format - getTokenPairAndScopesBySAMLGrantType(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 = configs["authorization"]["methods"]["oauth"]["attributes"]["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 tokenData = {};
tokenData["accessToken"] = responsePayload["access_token"];
tokenData["refreshToken"] = responsePayload["refresh_token"];
tokenData["scopes"] = responsePayload["scope"];
return tokenData;
} else {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairAndScopesBySAMLGrantType(x, y, z)");
return null;
}
}
}
};
/**
* If access token is expired, try to refresh it using existing refresh token
* @param callback
*/
publicMethods["refreshAccessToken"] = function (callback) {
try {
if (publicMethods.checkOAuthEnabled()) {
var currentTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials
= session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
callback(false);
throw new Error("{/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 = publicMethods.
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()");
callback(false);
} else {
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(newTokenPair));
callback(true);
}
}
} else {
log.error("You have not enable dynamic client yet");
callback(false);
}
} catch (exception) {
callback(false);
throw "Error while refreshing existing access token, " + exception;
}
};
/**
* Get access token and refresh token using refresh token grant type
* @param refreshToken refresh token
* @param encodedClientAppCredentials {{clientId:*, clientSecret:*}}
* @param scopes
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getNewTokenPairByRefreshToken"] = function (refreshToken, encodedClientAppCredentials, scopes) {
if (!refreshToken || !encodedClientAppCredentials) {
log.error("{/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 = configs["authorization"]["methods"]["oauth"]["attributes"]["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("{/modules/oauth/token-handler-utils.js} Error in retrieving new access token by " +
"current refresh token - getNewTokenPairByRefreshToken(x, y, z)");
return null;
}
}
};
/**
* Get access token using JWT grant type
* @param clientAppCredentials {{clientId:*, clientSecret:*}}
* @returns {{accessToken: *, refreshToken: *}}
*/
publicMethods["getAccessTokenByJWTGrantType"] = function (clientAppCredentials) {
if (!clientAppCredentials) {
log.error("{/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";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"],
configs["authorization"]["methods"]["oauth"]["attributes"]["oauthProvider"]["appRegistration"]["owner"],
null)["accessToken"];
}
};
/**
* Get jwt token
* @param username username of logged user
* @param claims claims which are required
* @returns {"jwtToken"}
*/
publicMethods["getJwtToken"] = function (username, claims) {
if (!username) {
log.error("{/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token");
return null;
} else {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
if (claims) {
return jwtClient.getJwtToken(username, claims);
} else {
return jwtClient.getJwtToken(username);
}
}
};
return publicMethods;
}();

@ -0,0 +1,192 @@
/*
* 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.
*/
/**
* -----------------------------------------------------
* Following module includes handlers
* at Jaggery Layer for handling OAuth tokens.
* -----------------------------------------------------
*/
var handlers = function () {
var log = new Log("/modules/oauth/token-handlers.js");
var tokenUtil = require("/modules/oauth/token-handler-utils.js")["utils"];
var constants = require("/modules/constants.js");
var configs = require('/configs/portal.js').config();
var publicMethods = {};
var privateMethods = {};
/**
* Get an AccessToken pair based on username and password
* @param username username of the logged user
* @param password password of the logged user
*/
publicMethods["setupTokenPairByPasswordGrantType"] = function (username, password) {
if (!username || !password) {
throw new Error("{/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_PORTAL_APP"]);
if (!encodedClientAppCredentials) {
throw new Error("{/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 tokenData;
// tokenPair will include current access token as well as current refresh token
var arrayOfScopes = configs["authorization"]["methods"]["oauth"]["attributes"]["scopes"];
var stringOfScopes = "";
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
tokenData = tokenUtil.
getTokenPairAndScopesByPasswordGrantType(username,
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
if (!tokenData) {
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 {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
/**
* Get an AccessToken pair based on SAML assertion
* @param samlToken SAML assertion
* @param username {{clientId:"", clientSecret:""}}
*/
publicMethods["setupTokenPairBySamlGrantType"] = function (username, samlToken) {
if (!username || !samlToken) {
throw new Error("{/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 - setupTokenPairBySamlGrantType(x, y)");
} else {
privateMethods.setUpEncodedTenantBasedClientAppCredentials(username);
var encodedClientAppCredentials =
session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
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 - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenData;
// accessTokenPair will include current access token as well as current refresh token
tokenData = tokenUtil.
getTokenPairAndScopesByJWTGrantType(username, encodedClientAppCredentials, "PRODUCTION");
if (!tokenData) {
throw new Error("{/modules/oauth/token-handlers.js} Could not set up token " +
"pair by saml grant type. Error in token " +
"retrieval - setupTokenPairBySamlGrantType(x, y)");
} else {
var tokenPair = {};
tokenPair["accessToken"] = tokenData["accessToken"];
tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up access token pair into session context as a string
session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(tokenPair));
var scopes = tokenData.scopes.split(" ");
// adding allowed scopes to the session
session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
};
/**
* Set access token and refresh token using refresh token grant type
*/
publicMethods["refreshTokenPair"] = function () {
var currentTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"]));
// currentTokenPair includes current access token as well as current refresh token
var encodedClientAppCredentials
= session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"]);
if (!currentTokenPair || !encodedClientAppCredentials) {
throw new Error("{/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["ACCESS_TOKEN_PAIR_IDENTIFIER_FOR_PORTAL"], stringify(newTokenPair));
}
}
};
/**
* If gateway is enable, apiManagerClientAppRegistrationServiceURL is used to create an oauth application or
* else DCR endpoint is used to create an oauth application
* @param username username of current logged user
*/
privateMethods["setUpEncodedTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
throw new Error("{/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 {
if (configs["authorization"]["methods"]["oauth"]["attributes"]["apimgt-gateway"]) {
var tenantBasedClientAppCredentials = tokenUtil.getTenantBasedClientAppCredentials(username);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/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_PORTAL_APP"],
encodedTenantBasedClientAppCredentials);
}
} else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(username);
if (!dynamicClientAppCredentials) {
throw new Error("{/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)");
}
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(dynamicClientAppCredentials["clientId"] + ":" +
dynamicClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS_PORTAL_APP"],
encodedTenantBasedClientAppCredentials);
}
}
};
return publicMethods;
}();

@ -55,7 +55,10 @@ var client = {};
client.validateSignature = function (samlObj, config) {
var tDomain = Util.getDomainName(samlObj);
var tId = carbon.server.tenantId({domain: tDomain});
if (tId != carbon.server.superTenant.tenantId) {
var identityTenantUtil = Packages.org.wso2.carbon.identity.core.util.IdentityTenantUtil;
identityTenantUtil.initializeRegistry(tId,tDomain);
}
return Util.validateSignature(samlObj,
config.KEY_STORE_NAME, config.KEY_STORE_PASSWORD, config.IDP_ALIAS, tId, tDomain);
};

@ -161,6 +161,9 @@
<featureArtifactDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature:${carbon.device.mgt.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature:${carbon.device.mgt.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature:${carbon.device.mgt.version}
</featureArtifactDef>
@ -958,6 +961,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -1904,6 +1911,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -2395,6 +2406,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -2605,6 +2620,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -3046,6 +3065,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -3255,6 +3278,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>
@ -3677,6 +3704,10 @@
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature.group</id>
<version>${carbon.device.mgt.version}</version>

@ -1529,14 +1529,14 @@
<carbon.governance.version>4.7.0</carbon.governance.version>
<!-- Carbon Device Management -->
<carbon.device.mgt.version>2.0.14-SNAPSHOT</carbon.device.mgt.version>
<carbon.device.mgt.version>2.0.16-SNAPSHOT</carbon.device.mgt.version>
<carbon.device.mgt.version.range>[2.0.0, 3.0.0)</carbon.device.mgt.version.range>
<!-- IOT Device Management -->
<product.iot.version>3.1.0-SNAPSHOT</product.iot.version>
<!-- Carbon Device Management Plugins-->
<carbon.device.mgt.plugin.version>3.0.11-SNAPSHOT</carbon.device.mgt.plugin.version>
<carbon.device.mgt.plugin.version>3.0.12-SNAPSHOT</carbon.device.mgt.plugin.version>
<!-- API Management -->
<carbon.api.mgt.version>6.1.65</carbon.api.mgt.version>

Loading…
Cancel
Save