rpt-token-portlet/src/main/webapp/html/rpttokenreader/view.jsp

492 lines
15 KiB
Plaintext

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@include file="../init.jsp" %>
<%@ page import="org.gcube.vomanagement.usermanagement.model.GCubeGroup" %>
<portlet:defineObjects />
<portlet:resourceURL var="resourceURL">
</portlet:resourceURL>
<% List<GCubeGroup> userGroups = (List<GCubeGroup>) request.getAttribute("userGroups");
pageContext.setAttribute("userGroups", userGroups);
List<String> userContexts = (List<String>) request.getAttribute("userContexts");
pageContext.setAttribute("userContexts", userContexts);
String sub = "-";
if (userContexts != null && userContexts.size()>0){
sub = userContexts.get(0).substring(userContexts.get(0).lastIndexOf("/") + 1);
}
pageContext.setAttribute("firstContextName", sub);
%>
<script type="text/javascript">
var global_token_response = {};
function formatDuration(seconds) {
console.log("seconds", seconds);
if (!seconds) {
return "";
}
if (seconds < 0) seconds *= seconds;
var intervals = {
day: Math.floor(seconds / (60 * 60 * 24)),
hour: Math.floor(seconds / (60 * 60)) % 24,
minute: Math.floor(seconds / 60) % 60,
second: Math.floor(seconds / 1) % 60
};
return Object.entries(intervals)
.filter(val => val[1] !== 0)
.map(([key, val]) => "" + val + " " + key + (val != 1 ? 's' : ''))
.join(', ');
}
function initForm() {
$('#response_group').hide();
$('#error_msg').hide();
$('#rawTokenResult').hide();
openInfo('intro_info')
closeInfo('token_info')
closeInfo('refresh_token_info')
closeInfo('refresh')
console.log("hided response_group")
}
function resetResults() {
// $('#buttonCopy').hide();
// $('#buttonDecode').hide();
$('#tokenResult').text('');
$('#tokenResultDetails').text('');
$('#refreshTokenResult').text('');
$('#refreshTokenResultDetails').text('');
$('#rawTokenResult').text('');
$('#error_msg').html("")
$('#refresh_token_url').html('');
$('#client_id').html('');
}
function setResults(resultObject) {
global_token_response = resultObject;
$('#tokenResult').text(resultObject.access_token);
$('#refreshTokenResult').text(resultObject.refresh_token);
$('#refresh_token_url').text(resultObject.token_url);
$('#client_id').text(resultObject.client_id);
$('#usage_token').html(generateAccessCurl("[ACCESS_TOKEN]", "[SERVICE_URL]"))
$('#usage_refresh').html(generateRefreshCurl("[CLIENT_ID]", "[REFRESH_TOKEN]", "[REFRESH_URL]"))
var raw = JSON.parse(resultObject.raw_token)
var expires_in = raw.expires_in;
if (expires_in) {
$('#tokenResultDetails').html('expires in <b>' + formatDuration(expires_in) + '</b>');
}
var refresh_expires_in = raw.refresh_expires_in;
if (expires_in) {
$('#refreshTokenResultDetails').html('expires in <b>' + formatDuration(refresh_expires_in) + '</b>');
}
var not_before_policy = raw["not-before-policy"];
console.log("expires_in", expires_in);
console.log("refresh_expires_in", refresh_expires_in);
console.log("not-before-policy", not_before_policy);
$('#rawTokenResult').html(JSON.stringify(raw, undefined, 4));
$('#response_group').show();
console.log("resultObject", resultObject)
//closeInfo('intro_info', false);
// closeInfo('token_info', true);
// closeInfo('refresh_token_info', true);
}
function setError(error_comment) {
$('response_group').hide();
$('#error_msg').show();
$('#error_msg').html(error_comment);
}
function getUMAToken(endpoint) {
console.log("getUMAToken:" + endpoint);
$('#umaButton').attr("disabled", true);
resetResults();
var selectedContext = $("#myselect").val();
console.log("selected context: ", selectedContext);
$.ajax({
url: endpoint,
type: 'POST',
datatype: 'json',
data: {
context: selectedContext
},
success: function (data) {
$("#intro").hide();
var raw = JSON.stringify(data)
var resultObject = JSON.parse(raw);
if (resultObject.success) {
setResults(resultObject);
} else {
setError(resultObject.comment)
}
$('#umaButton').attr("disabled", false);
},
error: function (xhr, status, error) {
console.error("error", xhr, status, error);
setError("Server error, cannot obtain the token");
$('#umaButton').attr("disabled", false);
}
});
}
function openInfo(destination_id) {
toggleInfo(destination_id, true)
}
function closeInfo(destination_id, do_switch) {
toggleInfo(destination_id, false)
}
function toggleInfo(destination_id, do_switch) {
$("#" + destination_id).toggle(do_switch);
do_switch = $("#" + destination_id).css('display') != 'none';
$("#" + destination_id + "_icon").toggleClass("icon-chevron-up", do_switch);
$("#" + destination_id + "_icon").toggleClass("icon-chevron-down", !do_switch);
}
function decodeFunction(text_id) {
var decode_text = $("#" + text_id).val();
window.open(
"https://jwt.io/#id_token=" + encodeURIComponent(decode_text),
'_blank'
);
}
function generateAccessCurl(token, service_url) {
return "curl -X GET -H 'Authorization: Bearer " + token + "' \\\n"
+ "\t " + service_url
}
function generateRefreshCurl(client_id, refresh_token, refresh_url) {
return "curl -X POST --location '" + refresh_url + "' \\\n" +
// "\t--header 'Content-Type: application/x-www-form-urlencoded' \\\n" +
"\t--data-urlencode 'grant_type=refresh_token' \\\n" +
"\t--data-urlencode 'client_id=" + client_id + "' \\\n" +
"\t--data-urlencode 'refresh_token=" + refresh_token + "' "
// return "curl --request POST " +
// "--data " +
// "'refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJjOTk5YmVjNC1iNDc4LTQ4Y2YtYmI5OS0wMWMxODY5NzcwNGIifQ.eyJleHAiOjE3MTA5NDMyNzcsImlhdCI6MTcwOTczMzY3NywianRpIjoiYTEyNWNkNjUtYTJlYi00OTM3LWEwODAtNzZkYjMxNThlZGU0IiwiaXNzIjoiaHR0cHM6Ly9hY2NvdW50cy5kZXYuZDRzY2llbmNlLm9yZy9hdXRoL3JlYWxtcy9kNHNjaWVuY2UiLCJhdWQiOiJodHRwczovL2FjY291bnRzLmRldi5kNHNjaWVuY2Uub3JnL2F1dGgvcmVhbG1zL2Q0c2NpZW5jZSIsInN1YiI6ImI5OTY5YjUxLTU3OGYtNGI2OS1hNTNmLTJjOGFkZjllZmNjNyIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJuZXh0LmRldi5kNHNjaWVuY2Uub3JnIiwic2Vzc2lvbl9zdGF0ZSI6IjczMzVjZGY5LTFlMjUtNGU5OC1iNjg2LWM1ZTg1NGU2MmQ4OCIsImF1dGhvcml6YXRpb24iOnsicGVybWlzc2lvbnMiOlt7InJzaWQiOiI1NzI4NTUxMC0zOTM5LTRkZTctOGZjMS1lM2E5ZDNjY2UyODEiLCJyc25hbWUiOiJEZWZhdWx0IFJlc291cmNlIn1dfSwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwic2lkIjoiNzMzNWNkZjktMWUyNS00ZTk4LWI2ODYtYzVlODU0ZTYyZDg4In0.q6T2tVSvMXJzxaxRGavGaghRB9myk4CSjhO_-mvOXxY" +
// "&client_id=next.dev.d4science.org" +
// "&grant_type=refresh_token' " +
// "https://accounts.dev.d4science.org/auth/realms/d4science/protocol/openid-connect/token"
}
function copyText(text) {
var listener = function (ev) {
ev.clipboardData.setData("text/plain", text);
ev.preventDefault();
};
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
navigator.clipboard.writeText(text).then(function () {
/* clipboard successfully set */
}, function () {
/* clipboard write failed */
});
}
function copyAccessCurl() {
// ***.dev.d4science.org => api.dev.d4science.org
// ***.pre.d4science.org => api.pre.d4science.org
// xxx.d4science.org => api.d4science.org
var client_id = global_token_response.client_id;
var service_path = "api.d4science.org";
if (client_id.endsWith("dev.d4science.org")){
service_path = "api.dev.d4science.org";
} else if (client_id.endsWith("pre.d4science.org")){
service_path = "api.pre.d4science.org";
}
var curl = generateAccessCurl(
global_token_response.access_token,
"https://" + service_path + "/catalogue/items");
copyText(curl);
}
function copyRefreshCurl() {
var curl = generateRefreshCurl(
global_token_response.client_id,
global_token_response.refresh_token,
global_token_response.token_url);
copyText(curl);
}
function copyFromTextField(text_id) {
/* Get the text field */
var copyText = document.getElementById(text_id);
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
document.execCommand("copy");
}
</script>
<c:if test="${userContexts.size() == 0}">
<div class="alert alert-error">
Configuration error, no context available
</div>
</c:if>
<div>
<c:if test="${userContexts.size() == 1}">
<p>Current context: ${firstContextName}</p>
<input type="hidden" name="contexts" id="myselect" value="${userContexts[0]}">
</c:if>
<c:if test="${userContexts.size() > 1}">
<p>Select the context:</p>
<div>
<select style="width: 100%;" name="contexts" id="myselect">
<c:forEach var="context" items="${userContexts}">
<option value="${context}">${context}</option>
</c:forEach>
</select>
</div>
</c:if>
<div class="row">
<div>
<c:if test="${userContexts.size() >= 1}">
<button name="umaButton" id="umaButton" type="button"
class="btn btn-primary" onClick="getUMAToken('${resourceURL}')">Get
Token</button>
</c:if>
</div>
</div>
</div>
<br>
<div id="response_group">
<div id="response_group_token" class="well well-small">
<div class="row">
<span class="span9"><b>OAuth Access Token <br> (Bearer Authorization)</b></span>
<button id="buttonInfo" data-toggle="tooltip" class="btn btn-small pull-right span2"
onclick="toggleInfo('token_info')" title="Toggle infos"
alt="Toggle infos">
<i class="icon-info"></i>
<i id="token_info_icon" class="icon-chevron-down"></i>
</button>
</div>
<textarea rows=" 2" id="tokenResult" class="disabled span12" readonly></textarea>
<div class="row">
<span class="help-block span9" id='tokenResultDetails'></span>
<div class="btn-group btn-group span2">
<button id="buttonDecode" data-toggle="tooltip" class="btn btn-small"
onclick="decodeFunction('tokenResult')" title="Decode" alt="Decode">
<i class="icon-eye-open"></i>
</button>
<button id="buttonCopy" data-toggle="tooltip" class="btn btn-small"
onclick="copyFromTextField('tokenResult')" title="Copy" alt="Copy">
<i class="icon-copy"></i>
</button>
</div>
</div>
<div id="token_info" style="display: none;" class="well well-small bg_white">
<p>Personal Token used to access protected resources</p>
<p>The token has a limited lifespan and must be included as a Bearer
token
in the Authorization header of the http request"</p>
<p>usage:<br>
<code id="usage_token" class="wraptext">curl -H "Authorization: Bearer [ACCESS_TOKEN] " \<br>&emsp;https://api.example.com/userinfo</code>
</p>
<p>
ref: <a
href="https://oauth.net/2/access-tokens">https://oauth.net/2/access-tokens/
</a>
</p>
<div class="row">
generate curl access request example: <button id="buttonGeneratAccessCurl"
data-toggle="tooltip" class="btn btn-small pull-right"
onclick="copyAccessCurl()" title="Copy to clipboard"
alt="Copy to clipboard">
<i class="icon-copy"></i>
</button>
</div>
</div>
</div>
<div id="response_group_refreshToken" class="well well-small">
<div class="row">
<span span9><b>Oauth2 Refresh Token</b></span>
<button id="buttonInfo" data-toggle="tooltip" class="btn btn-small pull-right"
onclick="toggleInfo('refresh_token_info')" title="Toggle infos"
alt="Toggle infos">
<i class="icon-info"></i>
<i id="refresh_token_info_icon" class="icon-chevron-down"></i>
</button>
</div>
<textarea rows=" 2" id="refreshTokenResult" class="disabled span12"
readonly></textarea>
<div class="row">
<span class="help-block span9" id='refreshTokenResultDetails'></span>
<div class="btn-group btn-group span2">
<button id="buttonDecodeRefresh" data-toggle="tooltip" class="btn btn-small"
onclick="decodeFunction('refreshTokenResult')" title="Decode"
alt="Decode">
<i class="icon-eye-open"></i>
</button>
<button id="buttonCopy" data-toggle="tooltip" class="btn btn-small"
onclick="copyFromTextField('refreshTokenResult')" title="Copy"
alt="Copy">
<i class="icon-copy"></i>
</button>
</div>
</div>
<div id="refresh_token_info" style="display: none;" class="well well-small bg_white">
<p>Use this token to programmaticaly refresh the Access token.
</p>
<p>usage:<br>
<code class="wraptext" id="usage_refresh"></code>
</p>
ref: <a href="https: //oauth.net/2/refresh-tokens/">
https://oauth.net/2/refresh-tokens/</a>
<div class="row">
generate curl refresh request: <button id="buttonGenerateRefreshCurl"
data-toggle="tooltip" class="btn btn-small pull-right"
onclick="copyRefreshCurl()" title="Copy to clipboard"
alt="Copy to clipboard">
<i class="icon-copy"></i>
</button>
</div>
</div>
</div>
<div id="parameters" class="well well-small">
<div class="row" onclick="toggleInfo('refresh')">
<span><b>Refresh parameters</b></span>
<i id="refresh_icon" class="icon-chevron-down pull-right"></i>
</div>
<div id="refresh">
<div class="row">
<br>
refresh token url: <code class="wraptext" id="refresh_token_url"></code>
<button id="refresh_token_url_copy" data-toggle="tooltip"
class="btn btn-small pull-right"
onclick="copyText(global_token_response.token_url)"
title="copy refresh token url" alt="copy refresh token url">
<i class="icon-copy"></i>
</button>
</div>
<div class="row">
client_id: <code class="wraptext" id="client_id"></code> <button
id="client_id_copy" data-toggle="tooltip" class="btn btn-small pull-right"
onclick="copyText(global_token_response.client_id)"
title="copy refresh token url" alt="copy refresh token url">
<i class="icon-copy"></i>
</button><br>
</div>
<div class="row">
generate curl refresh request: <button id="buttonGenerateRefreshCurl"
data-toggle="tooltip" class="btn btn-small pull-right"
onclick="copyRefreshCurl()" title="Copy to clipboard"
alt="Copy to clipboard">
<i class="icon-copy"></i>
</button>
</div>
</div>
</div>
<div id="div_decode">
You can decode the tokens using <a href="https://jwt.io/#debugger-io"
target="blank">https://jwt.io/</a>
</div>
</div>
<div class="well well-small" id="intro_container">
<div class="row" onclick="toggleInfo('intro_info')">
<span><b>Instructions</b></span>
<i id="intro_info_icon" class="icon-chevron-down pull-right"></i>
</div>
<div id="intro_info" class="well well-small bg_white">
<p>Obtain your personal OAuth2 Access and Refresh Tokens, to be used for
programmatic interaction with the Resources</p>
<p> Do not use this token to authenticate services but only for personal
access
</p>
<p>
ref:
<ul>
<li><a href="https://dev.d4science.org/how-to-access-resources">
Accessing Resources - how to</a></li>
<li><a
href="https://www.oauth.com/oauth2-servers/making-authenticated-requests">OAuth2:
Making Authenticated Requests</a></li>
<li><a
href="https://www.oauth.com/oauth2-servers/making-authenticated-requests/refreshing-an-access-token/">OAuth2:
Refresh Tokens</a></li>
</ul>
</p>
<p>Please Note: if you need long lasting refresh tokens (14 days) tick 'remember me' option during Sign In. For service to service interaction you may obtain a service account by opening a <a href="https://support.d4science.org" target="_blank">support request</a>.
</p>
</div>
</div>
<div id="error_msg" class="alert alert-error">
Configuration error, no context available
</div>
<script>
initForm();
</script>