diff --git a/pom.xml b/pom.xml index 371ba55..d2b2938 100644 --- a/pom.xml +++ b/pom.xml @@ -8,9 +8,8 @@ 4.0.0 dnet-openaire-users war - 2.1.1-BETA-SNAPSHOT + 3.0.0-BETA-SNAPSHOT - scm:git:gitea@code-repo.d4science.org:MaDgIK/dnet-openaire-users.git scm:git:gitea@code-repo.d4science.org:MaDgIK/dnet-openaire-users.git https://code-repo.d4science.org/MaDgIK/dnet-openaire-users/ HEAD @@ -21,11 +20,6 @@ uoa-user-management 2.0.5 - - eu.dnetlib - uoa-login-core - 1.0.3 - org.slf4j slf4j-api @@ -56,6 +50,7 @@ javax.servlet-api 3.0.1 + org.springframework.security spring-security-core @@ -71,6 +66,34 @@ spring-security-web 4.2.1.RELEASE + + + org.springframework.session + spring-session-data-redis + 1.3.1.RELEASE + pom + + + biz.paluch.redis + lettuce + 3.5.0.Final + + + javax.servlet + javax.servlet-api + 3.0.1 + + + org.mitre + openid-connect-client + 1.3.0 + + + org.bouncycastle + bcprov-jdk15on + + + com.google.code.gson gson diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/JwksDeserializer.java b/src/main/java/eu/dnetlib/openaire/usermanagement/JwksDeserializer.java deleted file mode 100644 index 33fa63b..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/JwksDeserializer.java +++ /dev/null @@ -1,70 +0,0 @@ -package eu.dnetlib.openaire.usermanagement; - -import com.google.gson.*; - -import java.lang.reflect.Type; - -public class JwksDeserializer implements JsonDeserializer { - - @Override - public Jwks deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) - throws JsonParseException { - - JsonObject jsonObject = jsonElement.getAsJsonObject(); - if (jsonObject == null) throw new JsonParseException("Jwks not valid."); - JsonArray jsonArray = jsonObject.getAsJsonArray("keys"); - - if (jsonArray == null ) throw new JsonParseException("Jwks not valid."); - - Jwks jwks = new Jwks(); - Key[] keys = new Key[jsonArray.size()]; - - Key key = null; - for (int i = 0; i < jsonArray.size(); i++) { - key = new Key(); - JsonElement je = jsonArray.get(i); - - if (je == null) throw new JsonParseException("Jwks not valid."); - if (je.getAsJsonObject().get("kty")==null) throw new JsonParseException("Jwks not valid."); - key.setKty(je.getAsJsonObject().get("kty").getAsString()); - - if (je.getAsJsonObject().get("e")==null) throw new JsonParseException("Jwks not valid."); - key.setE(je.getAsJsonObject().get("e").getAsString()); - - if (je.getAsJsonObject().get("kid")==null) throw new JsonParseException("Jwks not valid."); - key.setKid(je.getAsJsonObject().get("kid").getAsString()); - - if (je.getAsJsonObject().get("alg")==null) throw new JsonParseException("Jwks not valid."); - key.setAlg(je.getAsJsonObject().get("alg").getAsString()); - - if (je.getAsJsonObject().get("n")==null) throw new JsonParseException("Jwks not valid."); - key.setN(je.getAsJsonObject().get("n").getAsString()); - keys[i] = key; - } - - jwks.setKeys(keys); - return jwks; - } -} -/* - public static void main(String[] args) { - Gson gson = new GsonBuilder().registerTypeAdapter(Jwks.class, new JwksDeserializer()).create(); - - String jwksJson = "{\n" + - " \"keys\": [\n" + - " {\n" + - " \"kty\": \"RSA\",\n" + - " \"e\": \"AQAB\",\n" + - " \"kid\": \"05794a3c-a6f5-430c-9822-da4e53597ba5\",\n" + - " \"alg\": \"RS256\",\n" + - " \"n\": \"hm_OUny05OJEwbGBqPjE7wWvnwTMgqUHJFis_S9nM7hTivXQ_LX9f89RaVcPpXboox81Y8rrfuVwV0nc-FGr_E0FFpI-IwJ_sUUEDwf-5Qxor3LNc_S_5BiPOfFHY7c-R-ablRIAvVTXqwIjcyLVQnaHLjb9XQPf9lBt9sCZ2jN-9HOLztMO3BZWZYIFqvNr8ySKHfVPdlk0Wx3N45KPY0kgxk5RPYW0HLRakSlhIJtqYCJOr2IiDUEMAj9Z9BoWjeUKiAX3E3ZRo-DO1TWcc7feq-0Pei2IBw3lvNpgcBBv1_BlrsZYzQqkKOcDbLAppuhR3inUNhc3G67OuWt8ow\"\n" + - " }\n" + - " ]\n" + - "}"; - Jwks jwks = gson.fromJson(jwksJson, Jwks.class); - for(Key key:jwks.getKeys()) { - //System.out.println(key.getE()); - } - } -} -*/ \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/OverviewServlet.java b/src/main/java/eu/dnetlib/openaire/usermanagement/OverviewServlet.java index 0fbe4f3..7d6baf3 100644 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/OverviewServlet.java +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/OverviewServlet.java @@ -1,9 +1,9 @@ package eu.dnetlib.openaire.usermanagement; -import org.mitre.openid.connect.model.OIDCAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; +import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; @@ -12,22 +12,16 @@ import java.io.IOException; public class OverviewServlet extends HttpServlet { - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + @Value("${developers.url}") + private String url; - boolean isAuthenticated = !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString() - .equals("anonymousUser"); + public void init(ServletConfig config) throws ServletException { + super.init(config); + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, + config.getServletContext()); + } - if (isAuthenticated) { - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); - - StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0)); - name.append(authentication.getUserInfo().getFamilyName().charAt(0)); - request.getSession().setAttribute("authenticated", isAuthenticated); - request.getSession().setAttribute("name", name.toString()); - } - - response.setContentType("text/html"); - request.getRequestDispatcher("./overview.jsp").include(request, response); + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(url + "/"); } } diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/PersonalTokenServlet.java b/src/main/java/eu/dnetlib/openaire/usermanagement/PersonalTokenServlet.java index 5eb9ae8..b80b19b 100644 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/PersonalTokenServlet.java +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/PersonalTokenServlet.java @@ -1,19 +1,6 @@ package eu.dnetlib.openaire.usermanagement; -import com.google.gson.Gson; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -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.core.context.SecurityContextHolder; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import javax.servlet.ServletConfig; @@ -22,25 +9,11 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; public class PersonalTokenServlet extends HttpServlet { - @Value("${oidc.secret}") - private String secret; - - @Value("${oidc.id}") - private String id; - - @Value("${oidc.issuer}") - private String issuer; - - @Autowired - private StaticClientConfigurationService staticClientConfigurationService; - - private Logger logger = Logger.getLogger(PersonalTokenServlet.class); + @Value("${developers.url}") + private String url; public void init(ServletConfig config) throws ServletException { super.init(config); @@ -48,69 +21,7 @@ public class PersonalTokenServlet extends HttpServlet { config.getServletContext()); } - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html"); - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); - StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0)); - name.append(authentication.getUserInfo().getFamilyName().charAt(0)); - request.getSession().setAttribute("name", name.toString()); - request.getSession().setAttribute("accessToken", authentication.getAccessTokenValue()); - request.getSession().setAttribute("refreshToken", authentication.getRefreshTokenValue()); - request.getRequestDispatcher("./personal.jsp").include(request, response); + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(url + "/personal-token"); } - - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); - String refreshToken = authentication.getRefreshTokenValue(); - List oldRefreshTokens = null; - - try { - oldRefreshTokens = getOldRefreshTokens(authentication.getRefreshTokenValue(), authentication.getAccessTokenValue()); - deleteOldRefreshTokens(oldRefreshTokens, authentication.getAccessTokenValue()); - - } catch (IOException e) { - logger.error("Error deleting old refresh tokens.", e); - //TODO should I let user know? - } - request.getSession().setAttribute("showRefreshToken", true); - response.sendRedirect("./personalToken"); - } - - private void deleteOldRefreshTokens(List oldRefreshTokens, String accessToken) throws IOException { - HttpDelete httpDelete; - CloseableHttpClient httpclient = HttpClients.createDefault(); - - for (String refreshTokenId:oldRefreshTokens) { - httpDelete = new HttpDelete(issuer + "/api/tokens/refresh/" + refreshTokenId); - httpDelete.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); - HttpResponse response = httpclient.execute(httpDelete); - if (response.getStatusLine().getStatusCode()!=200) { - logger.warn("Could not delete old refresh tokens." + response.getStatusLine().getStatusCode()); - //System.out.println("Could not delete old refresh tokens." + response.getStatusLine().getStatusCode());//TODO should I throw exception? - } - } - } - - private List getOldRefreshTokens(String currentRefreshToken, String accessToken) throws IOException { - HttpGet httpGet = new HttpGet(issuer + "/api/tokens/refresh"); - httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); - - CloseableHttpClient httpclient = HttpClients.createDefault(); - String jsonResponse = IOUtils.toString(httpclient.execute(httpGet).getEntity().getContent(), StandardCharsets.UTF_8.name()); - Gson gson = new Gson(); - - List oldRefreshTokens = null; - for(RefreshToken refreshToken:gson.fromJson(jsonResponse, RefreshToken[].class)){ - if (oldRefreshTokens == null) { - oldRefreshTokens = new ArrayList<>(); - } - - if (!refreshToken.getValue().equals(currentRefreshToken)) { - oldRefreshTokens.add(refreshToken.getId()+""); - } - } - - return oldRefreshTokens; - } -} \ No newline at end of file +} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/RefreshToken.java b/src/main/java/eu/dnetlib/openaire/usermanagement/RefreshToken.java deleted file mode 100644 index 98c5a2c..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/RefreshToken.java +++ /dev/null @@ -1,58 +0,0 @@ -package eu.dnetlib.openaire.usermanagement; - -public class RefreshToken { - private String value; - private int id; - private String[] scopes; - private String clientId; - private String userId; - private String expliration; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String[] getScopes() { - return scopes; - } - - public void setScopes(String[] scopes) { - this.scopes = scopes; - } - - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getExpliration() { - return expliration; - } - - public void setExpliration(String expliration) { - this.expliration = expliration; - } -} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServiceServlet.java b/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServiceServlet.java index ca247ba..d4f809c 100644 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServiceServlet.java +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServiceServlet.java @@ -1,18 +1,6 @@ package eu.dnetlib.openaire.usermanagement; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -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.http.HttpResponse; -import org.apache.log4j.Logger; -import org.mitre.openid.connect.model.OIDCAuthenticationToken; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.method.P; -import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.beans.factory.annotation.Value; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import javax.servlet.ServletConfig; @@ -21,12 +9,12 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.sql.SQLException; public class RegisterServiceServlet extends HttpServlet { - private Logger logger = Logger.getLogger(RegisterServiceServlet.class); + @Value("${developers.url}") + private String url; public void init(ServletConfig config) throws ServletException { super.init(config); @@ -34,394 +22,7 @@ public class RegisterServiceServlet extends HttpServlet { config.getServletContext()); } - @Autowired - private RegisteredServicesUtils registeredServicesUtils; - - @Autowired - private TokenUtils tokenUtils; - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder. - getContext().getAuthentication(); - String userid = authentication.getSub(); - - StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0)); - name.append(authentication.getUserInfo().getFamilyName().charAt(0)); - request.getSession().setAttribute("name", name.toString()); - - String idParam = request.getParameter("id"); - - if (idParam != null && !idParam.isEmpty()) { // EDIT CASE - //System.out.println("In edit"); - try { - int id = Integer.parseInt(idParam); - RegisteredService registeredService = registeredServicesUtils.getRegisteredServiceDao().fetchRegisteredServiceById(id); - - if (registeredService != null && registeredServicesUtils.isAuthorized(userid, id)) { - ServiceResponse serviceResponse = tokenUtils.getRegisteredService(registeredService.getClientId(), registeredService.getRegistrationAccessToken()); - - updateFormFields(request, registeredService.getName(), registeredService.getKeyType(), serviceResponse); - - } else { - if (registeredService == null) { - //System.out.println("No service found!"); - request.getSession().setAttribute("message", "Not valid registered service with given id " + id + "."); - response.sendRedirect("./registeredServices"); - logger.warn("Not valid registered service with " + id + "id."); - - } else { - //System.out.println("Not authorized"); - request.getSession().setAttribute("message", "Not authorized to edit the registered service with id " + id + "."); - response.sendRedirect("./registeredServices"); - logger.warn("Not authorized to edit the service with " + id + "id."); - } - } - - } catch (NumberFormatException nfe) { - //System.out.println("WRONG FORMAT"); - request.getSession().setAttribute("message", "Invalid service id."); - response.sendRedirect("./registeredServices"); - logger.error("Invalid service id.", nfe); - - } catch (SQLException sqle) { - //System.out.println("SQL PROBLEM"); - request.getSession().setAttribute("message", "Could not fetch registered service."); - response.sendRedirect("./registeredServices"); - logger.error("Could not fetch registered service.", sqle); - } - - } else {// NEW SERVICE CASE - //Careful! Redirects in method - request.getSession().setAttribute("first_name", null); - request.getSession().setAttribute("key_type", null); - request.getSession().setAttribute("jwksUri", null); - request.getSession().setAttribute("value", null); - checkNumberOfRegisteredServices(request, response, authentication); - } - - response.setContentType("text/html"); - request.getRequestDispatcher("./registerService.jsp").include(request, response); + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(url + "/apis"); } - - private void updateFormFields(HttpServletRequest request, String serviceName, String keyType, ServiceResponse serviceResponse) { - //System.out.println("UPDATING FORM"); - request.getSession().setAttribute("first_name", serviceName); - //System.out.println("Service response URI " + serviceResponse.getJwksUri()); - request.getSession().setAttribute("key_type", keyType); - if (keyType != null) { - if (keyType.equals("uri")) { - request.getSession().setAttribute("jwksUri", serviceResponse.getJwksUri()); - } else { - Key key; - if (serviceResponse.getJwks() != null) { - key = serviceResponse.getJwks().keys[0]; - } else { - key = new Key(); - } - //System.out.println("Service response keys " + serviceResponse.getJwksUri()); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - request.getSession().setAttribute("value", gson.toJson(key)); - } - } - } - - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder. - getContext().getAuthentication(); - - response.setContentType("text/html"); - boolean canProceed = true; - - String mode = request.getParameter("mode").trim(); - //System.out.println("Mode was " + mode); - checkmode(mode); - //System.out.println("Mode is " + mode); - - String serviceId = request.getParameter("id"); - - String name = request.getParameter("first_name").trim(); - if (name.isEmpty()) { - request.getSession().setAttribute("first_name_error", true); - canProceed = false; - } - String keyType = request.getParameter("key_type"); - String jwksUri = null; - String jwksString = null; - Jwks jwks = null; - if(keyType != null) { - keyType = keyType.trim(); - if (keyType.equals("uri")) { - jwksUri = request.getParameter("uri"); - request.getSession().setAttribute("jwksUri", jwksUri); - - String[] schemes = {"https"}; - UrlValidator urlValidator = new UrlValidator(schemes); - if (!urlValidator.isValid(jwksUri)) { - request.getSession().setAttribute("uri_error", true); - canProceed = false; - } - } else { - jwksString = request.getParameter("value"); - try { - Gson gson = new GsonBuilder().registerTypeAdapter(Jwks.class, new JwksDeserializer()).create(); - String jwksSet = String.format("{\"keys\":[%s]}", jwksString); - jwks = gson.fromJson(jwksSet, Jwks.class); - request.getSession().setAttribute("value", jwksString); - - if (jwks.getKeys() == null || jwks.getKeys().length == 0) { - //System.out.println("Something wrong with the keys."); - request.getSession().setAttribute("value_error", true); - canProceed = false; - } - - - } catch (JsonParseException jpe) { - request.getSession().setAttribute("value_error", true); - canProceed = false; - } - } - } - String userid = authentication.getSub(); - String email = authentication.getUserInfo().getEmail(); - ServiceResponse serviceResponse = null; - - if (nameIsValid(name) && userInfoIsValid(userid, email) && keyIsValid(keyType, jwksUri, jwksString) && canProceed) { - - String serverMessage; - - if (mode.equals("create")) { - //Careful! Redirects in method - if (!checkNumberOfRegisteredServices(request, response, authentication)) { - return; - } - String serverRequestJSON = null; - if(keyType == null) { - serverRequestJSON = createServiceJson(null, name, email); - } else if (keyType.equals("uri")) { - serverRequestJSON = createServiceJson(null, name, email, jwksUri); - } else if (keyType.equals("value")){ - serverRequestJSON = createServiceJson(null, name, email, jwks); - } - if(serverRequestJSON != null) { - //System.out.println("SERVER JSON " + serverRequestJSON); - serverMessage = tokenUtils.registerService(serverRequestJSON); - logger.debug(serverMessage); - if (serverMessage == null) { - request.getSession().setAttribute("message", "There was an error registering your service. Please try again later."); - response.sendRedirect("./registeredServices"); - return; - } - serviceResponse = new Gson().fromJson(serverMessage, ServiceResponse.class); - String client_id = serviceResponse.getClientId(); - - RegisteredService registeredService = new RegisteredService(client_id, userid, name, serviceResponse.getRegistrationAccessToken(), keyType); - - try { - registeredServicesUtils.addRegistedService(registeredService); - if(registeredService.getKeyType() != null) { - request.getSession().setAttribute("success", - "Your service has been successfully registered!" + - "Client ID: " + serviceResponse.getClientId()); - } else { - request.getSession().setAttribute("success", - "Your service has been successfully registered!" + - "Client ID: " + serviceResponse.getClientId() + - "Client Secret:" + serviceResponse.getClientSecret() + ""); - } - - } catch (SQLException sqle) { - logger.error("Fail to save service.", sqle); - request.getSession().setAttribute("message", "There was an error registering your service. Please try again later."); - response.sendRedirect("./registeredServices"); - return; - } - } else { - logger.error("Service request JSON is null"); - request.getSession().setAttribute("message", "There was an error registering your service. Please try again later."); - response.sendRedirect("./registeredServices"); - return; - } - } else { - int serviceIdInt = 0; - if (serviceId == null || serviceId.isEmpty()) { //TODO WRONG MESSAGE - request.getSession().setAttribute("message", "Service with id " + serviceId + " does not exist."); - response.sendRedirect("./registeredServices"); - - } else { - //System.out.println("In edit..."); - try { - serviceIdInt = Integer.parseInt(serviceId); - if (!registeredServicesUtils.isAuthorized(authentication.getSub(), serviceIdInt)) { - request.getSession().setAttribute("message", "You have no permission to edit the service."); - response.sendRedirect("./registeredServices"); - - } else { - - RegisteredService registeredService = registeredServicesUtils.getRegisteredServiceDao().fetchRegisteredServiceById(serviceIdInt); - if (registeredService != null && registeredService.getClientId() != null) { - String serverRequestJSON = null; - if (keyType == null) { - serverRequestJSON = createServiceJson(registeredService.getClientId(), name, email); - } else if (keyType.equals("uri")) { - serverRequestJSON = createServiceJson(registeredService.getClientId(), name, email, jwksUri); - } else if (keyType.equals("value")) { - serverRequestJSON = createServiceJson(registeredService.getClientId(), name, email, jwks); - } - if (serverRequestJSON != null) { - //System.out.println("SERVER JSON " + serverRequestJSON); - HttpResponse resp = tokenUtils.updateService(registeredService.getClientId(), serverRequestJSON, registeredService.getRegistrationAccessToken()); - if (resp.getStatusLine().getStatusCode() == 200) { - //System.out.println("NAME >>>>" + name); - registeredService.setName(name); - - //System.out.println("Client Id " + registeredService.getClientId()); - try { - registeredServicesUtils.getRegisteredServiceDao().update(registeredService); - } catch (SQLException sqle) { - logger.error("Unable to contact db.", sqle); - request.getSession().setAttribute("message", "Fail to delete the service. Please try again later."); - response.setContentType("text/html"); - request.getRequestDispatcher("./registeredServices.jsp").include(request, response); - return; - } - request.getSession().setAttribute("success", - "Your service has been successfully updated!" + - "Client ID: " + registeredService.getClientId()); - } - - } else { - request.getSession().setAttribute("message", "Service with id " + serviceId + " does not exist."); - response.sendRedirect("./registeredServices"); - return; - } - } else { - logger.error("Service request JSON is null"); - request.getSession().setAttribute("message", "There was an error registering your service. Please try again later."); - response.sendRedirect("./registeredServices"); - return; - } - } - } catch(SQLException sqle){ - logger.error("Unable to access service with id " + serviceId, sqle); - request.getSession().setAttribute("message", "There was an error accessing your service."); - response.sendRedirect("./registeredServices"); - - } catch(NumberFormatException nfe){ - logger.error("Unable to access service with id " + serviceId, nfe); - request.getSession().setAttribute("message", "Service with id " + serviceId + " does not exist."); - response.sendRedirect("./registeredServices"); - } - } - } - - } else { - //something is wrong with the form and the error messages will appear - request.getSession().setAttribute("first_name", name); - request.getSession().setAttribute("key_type", keyType); - request.getSession().setAttribute("uri", jwksUri); - request.getSession().setAttribute("value", jwksString); - - if (serviceId != null && !serviceId.isEmpty()) { - request.getRequestDispatcher("./registerService.jsp?id=" + serviceId).forward(request, response); - - } else { - request.getRequestDispatcher("./registerService.jsp").include(request, response); - - } - return; - } - - response.sendRedirect("./registeredServices"); - } - - private void checkmode(String mode) { - if (mode != null && !mode.isEmpty()) { - if (!mode.equals("edit") || mode.equals("create")) { - mode = "create"; - } - } else { - mode = "create"; - } - } - - private boolean keyIsValid(String keyType, String jwksUri, String jwksString) { - return keyType == null || (keyType.equals("uri") && jwksUri != null && !jwksUri.isEmpty()) || - keyType.equals("value") && jwksString != null && !jwksString.isEmpty(); - } - - private boolean userInfoIsValid(String userid, String email) { - return userid != null && !userid.isEmpty() && - email != null && !email.isEmpty(); - } - - private boolean nameIsValid(String name) { - return name != null && !name.isEmpty(); - } - - private boolean checkNumberOfRegisteredServices(HttpServletRequest request, HttpServletResponse response, OIDCAuthenticationToken authentication) throws IOException { - try { - long numberOfRegisteredServices = - registeredServicesUtils.getRegisteredServiceDao().countRegisteredServices(authentication.getSub()); - - if (numberOfRegisteredServices >= 5) { - response.sendRedirect("./registeredServices"); // The message there already exists. - return false; - } - - } catch (SQLException sqle) { - logger.error("Unable to count registered services.", sqle); - request.getSession().setAttribute("message", "Unable to contact DB. Please try again later."); - response.sendRedirect("./registeredServices"); - return false; - } - - return true; - } - - private static String createServiceJson(String clientId, String name, String email) { - ServiceRequest serviceJSON = new ServiceRequest(); - serviceJSON.setClientId(clientId); - serviceJSON.setClientName(name); - serviceJSON.setContacts(new String[]{email}); - serviceJSON.setToken_endpoint_auth_method("client_secret_basic"); - serviceJSON.setTokenEndpointAuthSigningAlg(null); - GsonBuilder builder = new GsonBuilder(); - builder.serializeNulls(); - Gson gson = builder.create(); - //System.out.println("Created json " + serviceJSON); - return gson.toJson(serviceJSON); - } - - private static String createServiceJson(String clientId, String name, String email, String jwksURI) { - ServiceRequest serviceJSON = new ServiceRequest(); - serviceJSON.setClientId(clientId); - serviceJSON.setClientName(name); - serviceJSON.setContacts(new String[]{email}); - serviceJSON.setJwksUri(jwksURI); - - GsonBuilder builder = new GsonBuilder(); - builder.serializeNulls(); - Gson gson = builder.create(); - //System.out.println("Created json " + serviceJSON); - return gson.toJson(serviceJSON); - } - - private static String createServiceJson(String clientId, String name, String email, Jwks jwks) { - ServiceRequest serviceJSON = new ServiceRequest(); - serviceJSON.setClientId(clientId); - serviceJSON.setClientName(name); - serviceJSON.setContacts(new String[]{email}); - serviceJSON.setJwks(jwks); - - GsonBuilder builder = new GsonBuilder(); - builder.serializeNulls(); - Gson gson = builder.create(); - //System.out.println("Created json " + serviceJSON); - return gson.toJson(serviceJSON); - } - } diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/RegisteredServicesServlet.java b/src/main/java/eu/dnetlib/openaire/usermanagement/RegisteredServicesServlet.java index c31bb17..46d4f27 100644 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/RegisteredServicesServlet.java +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/RegisteredServicesServlet.java @@ -1,15 +1,6 @@ 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.http.HttpResponse; -import org.apache.log4j.Logger; -import org.mitre.openid.connect.model.OIDCAuthenticationToken; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.beans.factory.annotation.Value; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import javax.servlet.ServletConfig; @@ -18,20 +9,11 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; public class RegisteredServicesServlet extends HttpServlet { - private Logger logger = Logger.getLogger(RegisteredServicesServlet.class); - - @Autowired - private RegisteredServicesUtils registeredServicesUtils; - - @Autowired - private TokenUtils tokenUtils; + @Value("${developers.url}") + private String url; public void init(ServletConfig config) throws ServletException { super.init(config); @@ -39,122 +21,7 @@ public class RegisteredServicesServlet extends HttpServlet { config.getServletContext()); } - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - request.getSession().setAttribute("authenticated", - !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString() - .equals("anonymousUser")); - - OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder. - getContext().getAuthentication(); - - String userId = authentication.getSub(); - - List registeredServices = null; - try { - registeredServices = registeredServicesUtils. - getRegisteredServiceDao().fetchAllRegisteredServicesByOwner(userId); - //System.out.println("LOAD REGISTERED SERVICES. " + registeredServices.size()); - - if (registeredServices.isEmpty()) { - request.getSession().setAttribute("showEmptyList", true); - } else { - Map serviceResponses = new HashMap<>(); - Map serviceKey = new HashMap<>(); - - for (RegisteredService registeredService:registeredServices) { - ServiceResponse serviceResponse = tokenUtils.getRegisteredService(registeredService.getClientId(),registeredService.getRegistrationAccessToken()); - serviceResponses.put(registeredService.getId(), serviceResponse); - serviceKey.put(registeredService.getId(), extractPublicKeySet(serviceResponse)); - } - - boolean reachedLimit = reachedMaximumNumberOfServices(registeredServices); - StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0)); - name.append(authentication.getUserInfo().getFamilyName().charAt(0)); - request.getSession().setAttribute("name", name.toString()); - request.getSession().setAttribute("reachedLimit", reachedLimit); - //System.out.println("REACHED LIMIT??? " + reachedLimit); - - request.getSession().setAttribute("services", serviceResponses); - request.getSession().setAttribute("keys", serviceKey); - } - request.getSession().setAttribute("registeredServices", registeredServices); - - } catch (SQLException sqle) { - logger.error("Error fetching registered services for user " + userId , sqle); - request.getSession().setAttribute("message", "Error fetching registered services. " + - "Please try again later."); - request.getSession().setAttribute("showEmptyList", false); - request.getRequestDispatcher("./registeredServices.jsp").include(request, response); - } - - 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. - getContext().getAuthentication(); - String id = request.getParameter("id"); - - //System.out.println("POST " +id); - - if (id!=null && !id.isEmpty()) { - try { - RegisteredService registeredService = registeredServicesUtils.getRegisteredServiceDao().fetchRegisteredServiceById(Integer.parseInt(id)); - - if (!registeredService.getOwner().equals(authentication.getSub())) { - request.getSession().setAttribute("message", "You are not allowed to delete the service."); - //System.out.println("BLOCKED " + registeredService.getOwner() + " >> " + authentication.getSub()); - response.sendRedirect("./registeredServices"); - return; - } - - HttpResponse resp = tokenUtils.deleteService(registeredService.getClientId(), registeredService.getRegistrationAccessToken()); - - int statusCode = resp.getStatusLine().getStatusCode(); - //System.out.println("STATUS CODE " + statusCode); - - if (statusCode != 204) { - logger.error("Unable to delete the service. Status code was " + statusCode); - request.getSession().setAttribute("message", "Fail to delete the service. Status " + statusCode); - //System.out.println("AAI blocked"); - response.sendRedirect("./registeredServices"); - return; - } else { - registeredServicesUtils.getRegisteredServiceDao().delete(Integer.parseInt(id)); - request.getSession().setAttribute("success", "The service was successfully deleted."); - //System.out.println("HERE HERE"); - } - - } catch (SQLException sqle) { - logger.error("Unable to contact db.", sqle); - request.getSession().setAttribute("message", "Fail to delete the service. Please try again later."); - } - - } else { - request.getSession().setAttribute("message", "Error selecting service to delete. Please try again."); - } - - response.sendRedirect("./registeredServices"); - } - - private boolean reachedMaximumNumberOfServices(List registeredServices) { - return registeredServices.size() >= 5; + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(url + "/apis"); } } diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceRequest.java b/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceRequest.java deleted file mode 100644 index 3816eb1..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceRequest.java +++ /dev/null @@ -1,170 +0,0 @@ -package eu.dnetlib.openaire.usermanagement; - -import java.io.Serializable; - -public class ServiceRequest { - String client_name; - String client_id; - String logo_uri; - String policy_uri; - String[] contacts; - String[] redirect_uris = new String[]{}; - String[] grant_types = new String[] {"client_credentials"}; - String token_endpoint_auth_method = "private_key_jwt"; - String token_endpoint_auth_signing_alg = "RS256"; - String jwks_uri; - Jwks jwks; - - public String getClientName() { - return client_name; - } - - public void setClientName(String clientName) { - this.client_name = clientName; - } - - public String getClientId() { - return client_id; - } - - public void setClientId(String clientId) { - this.client_id = clientId; - } - - public String[] getRedirectUris() { - return redirect_uris; - } - - public void setRedirectUris(String[] redirectUris) { - this.redirect_uris = redirectUris; - } - - public String getLogoUri() { - return logo_uri; - } - - public void setLogoUri(String logoUri) { - this.logo_uri = logoUri; - } - - public String getPolicyUri() { - return policy_uri; - } - - public void setPolicyUri(String policyUri) { - this.policy_uri = policyUri; - } - - public String[] getContacts() { - return contacts; - } - - public void setContacts(String[] contacts) { - this.contacts = contacts; - } - - public String[] getGrantTypes() { - return grant_types; - } - - public void setGrantTypes(String[] grantTypes) { - this.grant_types = grantTypes; - } - - public String getToken_endpoint_auth_method() { - return token_endpoint_auth_method; - } - - public void setToken_endpoint_auth_method(String token_endpoint_auth_method) { - this.token_endpoint_auth_method = token_endpoint_auth_method; - } - - public String getTokenEndpointAuthSigningAlg() { - return token_endpoint_auth_signing_alg; - } - - public void setTokenEndpointAuthSigningAlg(String tokenEndpointAuthSigningAlg) { - this.token_endpoint_auth_signing_alg = tokenEndpointAuthSigningAlg; - } - - public String getJwksUri() { - return jwks_uri; - } - - public void setJwksUri(String jwksUri) { - this.jwks_uri = jwksUri; - } - - public Jwks getJwks() { - return jwks; - } - - public void setJwks(Jwks jwks) { - this.jwks = jwks; - } -} - -class Jwks implements Serializable { - Key[] keys; - - public Key[] getKeys() { - return keys; - } - - public void setKeys(Key[] keys) { - this.keys = keys; - } -} - -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; - } -} - - - - - diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceResponse.java b/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceResponse.java deleted file mode 100644 index 37aef05..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/ServiceResponse.java +++ /dev/null @@ -1,93 +0,0 @@ -package eu.dnetlib.openaire.usermanagement; - -import java.io.Serializable; - -public class ServiceResponse implements Serializable { - String client_id; - Long client_id_issued_at; - String client_secret; - Long client_secret_expires_at; - String registration_access_token; - String registration_client_uri; - String[] redirect_uris; - String client_name; - String logo_uri; - String policy_uri; - String[] contacts; - String[] grant_types; - String token_endpoint_auth_method; - String token_endpoint_auth_signing_alg; - String scope; - String jwks_uri; - Jwks jwks; - - - public String getClientId() { - return client_id; - } - - public Long getClientIdIssuedAt() { - return client_id_issued_at; - } - - public String getClientSecret() { - return client_secret; - } - - public Long getClientSecretExpiresAt() { - return client_secret_expires_at; - } - - public String getRegistrationAccessToken() { - return registration_access_token; - } - - public String getRegistrationClientUri() { - return registration_client_uri; - } - - public String[] getRedirectUris() { - return redirect_uris; - } - - public String getClientName() { - return client_name; - } - - - public String getLogoUri() { - return logo_uri; - } - - public String getPolicyUri() { - return policy_uri; - } - - public String[] getContacts() { - return contacts; - } - - public String[] getGrantTypes() { - return grant_types; - } - - public String getTokenEndpointAuthMethod() { - return token_endpoint_auth_method; - } - - public String getTokenEndpointAuthSigningAlg() { - return token_endpoint_auth_signing_alg; - } - - public String getScope() { - return scope; - } - - public String getJwksUri() { - return jwks_uri; - } - - public Jwks getJwks() { - return jwks; - } -} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java b/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java index 2d33c69..43ac843 100644 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java @@ -7,9 +7,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO; import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP; -import eu.dnetlib.openaire.user.login.utils.AuthoritiesMapper; import eu.dnetlib.openaire.user.pojos.migration.LDAPUser; import eu.dnetlib.openaire.user.store.DataSourceConnector; +import eu.dnetlib.openaire.usermanagement.authorization.AuthoritiesMapper; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/AuthoritiesMapper.java b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/AuthoritiesMapper.java new file mode 100644 index 0000000..f6702db --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/AuthoritiesMapper.java @@ -0,0 +1,41 @@ +package eu.dnetlib.openaire.usermanagement.authorization; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import org.apache.log4j.Logger; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import java.util.Collection; +import java.util.HashSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class AuthoritiesMapper { + + private static final Logger logger = Logger.getLogger(AuthoritiesMapper.class); + + public static Collection extends GrantedAuthority> map(JsonArray entitlements) { + HashSet authorities = new HashSet<>(); + String regex = "urn:geant:openaire[.]eu:group:([^:]*):?(.*)?:role=member#aai[.]openaire[.]eu"; + for(JsonElement obj: entitlements) { + Matcher matcher = Pattern.compile(regex).matcher(obj.getAsString()); + if (matcher.find()) { + StringBuilder sb = new StringBuilder(); + if(matcher.group(1) != null && matcher.group(1).length() > 0) { + sb.append(matcher.group(1).replace("+-+", "_").replaceAll("[+.]", "_").toUpperCase()); + } + if(matcher.group(2).length() > 0) { + sb.append("_"); + if(matcher.group(2).equals("admins")) { + sb.append("MANAGER"); + } else { + sb.append(matcher.group(2).toUpperCase()); + } + } + authorities.add(new SimpleGrantedAuthority(sb.toString())); + } + } + return authorities; + } +} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/Config.java b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/Config.java new file mode 100644 index 0000000..e75b421 --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/Config.java @@ -0,0 +1,49 @@ +package eu.dnetlib.openaire.usermanagement.authorization; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; +import org.springframework.session.web.http.CookieSerializer; +import org.springframework.session.web.http.DefaultCookieSerializer; + +@Configuration +@EnableRedisHttpSession +public class Config { + + private static Logger logger = Logger.getLogger(Config.class); + + @Value("${redis.host:localhost}") + private String host; + + @Value("${redis.port:6379}") + private String port; + + @Value("${redis.password:#{null}}") + private String password; + + @Value("${webbapp.front.domain:.openaire.eu}") + private String domain; + + @Bean + public LettuceConnectionFactory connectionFactory() { + logger.info(String.format("Redis connection listens to %s:%s ",host,port)); + LettuceConnectionFactory factory = new LettuceConnectionFactory(host,Integer.parseInt(port)); + if(password != null) factory.setPassword(password); + return factory; + } + + @Bean + public CookieSerializer cookieSerializer() { + logger.info("Cookie Serializer: Domain is "+domain); + DefaultCookieSerializer serializer = new DefaultCookieSerializer(); + serializer.setCookieName("openAIRESession"); // <1> + serializer.setCookiePath("/"); // <2> +// serializer.setDomainNamePattern(""); //with value "" set's the domain of the service e.g scoobydoo.di.uoa.gr + serializer.setDomainName(domain); + return serializer; + } +} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/EntryPoint.java b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/EntryPoint.java new file mode 100644 index 0000000..1086333 --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/authorization/EntryPoint.java @@ -0,0 +1,19 @@ +package eu.dnetlib.openaire.usermanagement.authorization; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class EntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); + } + +} + diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/utils/RegisteredServicesUtils.java b/src/main/java/eu/dnetlib/openaire/usermanagement/utils/RegisteredServicesUtils.java deleted file mode 100644 index b850d6e..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/utils/RegisteredServicesUtils.java +++ /dev/null @@ -1,35 +0,0 @@ -package eu.dnetlib.openaire.usermanagement.utils; - -import eu.dnetlib.openaire.user.pojos.RegisteredService; -import eu.dnetlib.openaire.user.registeredService.RegisteredServiceDao; -import eu.dnetlib.openaire.user.registeredService.RegisteredServiceSQL; -import org.springframework.stereotype.Component; - -import java.sql.SQLException; - -@Component -public class RegisteredServicesUtils { - - RegisteredServiceDao registeredServiceDao = new RegisteredServiceSQL(); - - public RegisteredServiceDao getRegisteredServiceDao() { - return registeredServiceDao; - } - - public void setRegisteredServiceDao(RegisteredServiceDao registeredServiceDao) { - this.registeredServiceDao = registeredServiceDao; - } - - public void addRegistedService(RegisteredService registeredService) throws SQLException { - registeredServiceDao.insertRegisteredService(registeredService); - } - - public boolean isAuthorized(String userid, int id) throws SQLException { - RegisteredService registeredService = registeredServiceDao.fetchRegisteredServiceById(id); - if (registeredService == null) { - return false; //no harm in accessing nothing - } - return registeredService.getOwner().equals(userid); - } - -} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/utils/TokenUtils.java b/src/main/java/eu/dnetlib/openaire/usermanagement/utils/TokenUtils.java deleted file mode 100644 index 2395618..0000000 --- a/src/main/java/eu/dnetlib/openaire/usermanagement/utils/TokenUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -package eu.dnetlib.openaire.usermanagement.utils; - -import com.google.gson.Gson; -import eu.dnetlib.openaire.usermanagement.ServiceResponse; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -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.stereotype.Component; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; - -@Component -public class TokenUtils { - - private Logger logger = Logger.getLogger(TokenUtils.class); - - @Value("${oidc.issuer}") - private String issuer; - - public String registerService(String serverRequestJSON) - throws IOException { - - HttpPost httppost = new HttpPost( issuer + "register"); - httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - StringEntity params = new StringEntity(serverRequestJSON); - httppost.setEntity(params); - - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpResponse httpResponse = httpclient.execute(httppost); - - //System.out.println("HTTP RESPONSE " + httpResponse.getStatusLine().getStatusCode()); - if (httpResponse.getStatusLine().getStatusCode() == 201) { - //logger.debug(IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8.name())); - return IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8.name()); - } - - return null; - } - - public HttpResponse updateService(String serviceId, String serviceSON, String registeredAccessToken) throws IOException { - - HttpPut httpPut = new HttpPut(issuer + "register/"+serviceId); - httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - httpPut.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + registeredAccessToken); - StringEntity params = new StringEntity(serviceSON.toString()); - httpPut.setEntity(params); - - CloseableHttpClient httpclient = HttpClients.createDefault(); - return httpclient.execute(httpPut); - } - - public HttpResponse deleteService(String serviceId, String registeredAccessToken) throws IOException { - - //System.out.println("DELETE " + issuer + "register/"+serviceId); - HttpDelete httpDelete = new HttpDelete(issuer + "register/"+serviceId); - httpDelete.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - httpDelete.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + registeredAccessToken); - - CloseableHttpClient httpclient = HttpClients.createDefault(); - return httpclient.execute(httpDelete); - } - - public ServiceResponse getRegisteredService(String serviceId, String registeredAccessToken) throws IOException { - //System.out.println("ISSUER " + issuer); - HttpGet httpGet = new HttpGet(issuer + "register/"+ serviceId); - httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + registeredAccessToken); - - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpResponse httpResponse = httpclient.execute(httpGet); - String registeredService = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8.name()); - //System.out.println(registeredService); - return new Gson().fromJson(registeredService,ServiceResponse.class); - } - - public void viewRegisteredServices(List serviceIds, String registeredAccessToken) throws IOException { - for (String serviceId: serviceIds) { - getRegisteredService(serviceId, registeredAccessToken); - } - } -} diff --git a/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties b/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties index 94193b2..d79dcb6 100644 --- a/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties +++ b/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties @@ -2,3 +2,13 @@ google.recaptcha.secret = 6LfYrU8UAAAAADwrbImPvDo_XcxEZvrkkgMy9yU0 google.recaptcha.key = 6LfYrU8UAAAAAFsl3m2YhP1uavdmAdFEXBkoY_vd role-management.url = http://mpagasas.di.uoa.gr:8080/dnet-role-management +developers.url = http://mpagasas.di.uoa.gr:5100 + +# Redis +redis.host = 127.0.0.1 +#redis.port = 6379 +#redis.password + +webbapp.front = http://mpagasas.di.uoa.gr:4200/reload +webbapp.front.path = / +webbapp.front.domain = .di.uoa.gr diff --git a/src/main/webapp/WEB-INF/applicationContext.xml b/src/main/webapp/WEB-INF/applicationContext.xml index 3da3ed3..e66588c 100644 --- a/src/main/webapp/WEB-INF/applicationContext.xml +++ b/src/main/webapp/WEB-INF/applicationContext.xml @@ -9,9 +9,7 @@ http://www.springframework.org/schema/context/spring-context-4.2.xsd"> - - - + @@ -33,12 +31,10 @@ classpath*:/eu/**/applicationContext*.properties classpath*:/eu/dnetlib/applicationContext-defaultProperties.properties classpath*:/eu/**/springContext-userManagementService.properties - classpath*:/eu/**/springContext-userLoginCore.properties classpath*:/eu/**/springContext-dnetOpenaireUsersService.properties classpath*:/uoa-override.properties classpath*:/dnet-override.properties - - \ No newline at end of file + diff --git a/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml b/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml index 22334a2..70396c6 100644 --- a/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml +++ b/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml @@ -2,12 +2,27 @@ - + - \ No newline at end of file + + + + + + + + + + + + + + + diff --git a/src/main/webapp/overview.jsp b/src/main/webapp/overview.jsp deleted file mode 100644 index d28d97d..0000000 --- a/src/main/webapp/overview.jsp +++ /dev/null @@ -1,79 +0,0 @@ -<%-- - Created by IntelliJ IDEA. - User: sofia - Date: 19/10/2017 - Time: 4:30 μμ - To change this template use File | Settings | File Templates. ---%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> - - - - - - - OpenAIRE - APIs Authentication - - - - - - - - - - - - - - - - - - - - - - - - - - OpenAIRE APIs Authentication - - The OpenAIRE APIs can be accessed over HTTPS both by authenticated and unauthenticated requests. - To achieve better rate limits you need to make authenticated requests. - - - - - - - For more information please read the OpenAIRE API Authentication documentation. - - - - - - Personal token - Get access to the OpenAIRE APIs with your personal access and refresh token. - - - - - Registered Services - Register your services to get access to the OpenAIRE APIs. - - - - - - - - - - - - - diff --git a/src/main/webapp/personal.jsp b/src/main/webapp/personal.jsp deleted file mode 100644 index db1f033..0000000 --- a/src/main/webapp/personal.jsp +++ /dev/null @@ -1,186 +0,0 @@ - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - - - - - - OpenAIRE - Personal token - - - - - - - - - - - - - - - - - - - - - - - - API Access - - Personal token - Registered services - <%-- - Parent - - Sub item - - Sub item - - Sub item - Sub item - - - - --%> - - - - - - - ${message} - - - - - For further information on how to use the tokens please visit the - OpenAIRE API Authentication documentation. - - - - - Your personal access token is - - - ${accessToken} - - - - - - - - - - Your access token is valid for an hour. - - - - - - Do not share your personal access token. Send your personal access token only over HTTPS. - - - - - - - - - Your refresh token is - - - ${refreshToken} - - - - - - - - - OpenAIRE refresh token expires after 1 month and allows you to programmatically get a new access token. - - - - - Please copy your refresh token and store it confidentially. You will not be able to retrieve it. - Do not share your refresh token. Send your refresh token only over HTTPS. - - - - - Do you need a refresh token? - - - OpenAIRE refresh token expires after 1 month and allows you to programmatically get a new access token. - - Get a - refresh token - - - - - - - - - - - Get refresh token - In case you already have a refresh token, it will no longer be valid. Do you want to - proceed? - - Cancel - Get - refresh token - - - - - - - - - - - - - - - diff --git a/src/main/webapp/registerService.jsp b/src/main/webapp/registerService.jsp deleted file mode 100644 index f2e9c50..0000000 --- a/src/main/webapp/registerService.jsp +++ /dev/null @@ -1,314 +0,0 @@ -<%-- - Created by IntelliJ IDEA. - User: sofia - Date: 19/10/2017 - Time: 4:30 μμ - To change this template use File | Settings | File Templates. ---%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - - - - - - - OpenAIRE - Register - - - - - - - - - - - - - - - - - - - - API Access - - Personal token - Registered services - - - - - - - - Edit service - - - Add a new service - - - - - - - - - - - - - - - - - - - - Name* - Give a name to your service - - - - Please enter a name for your service. - - - - Please enter a name for your service. - - - - - - - Security level - - - - - Basic - - - - Advanced - - - - - Public Key - - - - By Value - - - - By URI - - - - Public Key hint - - ${(value != null)?value:''} - - - Please provide a valid JSON. The format should be - {"kty": ..., "e": ... , "use": ... , "kid": ..., "alg": ... , "n": ...} - - - - Please provide a valid JSON. The format should be - {"kty": ..., "e": ... , "use": ... , "kid": ..., "alg": ... , "n": ...} - - - - - - - - - - Please provide a valid URI (do not forget the protocol! https://...) - - - - - - Please provide a valid URI (do not forget the protocol! https://...) - - - - - - - - Cancel - - - - Update service - - - Add new service - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/webapp/registeredServices.jsp b/src/main/webapp/registeredServices.jsp deleted file mode 100644 index 9686bac..0000000 --- a/src/main/webapp/registeredServices.jsp +++ /dev/null @@ -1,191 +0,0 @@ -<%@ page contentType="text/html;charset=UTF-8" language="java" %> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - - - - - - - OpenAIRE - Registered services - - - - - - - - - - - - <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> - - - - - - - - - - API Access - - Personal token - Registered services - - - - - - - - Registered services - - ${message} - - - - - - - - - - - New service - - - - - - New service - - - - - - - - - - You can register up to 5 services. - For more information please read the OpenAIRE API Authentication documentation. - - - - - You have reached the maximum size of allowed registered services. - - - - You have not registered any service yet! - - - - - - Name - Client Id - Creation Date - Actions - - - - - - - - - ${registeredService.name} - - - - - ${registeredService.clientId} - - - - - - - - - - - - - - - Delete service - - Are you sure you want to delete the - '${registeredService.name}' service? You cannot undo - this action! - - - Cancel - - - Delete - - - - - - - - - - - Name: ${services[key].clientName} - Client Id: ${services[key].clientId} - Scope: openid - Grant type: client credentials - - - Client secret: ${services[key].clientSecret} - Authentication Method Client Secret Basic - - - Authentication Method Asymmetrically-signed JWT assertion - Token Endpoint Authentication Signing Algorithm RSASSA using - SHA-256 hash algorithm - Public Key - ${keys[key]} - - - - Creation Date: - - - - - - - - - - - - - - - - - - - - - -
${accessToken}
${refreshToken}
In case you already have a refresh token, it will no longer be valid. Do you want to - proceed?
- Cancel - Get - refresh token - -
Name: ${services[key].clientName}
Client Id: ${services[key].clientId}
Scope: openid
Grant type: client credentials
Client secret: ${services[key].clientSecret}
Authentication Method Client Secret Basic
Authentication Method Asymmetrically-signed JWT assertion
Token Endpoint Authentication Signing Algorithm RSASSA using - SHA-256 hash algorithm
Public Key -
${keys[key]}
Creation Date: - - - -