Obtain idp certificate OnApplicationStart
),
DE( "https://" ),
DE( "http://" )
) &
cgi.http_host &
reReplace(
getDirectoryFromPath( arguments.template ), "([^\\/]+[\\/]){#local.requestDepth#}$",
"",
"one"
)
) />
onRequest:check for cert started #(getTickCount()-request.startTickCount)#
Obtain IDP Certificate (onRequest)
onRequest:check for cert finished #(getTickCount()-request.startTickCount)#
#(getTickCount()-request.startTickCount)#
сессия есть
сессии нет
jwt = new lib.jwt(this.client_secret);
idp = new lib.oauth2(this.client_id, this.client_secret, this.auth_endpoint, this.access_token_endpoint, this.redirect_uri);
/*
часто появляется ошибка: после неудачного запроса к IDP
в адресной строке браузера остается все, с чем его редиректил IDP,
а повторный запрос с этим контентом уже не работает. Получаем 400 Bad Request -
может быть, KeyCloak так защищается от циклических редиректов
Не очень понятно, как предотвратить повторный запрос (можно, конечно, использовать сессию, но странно)
*/
writeOutput(getTickCount()-request.startTickCount);
if(structKeyExists(url, "code")) { //обрабатываем редирект от IDP *** наличие поля code в URL введет нас в заблуждение, но эvar = data, label =то только без валидной сессии
dump(var = url.code, label = "URL.code");
// Request access token from idp with the
// authorization code that we got via the URL
//aFormFields = [];
//data = idp.makeAccessTokenRequest((url.code).content, aFormFields);
try {
writeOutput("idp.makeAccessTokenRequest");
writeOutput(getTickCount()-request.startTickCount);
resp = idp.makeAccessTokenRequest(url.code/*, aFormFields*/);
writeOutput("idp.makeAccessTokenRequest Done");
writeOutput(getTickCount()-request.startTickCount);
dump(resp);
data = deserializeJson(resp.content);
//writedump(data);
// Print full response from idp
dump(var = data, label = "makeAccessTokenRequest - Response from idp");
echo('Refresh token #data.refresh_token#');
session.auth.expires_in = data.expires_in;
session.auth.refresh_expires_in = data.refresh_expires_in;
session.auth.access_token = data.access_token;
session.auth.refresh_token = data.refresh_token;
session.auth.id_token = data.id_token;
session.auth.token_type = data.token_type;
session.idp_response_content = structCopy(data);
//flush()
lock scope="application" type="readonly" timeout="1" {
token_data = (jwt.decode(data.access_token, application.idpCertificate,"RS256"));
}
writeOutput("jwt.decode Done");
writeOutput(getTickCount()-request.startTickCount);
writedump(token_data);
session.auth.login = token_data.preferred_username;
session.auth.wz = token_data.ClientID;
session.auth.fullname = token_data.name;
session.auth.groups = token_data.groups;
session.auth.session_state = token_data.session_state;
session.auth.sid = token_data.sid;
session.auth.auth_time = token_data.auth_time;
session.auth.exp = token_data.exp;
session.auth.iat = token_data.iat;
//session.sid = token_data.sid;
session.token_data = structCopy(token_data);
location(this.redirect_uri,false);
} catch (e) {echo('
****************** #e.message# : #e.detail# **********');}
} else {
strURL = idp.buildRedirectToAuthURL({"scope":'openid profile email',"state":session.auth_state,"allow_signup":false});
echo('self-made Auth link (idp) #strURL#
');
location(strUrl,false);
}
--->
select value as stand from config
where name='STAND'
select 1;
//https://keycloak.nubes.ru/admin
//https://keycloak.nubes.ru/realms/SSH_CA/account //smishchuk@mgmt.nubes.ru
//https://stackoverflow.com/questions/28658735/what-are-keycloaks-oauth2-openid-connect-endpoints
//http://https://keycloak.nubes.ru/realms/SSH_CA/.well-known/openid-configuration
//https://keycloak.nubes.ru/realms/cloud/.well-known/openid-configuration тут ссылка
//https://keycloak.nubes.ru/realms/cloud/protocol/openid-connect/certs тут серт
//только надо его обрамить -----BEGIN CERTIFICATE-----
function getIdpCertificate(certUrl) {
var httpService = new http();
httpService.setMethod( "get" );
httpService.setCharset( "utf-8" );
httpService.setUrl(arguments.certUrl);
var result = httpService.send().getPrefix();
var status_code = result.ResponseHeader['Status_Code'];
if ('200' == status_code) {
var content = deserializeJson(result.FileContent);
//мы подразумеваем структуру конкретно KeyCloak
var key = "";
for (key in content.keys) {
if ("RSA" == key.kty AND "sig" == key.use) {
return "-----BEGIN CERTIFICATE-----" & key.x5c[1] & "-----END CERTIFICATE-----";
}
}
throw(message="RSA cetificate not found");
} else {
throw (message="Cannot obtain IDP certificate, request failed", detail="Status_Code #status_code#");
}
}
function auth() {
client_id = "payg-report.deck.nubes.ru"
client_secret = "********"
auth_endpoint = "https://keycloak.nubes.ru/realms/cloud/protocol/openid-connect/auth"
access_token_endpoint = "https://keycloak.nubes.ru/realms/cloud/protocol/openid-connect/token"
redirect_uri = "https://localhost/payg-report/"
jwt = new lib.jwt(client_secret);
idp = new lib.oauth2(client_id, client_secret, auth_endpoint, access_token_endpoint, redirect_uri);
// Get URL that the user will click on and grant our application all necessary permissions
strURL = idp.buildRedirectToAuthURL({"scope":'openid profile email',"state":createGUID().toString(),"allow_signup":true});
echo('self-made Auth link (idp) #strURL#
');
//redreshURL = github.refreshAccessTokenRequest();
if(structKeyExists(url, "code")) {
writedump(url.code);
// Request access token from idp with the authorization code that we got via the URL
data = deserializeJson(idp.makeAccessTokenRequest(url.code/*, aFormFields*/).content);
// Print full response from idp
dump(var = data, label = "makeAccessTokenRequest - Response from idp");
try {
//parsed=getParamsFromUrlString(data);
writedump(data);
echo('Refresh token #data.refresh_token#');
//https://keycloak.nubes.ru/realms/cloud/.well-known/openid-configuration тут ссылка
//https://keycloak.nubes.ru/realms/cloud/protocol/openid-connect/certs тут серт
//только надо его обрамить -----BEGIN CERTIFICATE-----
writedump(jwt.decode(data.access_token,"-----BEGIN CERTIFICATE-----
MIICmTCCAYECBgGG7361eDANBgkqhkiG9w0BAQsFADAQMQ4wDAYDVQQDDAVjbG91ZDAeFw0yMzAzMTcxMjEzMjRaFw0zMzAzMTcxMjE1MDRaMBAxDjAMBgNVBAMMBWNsb3VkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn2segSPrciUFaD7Fa+brR9JdZknQr0F8zCzYQdTPsZJMtYnVPuE7MdZlbtGQ9n/HjcUst8FINjMONhzzbwVQSRZHH57pbAEm4r7fM3QDEAKXGERtDXhVLJGQSkg17X9zSWZs4RwkbxNsG6r+3/GT+U75lTG+/LKKzdG5OHK7Wwnrsiqy7sg3wAPFtlSwbebMdXJ70FosEI1SVhPRDn+LuVH3WINvijQU1GV2srWPwZl16fdXDele6NkvnC032l00pTbkVbgBLgySR0sPsI1s5AuMTT//nA0Xm5Ss40SwLJX2BYWyEALvEYdVt9wUZU2QXcZLLgmsCcFye4HjXa2CAwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBlvkOLPRG6+tB30ZElwKSh/xrptnxgTf93RnS4IUDZebSolR5V/77PFAuqw4DTIlBNtJ6i1ffmyvtZIAMlm3sMZK0GuQ+SFq72DHxYzSmZ61cSS5YFKKyHcX3JIFMXYLmrw11GXt69V3xB8/Y0+BnBBpDD7ZKDdXdQa+9IWsERdTAIFk7ucwiG3BuTOJbzU1d+m8hNIVL4+dYR1TAnA9QPaJaQj0kUD0DYgXcIrrTFIQF0IPeB9I+eOyJ0FxJkukffX7QLVGFrc3+dVRHSSWmMpXi0B/VXT5DlsFDstEldH+/r3XnXAY6qadciyksSBRSXR4Rm9ZEq/xk+VmcxomWc
-----END CERTIFICATE-----","RS256"));
} catch (e) {echo('
****************** #e.message# : #e.detail# **********');}
}
if(structKeyExists(url, "refresh")) {
// With the refresh_token we can easly request a new access token
refreshedToken = deserializeJson(idp.refreshAccessTokenRequest(url.refresh).content);
dump(var = refreshedToken, label = "refreshAccessTokenRequest - Response from IDP");
echo('
Refresh token #refreshedToken.refresh_token#')
writedump(jwt.decode(refreshedToken.access_token));
}
}