service registration with keys enabled

This commit is contained in:
Katerina Iatropoulou 2020-10-16 15:30:25 +00:00
parent 4c5687f36a
commit 94dee47ab3
8 changed files with 241 additions and 27 deletions

View File

@ -12,7 +12,9 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.client.service.impl.StaticClientConfigurationService;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
@ -39,6 +41,9 @@ public class PersonalTokenServlet extends HttpServlet {
@Value("${oidc.id}")
private String id;
@Autowired
private StaticClientConfigurationService staticClientConfigurationService;
private Logger logger = Logger.getLogger(PersonalTokenServlet.class);
public void init(ServletConfig config) throws ServletException {

View File

@ -1,9 +1,11 @@
package eu.dnetlib.openaire.usermanagement;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import eu.dnetlib.openaire.user.pojos.RegisteredService;
import eu.dnetlib.openaire.usermanagement.utils.RegisteredServicesUtils;
import eu.dnetlib.openaire.usermanagement.utils.TokenUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
@ -16,6 +18,7 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
@ -40,11 +43,35 @@ public class RegisterServiceServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//TODO check user's limit
response.setContentType("text/html");
String name = request.getParameter("first_name").trim();
String description = request.getParameter("description").trim();
String keyType = request.getParameter("key_radio").trim();
System.out.println("key type " + keyType);
/*
if (keyType.equals("uri")) {
String jwksUri = request.getParameter("uri");
System.out.println("JWKS URI " + jwksUri);
UrlValidator urlValidator = new UrlValidator();
if (!urlValidator.isValid(jwksUri)){
request.getSession().setAttribute("msg_key_uri_error_display", "display:block");
}
} else {
String jwksString = request.getParameter("value");
System.out.println("JWKS String " + jwksString);
Gson gson = new GsonBuilder().registerTypeAdapter(Jwks.class, new ServiceResponseDeserializer()).create();
Jwks jwks = gson.fromJson(jwksString, Jwks.class);
System.out.println(jwks.keys);
System.out.println(jwks.keys.length);
}
*/
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String userid = authentication.getSub();
String email = authentication.getUserInfo().getEmail();

View File

@ -1,5 +1,7 @@
package eu.dnetlib.openaire.usermanagement;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import eu.dnetlib.openaire.user.pojos.RegisteredService;
import eu.dnetlib.openaire.usermanagement.utils.RegisteredServicesUtils;
import eu.dnetlib.openaire.usermanagement.utils.TokenUtils;
@ -51,6 +53,7 @@ public class RegisteredServicesServlet extends HttpServlet {
try {
registeredServices = registeredServicesUtils.
getRegisteredServiceDao().fetchAllRegisteredServicesByOwner(userId);
System.out.println("LOAD REGISTERED SERVICES. " + registeredServices);
} catch (SQLException sqle) {
@ -62,21 +65,40 @@ public class RegisteredServicesServlet extends HttpServlet {
}
Map<String, ServiceResponse> serviceResponses = new HashMap<>();
Map<String, String> serviceKey = new HashMap<>();
for (RegisteredService registeredService:registeredServices) {
serviceResponses.put(registeredService.getId(),
TokenUtils.getRegisteredService(registeredService.getAai_id(),authentication.getAccessTokenValue()));
ServiceResponse serviceResponse = TokenUtils.getRegisteredService(registeredService.getAai_id(),authentication.getAccessTokenValue());
serviceResponses.put(registeredService.getId(), serviceResponse);
serviceKey.put(registeredService.getId(), extractPublicKeySet(serviceResponse));
}
boolean reachedLimit = reachedMaximumNumberOfServices(registeredServices);
request.getSession().setAttribute("reachedLimit", reachedLimit);
request.getSession().setAttribute("test", "TEST");
System.out.println("REACHED LIMIT??? " + reachedLimit);
request.getSession().setAttribute("services", serviceResponses);
request.getSession().setAttribute("keys", serviceKey);
request.getSession().setAttribute("registeredServices", registeredServices);
response.setContentType("text/html");
request.getRequestDispatcher("./registeredServices.jsp").include(request, response);
}
private String extractPublicKeySet(ServiceResponse serviceResponse) {
if (serviceResponse.getJwksUri()!=null && !serviceResponse.getJwksUri().isEmpty())
return serviceResponse.getJwksUri();
return extractJSONJwk(serviceResponse.getJwks());
}
private String extractJSONJwk(Jwks jwks) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(jwks));
return gson.toJson(jwks);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.

View File

@ -148,11 +148,59 @@ public class ServiceRequest {
}
}
class Jwks implements Serializable {
Key[] keys = new Key[]{new Key()};
}
class Key implements Serializable {
/* String kty;
String e;
String kid;
String alg;
String n;
public String getKty() {
return kty;
}
public void setKty(String kty) {
this.kty = kty;
}
public String getE() {
return e;
}
public void setE(String e) {
this.e = e;
}
public String getKid() {
return kid;
}
public void setKid(String kid) {
this.kid = kid;
}
public String getAlg() {
return alg;
}
public void setAlg(String alg) {
this.alg = alg;
}
public String getN() {
return n;
}
public void setN(String n) {
this.n = n;
}
*/
String kty = "RSA";
String e = "AQAB";
String kid = "05794a3c-a6f5-430c-9822-da4e53597ba5";

View File

@ -119,7 +119,7 @@ public class Test3Service {
params.add(new BasicNameValuePair("client_secret", secret));
params.add(new BasicNameValuePair("grant_type", "refresh_token"));
params.add(new BasicNameValuePair("refresh_token", refreshToken));
params.add(new BasicNameValuePair("scope", "openid email profile offline_access"));
params.add(new BasicNameValuePair("scope", "openid"));
HttpResponse response = null;
@ -166,7 +166,7 @@ public class Test3Service {
params.add(new BasicNameValuePair("client_secret", secret));
params.add(new BasicNameValuePair("grant_type", "refresh_token"));
params.add(new BasicNameValuePair("refresh_token", accessToken));
params.add(new BasicNameValuePair("scope", "openid email profile"));
params.add(new BasicNameValuePair("scope", "openid"));
try {
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.

View File

@ -16,6 +16,7 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import javax.xml.ws.Service;
@ -23,11 +24,12 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
public class TokenUtils {
Logger logger = Logger.getLogger(TokenUtils.class);
private Logger logger = Logger.getLogger(TokenUtils.class);
public static String registerService(String userId, String name, String description, String email, String accessToken)
throws IOException {

View File

@ -17,7 +17,6 @@
<title>OpenAIRE - Register</title>
<script src="./js/jquery.js"></script>
<script src="./js/uikit.js"></script>
<script src="./js/validation.js"></script>
<script src="./js/uikit-icons-max.js"></script>
<link rel="stylesheet" style="text/css" href="./css/theme.css">
<link rel="stylesheet" style="text/css" href="./css/custom.css">
@ -95,37 +94,86 @@
<!-- CENTER SIDE -->
<div class="uk-width-2-3@l uk-width-2-3@m">
<h2 class="uk-h2 uk-margin-small-bottom">Add a new service</h2>
<%--<div class="uk-text-meta uk-margin-large-bottom">Use the same credentials for all our services</div>--%>
<h4 class="uk-h4">Please provide the basic information on your new service</h4>
<div class="middle-box text-center loginscreen animated fadeInDown ">
<div class="k-width-1-1@m uk-width-1-1@s uk-text-center">
<!-- REGISTER FORM -->
<div id="registerForm">
<form action="registerService" method="POST" role="form" class="m-t" id="register_form">
<form action="registerService" method="POST" role="form" class="m-t uk-form-horizontal" id="register_form">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div class="alert alert-success" aria-hidden="true" style="display: none;"></div>
<div class="alert alert-danger" aria-hidden="true" style="display: none;"></div>
<span id="server_error" class="uk-text-danger uk-text-small uk-float-left">${message}</span>
<c:remove var="message" scope="session" />
<div class="form-group">
<h5 class="uk-h5">General</h5>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Name(*)</label>
<span class="msg_first_name_error uk-text-danger uk-text-small uk-float-left" style='${msg_first_name_error_display}'>Please enter a name for your service.</span>
<input id="first_name" name="first_name" type="text" placeholder="Name (*)" class="form-control" value=${first_name}></div>
<input id="first_name" name="first_name" type="text" placeholder="Name (*)" class="form-control" value=${first_name}>
<c:remove var="msg_first_name_error_display" scope="session" />
<c:remove var="first_name" scope="session" />
<div class="form-group">
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Description</label>
<textarea id="description" name="description" type="textarea" placeholder="Description:" class="form-control uk-textarea" rows="3" value=${description}></textarea>
<c:remove var="organization" scope="session" />
</div>
<hr class="uk-margin-remove-top">
<h5 class="uk-h5">Access</h5>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Scope</label>
<input disabled value="openid" class="uk-input"></input>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Grant Types</label>
<input disabled value="client credentials" class="uk-input"></input>
</div>
<hr class="uk-margin-remove-top">
<h5 class="uk-h5">Credentials</h5>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Authentication Method</label>
<input disabled value="Asymmetrically-signed JWT assertion" class="uk-input"></input>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Token Endpoint Authentication Signing Algorithm</label>
<input disabled value="RSASSA using SHA-256 hash algorithm" class="uk-input"></input>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-horizontal-text">Public Key Set</label>
<label><input class="uk-radio" type="radio" name="key_radio" value="value" checked>By Value</label>
<label><input class="uk-radio" type="radio" name="key_radio" value="uri">By URI</label><br>
<div id="value_input">
<span class="msg_key_value_error uk-text-danger uk-text-small uk-float-left" style='${msg_key_value_error_display}'>Please provide a valid JSON.</span>
<textarea id="value" name="value" type="textarea" placeholder='{"keys":[]}' class="form-control uk-textarea" rows="10"></textarea>
</div>
<div id="uri_input" style="display:none;">
<span class="msg_key_uri_error uk-text-danger uk-text-small uk-float-left" style='${msg_key_uri_error_display}'>Please provide a valid URI.</span>
<input id="uri" name="uri" type="text" placeholder="https://" class="form-control" value="${jwksUri}">
</div>
</div>
<hr class="uk-margin-remove-top">
<div class="uk-width-1-1 uk-grid-margin uk-first-column">
<a type="submit" class="uk-button uk-button-default" href="./registeredServices">Cancel</a>
<button type="submit" class="uk-button uk-button-primary" onclick="return validate();">Add new service</button>
</div>
</div>
</form>
</div>
<!-- END OF REGISTER FORM -->
<script>
$('input[type=radio][name=key_radio]').change(function() {
if (this.value == 'uri') {
$("#uri_input").show();
$("#value_input").hide();
} else if (this.value == 'value') {
$("#uri_input").hide();
$("#value_input").show();
}
});
function validate() {
// Check if name is filled
var isValid = false;
if($("#first_name").val() != undefined) {
if($.trim($("#first_name").val()).length <= 0) {
$("#first_name").addClass('uk-input aai-form-danger');
@ -135,13 +183,69 @@
$(".msg_first_name_error").hide();
$("#first_name").removeClass('aai-form-danger');
}
}
if ($('input[type=radio][name=key_radio]:checked').val()==='value') {
isValid = validateJSON();
if (!isValid) {
$("#value_input").addClass('uk-input aai-form-danger');
$(".msg_key_value_error_display").show();
return false;
}
}
if ($('input[type=radio][name=key_radio]:checked').val()==='uri') {
isValid = validateURI();
if (!isValid) {
$("#uri_input").addClass('uk-input aai-form-danger');
$(".msg_key_uri_error_display").show();
return false;
}
}
}
function validateJSON() {
if ($("#value").val() != undefined && $("#value").val()!=="") {
if (/^[\],:{}\s]*$/.test($("#value").val().replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
return true;
} else {
return false;
}
}
return false;
}
function validateURI() {
if ($("#uri").val() != undefined && $("#uri").val()!=="") {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test($("#uri").val());
}
return false;
}
$("#first_name").focusin(function () {
$(this).removeClass('aai-form-danger');
$(".msg_first_name_error").fadeOut();
});
$("#value_input").focusin(function () {
$(this).removeClass('aai-form-danger');
$(".msg_key_value_error").fadeOut();
});
$("#uri_input").focusin(function () {
$(this).removeClass('aai-form-danger');
$(".msg_key_uri_error").fadeOut();
});
</script>
</div>
</ul>

View File

@ -19,6 +19,7 @@
<link rel="icon" type="image/png" sizes="96x96" href="images/favicon//favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png">
<link href="images/favicon/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
</head>
<body class="" style="">
<div class="uk-offcanvas-content uk-height-viewport">
@ -116,7 +117,7 @@
</c:if>
<c:if test="${registeredServices.size() > 0}">
<!-- REGISTER FORM -->
<ul class="uk-list">
<li>
<div class="uk-grid uk-child-width-1-3 uk-text-muted">
@ -125,15 +126,14 @@
<div>Actions</div>
</div>
</li>
>>> ${registeredServices.size()}
${services}
<c:forEach items="${registeredServices}" var="registeredService">
<c:forEach items="${registeredServices}" var="registeredService" varStatus="loop">
<c:set var="key" value="${registeredService.id}"/>
<li>
<hr class="uk-margin-remove-top">
<div class="uk-grid uk-child-width-1-3">
<div ><a uk-toggle="target: #details${registeredService.id}; animation: uk-animation-fade">${registeredService.name} <span uk-icon="icon:info;ratio:0.7"></span></a>
</div>
<div>${registeredService.date}</div>
<div><fmt:formatDate value="${registeredService.date}" pattern="dd-MM-yyyy HH:mm" /></div>
<div>
<a href="./editRegisteredService?id=${registeredService.id}"><span class="uk-margin-small-right" uk-icon="pencil" ></span>
@ -158,10 +158,15 @@
</li>
<li id="details${registeredService.id}" hidden="hidden" >
<div class="uk-alert">
<p>Service Name: </p>
<p>Service Description: </p>
<p>Service Id:</p>
<p>Creation Date:</p>
<p><em>Name</em>: ${services[key].clientName}</p>
<p><em>Description</em>: ${services[key].clientDescription}</p>
<p><em>Scope</em>: openid</p>
<p><em>Grant type</em>: client credentials</p>
<p><em>Authentication Method</em>: Asymmetrically-signed JWT assertion</p>
<p><em>Token Endpoint Authentication Signing Algorithm</em>: RSASSA using SHA-256 hash algorithm</p>
<p><em>Public Key Set(*)</em>: <pre><code>${keys[key]}</code></pre></p>
<p><em>Creation Date</em>: ${services[key].createdAt}</p>
</p>
</div>
</li>
</c:forEach>
@ -181,6 +186,7 @@
</button>
</c:otherwise>
</c:choose>
<c:remove var="reachedLimit" scope="session"/>
</div>
</div>