From 3d9aa1633482a5c37dbcaf671d6d5fd80dfda64c Mon Sep 17 00:00:00 2001 From: Katerina Iatropoulou Date: Thu, 22 Feb 2018 13:27:40 +0000 Subject: [PATCH] MERGE redis branch 49864:50863 --- pom.xml | 147 +++++++--- .../usermanagement/api/Test3Service.java | 270 ++++++++++++++++++ .../usermanagement/registry/beans/Config.java | 47 +++ ...ndLinkURIAuthenticationSuccessHandler.java | 87 ++++++ .../usermanagement/security/JWTGenerator.java | 177 ++++++++++++ .../openaire/usermanagement/redis.properties | 5 + ...ontext-dnetOpenaireUsersService.properties | 7 + .../webapp/WEB-INF/applicationContext.xml | 15 +- .../webapp/WEB-INF/dispatcher-servlet.xml | 6 - src/main/webapp/WEB-INF/security-context.xml | 34 --- ...springContext-dnetOpenaireUsersService.xml | 250 ++++++++++++++++ src/main/webapp/WEB-INF/web.xml | 49 ++-- src/main/webapp/error.jsp | 21 +- src/main/webapp/error404.jsp | 76 +++++ src/main/webapp/index.jsp | 1 + 15 files changed, 1086 insertions(+), 106 deletions(-) create mode 100644 src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java create mode 100644 src/main/java/eu/dnetlib/openaire/usermanagement/registry/beans/Config.java create mode 100644 src/main/java/eu/dnetlib/openaire/usermanagement/security/FrontEndLinkURIAuthenticationSuccessHandler.java create mode 100644 src/main/java/eu/dnetlib/openaire/usermanagement/security/JWTGenerator.java create mode 100644 src/main/resources/eu/dnet/openaire/usermanagement/redis.properties create mode 100644 src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties delete mode 100644 src/main/webapp/WEB-INF/dispatcher-servlet.xml delete mode 100644 src/main/webapp/WEB-INF/security-context.xml create mode 100644 src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml create mode 100644 src/main/webapp/error404.jsp diff --git a/pom.xml b/pom.xml index 0ba1fda..23f3b52 100644 --- a/pom.xml +++ b/pom.xml @@ -1,50 +1,115 @@ - - - eu.dnetlib - dnet45-container-parent - 1.0.0 - - 4.0.0 - eu.dnetlib - dnet-openaire-users - war - 1.0.0-SNAPSHOT - - scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-openaire-users/trunk - - - - eu.dnetlib - uoa-user-management - [2.0.0-SNAPSHOT, 3.0.0) - - - eu.dnetlib - dnet-runtime - [1.0.0, 2.0.0) - - - org.apache.cxf - cxf-rt-transports-http - ${cxf.version} - + + + eu.dnetlib + dnet45-container-parent + 1.0.0-SNAPSHOT + + 4.0.0 + eu.dnetlib + dnet-openaire-users + war + 1.0.0-SNAPSHOT + + + scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-openaire-users/branches/redis + + + + + eu.dnetlib + uoa-user-management + [2.0.0-SNAPSHOT, 3.0.0) + + + org.slf4j + slf4j-api + 1.7.5 + + + org.slf4j + slf4j-log4j12 + 1.7.5 + + + eu.dnetlib + dnet-runtime + [1.0.0, 2.0.0) + + + org.apache.cxf + cxf-rt-transports-http + ${cxf.version} + jstl jstl 1.2 - - javax.servlet - javax.servlet-api - 3.0.1 - - - eu.dnetlib - uoa-user-management - 2.0.0-SNAPSHOT - - + + javax.servlet + javax.servlet-api + 3.0.1 + + + eu.dnetlib + uoa-user-management + 2.0.0-SNAPSHOT + + + org.springframework.security + spring-security-core + 4.2.1.RELEASE + + + org.springframework.security + spring-security-config + 4.2.1.RELEASE + + + org.springframework.security + spring-security-web + 4.2.1.RELEASE + + + com.google.code.gson + gson + 2.6.2 + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + org.mitre + openid-connect-client + 1.3.0 + + + + + + + org.springframework.session + spring-session-data-redis + 1.3.1.RELEASE + pom + + + biz.paluch.redis + lettuce + 3.5.0.Final + + + org.springframework + spring-web + 4.3.4.RELEASE + + + diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java b/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java new file mode 100644 index 0000000..ada159d --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/api/Test3Service.java @@ -0,0 +1,270 @@ +package eu.dnetlib.openaire.usermanagement.api; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.unboundid.ldap.sdk.LDAPException; +import eu.dnetlib.openaire.user.LDAPUser; +import eu.dnetlib.openaire.user.MigrationUser; +import eu.dnetlib.openaire.user.Role; +import eu.dnetlib.openaire.user.dao.RoleDAO; +import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO; +import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP; +import eu.dnetlib.openaire.user.store.DataSourceConnector; +import eu.dnetlib.openaire.usermanagement.security.JWTGenerator; +import org.apache.log4j.Logger; +import org.mitre.openid.connect.model.UserInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.*; +import org.springframework.http.HttpMethod; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.sql.SQLException; + +/** + * Created by sofia on 24/11/2016. + */ +@Component(value = "test3service") +@Path("/users") +public class Test3Service { + + private static final Logger logger = Logger.getLogger(Test3Service.class); + + @Autowired + private SQLMigrationUserDAO sqlMigrationUserDAO; + + @Autowired + private MUserActionsLDAP mUserActionsLDAP; + + @Autowired + private DataSourceConnector dataSourceConnector; + + @GET + @Path("/{userId}") + @Produces(MediaType.APPLICATION_JSON) + public Response getUserById(@PathParam("userId") int userId) { + try { + MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId); + + // Invalide user ID + if (mUser == null) { + String errorMessageJson = compose404Message("Cannot find user with id " + userId + "."); + + return Response + .status(Response.Status.NOT_FOUND) + .entity(errorMessageJson) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + return Response.status(200).entity(composeDataResponse(mUser)).build(); + } + catch (SQLException e) { + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(compose500Message("Fail to fetch users.", e)) + .type(MediaType.APPLICATION_JSON) + .build(); + } + } + + /* How to check @browser ../authenticate/?username=MY_USERNAME&password=MY_PASSWORD + * http://localhost:8080/uoa-user-management-1.0.0-SNAPSHOT/api/users/authenticate?username=sba&password=12345678 + @GET + @Path("/authenticate") + @Produces(MediaType.APPLICATION_JSON) + public Response authenticateUserGET(@QueryParam("username") String username, @QueryParam("password") String password) + { + return commonAuthenticateFunction(username, password); + + }*/ + + @POST + @Path("/authenticates") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response authenticateUserPOST(String input) { + JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject(); + + String username = jsonObject.get("username").getAsString(); + String password = jsonObject.get("password").getAsString(); + + return commonAuthenticateFunction(username, password); + } + + private Response commonAuthenticateFunction(String username, String password) + { + try { + boolean usernameExists = mUserActionsLDAP.usernameExists(username); + + // if user was not found + if (!usernameExists) { + String errorMessageJson = compose401Message("Wrong credentials."); + + return Response + .status(Response.Status.UNAUTHORIZED) + .entity(errorMessageJson) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + boolean authenticated = mUserActionsLDAP.authenticate(username, password); + + // if user was not authenticated + if (!authenticated) { + return Response + .status(Response.Status.UNAUTHORIZED) + .entity(compose401Message("User " + username + " could not be authenticated.")) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + MigrationUser mUser = sqlMigrationUserDAO.fetchByUsername(username); + + // if user was not found in my db + LDAPUser ldapUser = null; + if (mUser == null) { + mUser = new MigrationUser(username); + ldapUser = mUserActionsLDAP.getUser(username); + mUser.setFullname(ldapUser.getDisplayName()); + mUser.setEmail(ldapUser.getEmail()); + mUser.setRoleId(2); + + + sqlMigrationUserDAO.insert(mUser); + } + return Response.status(200).entity(composeDataResponse(mUser)).type(MediaType.APPLICATION_JSON).build(); + + } catch (LDAPException exc) { + logger.error("Fail to connect to LDAP. ", exc); + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(compose500Message("LDAP error.", exc)) + .type(MediaType.APPLICATION_JSON) + .build(); + + } catch (SQLException exc) { + logger.error("Fail to fetch users. ", exc); + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(compose500Message("Fail to fetch users.", exc)) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + } + + @GET + @Path("/changeRole") + @Produces(MediaType.APPLICATION_JSON) + public Response changeRole(@QueryParam("roleId") int roleId, @QueryParam("userId") int userId) + { + RoleDAO roleDAO = new RoleDAO(); + try + { + Role role = roleDAO.fetchById(roleId); + if (role == null) + { + //fetch all roleids TODO + String errorMessageJson = compose404Message("Cannot find role with id" + roleId + "."); + + return Response + .status(Response.Status.NOT_FOUND) + .entity(errorMessageJson) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId); + + if (mUser == null) + { + String errorMessageJson = compose404Message("Cannot find user with id " + userId + "."); + + return Response + .status(Response.Status.NOT_FOUND) + .entity(errorMessageJson) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + mUser.setRoleId(roleId); + sqlMigrationUserDAO.update(mUser); + + return Response.status(200).entity(composeDataResponse(mUser)).build(); + } + catch (SQLException exc) + { + return Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(compose500Message("Fail to fetch users.", exc)) + .type(MediaType.APPLICATION_JSON) + .build(); + } + } + + @GET + @Path("/getUserInfo") + @Produces(MediaType.APPLICATION_JSON) + public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException { + + //return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build(); + + // call aai with accessToken + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization","Bearer " + accessToken); + HttpEntity request = new HttpEntity(null, headers); + String fooResourceUrl = "https://aai.openminted.eu/oidc/userinfo"; + + logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class)); + ResponseEntity response1 = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class); + logger.info(response1.getBody().toString()); + ObjectMapper mapper = new ObjectMapper(); + + return Response.status(response1.getStatusCode().value()).entity(mapper.writeValueAsString(response1.getBody())).type(MediaType.APPLICATION_JSON).build(); + + } + + /* JSON Utility Methods */ + + private String compose401Message(String message) { + return "{ \"status\" : \"error\", \"code\" : \"401\", \"message\" : \" " + message +" \" }"; + } + + private String compose404Message(String message) { + return "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \" " + message +" \" }"; + } + + private String compose500Message(String message, Exception exception) { + return "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \" " + message + "\", " + + "\"description\" : \""+ exception.getMessage() +"\" }"; + } + + private String composeDataResponse(UserInfo user) { + return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }"; + } + + private String composeDataResponse(MigrationUser user) { + //return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }"; + return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }"; + } + + private String composeDataResponse(LDAPUser user) { + return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }"; + } + +// private String composeDataResponse(String username) { +// return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(username) + " }"; +// } + + private String composeDataResponse(String fullname) { + return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }"; + } +} diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/registry/beans/Config.java b/src/main/java/eu/dnetlib/openaire/usermanagement/registry/beans/Config.java new file mode 100644 index 0000000..52e41fa --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/registry/beans/Config.java @@ -0,0 +1,47 @@ +package eu.dnetlib.openaire.usermanagement.registry.beans; + +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.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; + +/** + * Created by stefanos on 14/6/2017. + */ + +@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; + + @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() { + DefaultCookieSerializer serializer = new DefaultCookieSerializer(); + serializer.setCookieName("SESSION"); // <1> + serializer.setCookiePath("/"); // <2> + serializer.setDomainNamePattern(""); + return serializer; + } +} \ No newline at end of file diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/security/FrontEndLinkURIAuthenticationSuccessHandler.java b/src/main/java/eu/dnetlib/openaire/usermanagement/security/FrontEndLinkURIAuthenticationSuccessHandler.java new file mode 100644 index 0000000..ebe8249 --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/security/FrontEndLinkURIAuthenticationSuccessHandler.java @@ -0,0 +1,87 @@ +package eu.dnetlib.openaire.usermanagement.security; + +import org.apache.log4j.Logger; +import org.mitre.openid.connect.model.OIDCAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by stefanos on 9/5/2017. + */ +public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + + private static final Logger logger = Logger.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class); + + private String frontEndURI; + private String frontPath; + private String frontDomain; + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IllegalArgumentException, IOException { + + OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication; + + try { + + Cookie jwt = new Cookie("XCsrfToken", JWTGenerator.generateToken(authOIDC, "my-very-secret")); + Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue()); + + // Expire the cookies in four hours (4 * 3600) + jwt.setMaxAge(14400); + accessToken.setMaxAge(14400); + + //TODO DELETE LOG + logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); + logger.info("access token: " + authOIDC.getAccessTokenValue()); + logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); + + jwt.setPath(frontPath); + if (frontDomain!=null) jwt.setDomain(frontDomain); + accessToken.setPath(frontPath); + if (frontDomain!=null) accessToken.setDomain(frontDomain); + + response.addCookie(jwt); + response.addCookie(accessToken); + response.sendRedirect(frontEndURI); + + } catch (IOException e) { + logger.error("IOException in redirection ", e); + throw new IOException(e); + }catch (IllegalArgumentException e) { + logger.error("IllegalArgumentException in redirection ", e); + throw new IllegalArgumentException(e); + } + + } + + public String getFrontEndURI() { + return frontEndURI; + } + + public void setFrontEndURI(String frontEndURI) { + this.frontEndURI = frontEndURI; + } + + public String getFrontPath() { + return frontPath; + } + + public void setFrontPath(String frontPath) { + this.frontPath = frontPath; + } + + public String getFrontDomain() { + return frontDomain; + } + + public void setFrontDomain(String frontDomain) { + this.frontDomain = frontDomain; + } +} + + diff --git a/src/main/java/eu/dnetlib/openaire/usermanagement/security/JWTGenerator.java b/src/main/java/eu/dnetlib/openaire/usermanagement/security/JWTGenerator.java new file mode 100644 index 0000000..e721f60 --- /dev/null +++ b/src/main/java/eu/dnetlib/openaire/usermanagement/security/JWTGenerator.java @@ -0,0 +1,177 @@ +package eu.dnetlib.openaire.usermanagement.security; + +import com.google.gson.JsonObject; +import eu.dnetlib.openaire.user.MigrationUser; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.apache.log4j.Logger; +import org.mitre.openid.connect.model.OIDCAuthenticationToken; +import org.mitre.openid.connect.model.UserInfo; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.ParseException; +import java.util.Date; + +public class JWTGenerator { + + private static final Logger logger = Logger.getLogger(JWTGenerator.class); + + public static String generateToken(MigrationUser u, String secret) { + Claims claims = Jwts.claims().setSubject(u.getUsername()); + claims.put("fullname", u.getFullname() + ""); + claims.put("userId", u.getId() + ""); + claims.put("email", u.getEmail() + ""); + claims.put("role", u.getRoleId()); + + //expiration + long nowMillis = System.currentTimeMillis(); + Date now = new Date(nowMillis); + long ttlMillis = 1800000; + long expMillis = nowMillis + ttlMillis; + Date exp = new Date(expMillis); + + return Jwts.builder() + .setClaims(claims) + .setExpiration(exp) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } + + public static String generateToken(OIDCAuthenticationToken authOIDC, String secret) { + + try { + + JsonObject userInfo = authOIDC.getUserInfo().getSource(); + Claims claims = Jwts.claims().setSubject(authOIDC.getUserInfo().getSub()); + claims.put("fullname", URLEncoder.encode(authOIDC.getUserInfo().getName(), "UTF-8") + ""); + + if (authOIDC.getUserInfo().getGivenName() == null){ + logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name"); + claims.put("firstname", URLEncoder.encode(" ", "UTF-8") + ""); + } else { + claims.put("firstname", URLEncoder.encode(authOIDC.getUserInfo().getGivenName(), "UTF-8") + ""); + + } + if (authOIDC.getUserInfo().getFamilyName() == null){ + logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name"); + claims.put("lastname", URLEncoder.encode(" ", "UTF-8") + ""); + } else { + claims.put("lastname", URLEncoder.encode(authOIDC.getUserInfo().getFamilyName(), "UTF-8") + ""); + + } + claims.put("email", authOIDC.getUserInfo().getEmail() + ""); +// claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + ""); +// + +// if (userInfo.getAsJsonArray("eduPersonScopedAffiliation").toString() != null) { +// claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + ""); +// } + + if (userInfo.getAsJsonArray("edu_person_entitlements") == null){ + logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have role"); + claims.put("role", URLEncoder.encode(" ", "UTF-8") + ""); + } else { + claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + ""); + } + + //TODO remove, We don't need it but if we are going to use it, we need to check if the user has affiliation + //claims.put("edu_person_scoped_affiliations", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + ""); + + //TODO remove + //TODO THIS IS TEST +// claims.put("fullname", URLEncoder.encode("Σοφία Μπαλτζή", "UTF-8") + ""); +// claims.put("firstname", URLEncoder.encode("Σοφία", "UTF-8") + ""); +// claims.put("lastname", URLEncoder.encode("Μπαλτζή", "UTF-8") + ""); +// claims.put("email", "sofie.mpl@gmail.com" + ""); +// claims.put("edu_person_scoped_affiliations", "faculty"); + + Date exp = new Date(authOIDC.getIdToken().getJWTClaimsSet().getExpirationTime().getTime()); + + //TODO DELETE LOGS +// logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); +// logger.info("fullName: " + authOIDC.getUserInfo().getName()); +// logger.info("firstName: " + authOIDC.getUserInfo().getGivenName()); +// logger.info("lastName: " + authOIDC.getUserInfo().getFamilyName()); +// logger.info("email: " + authOIDC.getUserInfo().getEmail()); +// //logger.info("Check everything"); +// logger.info("locale: " + authOIDC.getUserInfo().getSource()); +// logger.info("role: " + userInfo.getAsJsonArray("edu_person_entitlements").toString()); +// //logger.info("affiliation: " + userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString()); +// logger.info("expirationTime: " + exp); +// logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); + + return Jwts.builder() + .setClaims(claims) + .setExpiration(exp) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + + } catch (ParseException e) { + e.printStackTrace(); + logger.error("JWT Parse Exception from getting Expiration Time ", e); + return "error"; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + logger.error("UnsupportedEncodingException UTF-8 ", e); + return "error"; + } + } + + //TODO DELETE IF IT IS NOT NECESSARY + public static String generateAccessToken(OIDCAuthenticationToken authOIDC, String secret) { + Claims claims = Jwts.claims().setId(authOIDC.getAccessTokenValue()); + + //TODO DELETE LOGS + logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); + logger.info("access token: " + authOIDC.getAccessTokenValue()); + logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n"); + + return Jwts.builder() + .setClaims(claims) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } + + + public static String generateToken(UserInfo user, String secret) { + try { + + JsonObject userInfo = user.getSource(); + + Claims claims = Jwts.claims().setSubject(user.getSub()); + claims.put("email", user.getEmail() + ""); + claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + ""); + + return Jwts.builder() + .setClaims(claims) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + logger.error("UnsupportedEncodingException UTF-8 ", e); + return "error"; + } + } + +} + + + +// How to add it manually +// long nowMillis = System.currentTimeMillis(); +// //This is my token +// try { +// String jwt = Jwts.builder() +// .setSubject("Argiro") +// .setExpiration(new Date(nowMillis+1800000)) +// .claim("fullname", "Argiro Kokogianaki") +// .claim("id", "8") +// .claim("email", "argiro@gmail.com") +// .claim("role","2") +// .signWith( +// SignatureAlgorithm.HS512, +// "my-very-secret".getBytes("UTF-8") +// ) +// .compact(); diff --git a/src/main/resources/eu/dnet/openaire/usermanagement/redis.properties b/src/main/resources/eu/dnet/openaire/usermanagement/redis.properties new file mode 100644 index 0000000..c532ff6 --- /dev/null +++ b/src/main/resources/eu/dnet/openaire/usermanagement/redis.properties @@ -0,0 +1,5 @@ +redis.host = 127.0.0.1 +#redis.port = 6379 +#redis.password + + diff --git a/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties b/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties new file mode 100644 index 0000000..3034c62 --- /dev/null +++ b/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties @@ -0,0 +1,7 @@ +oidc.secret = U_gLOupYu2trYIOwfxGgZkkZoOHG_zGfaViOUsXcZ7qVQuF1rcJeQYKIDX1TY3z27CIoHaqq9ht2rmAiUmBRYQ +oidc.id = 24e83176-1312-4ba3-bc0b-ffeebea1603e +oidc.issuer = https://aai.openminted.eu/oidc/ +oidc.home = http://rudie.di.uoa.gr:8080/dnet-openaire-users-1.0.0-SNAPSHOT/openid_connect_login +webbapp.front = http://scoobydoo.di.uoa.gr:5000/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 944e6dc..05ccbce 100644 --- a/src/main/webapp/WEB-INF/applicationContext.xml +++ b/src/main/webapp/WEB-INF/applicationContext.xml @@ -8,8 +8,16 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> + + + + + + + + @@ -25,13 +33,12 @@ classpath*:/eu/**/applicationContext*.properties classpath*:/eu/dnetlib/applicationContext-defaultProperties.properties classpath*:/eu/**/springContext-userManagementService.properties - + classpath*:/eu/**/springContext-dnetOpenaireUsersService.properties + classpath*:/eu/**/redis.properties classpath*:/uoa-override.properties classpath*:/dnet-override.properties - - - + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/dispatcher-servlet.xml b/src/main/webapp/WEB-INF/dispatcher-servlet.xml deleted file mode 100644 index 4a4405f..0000000 --- a/src/main/webapp/WEB-INF/dispatcher-servlet.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/src/main/webapp/WEB-INF/security-context.xml b/src/main/webapp/WEB-INF/security-context.xml deleted file mode 100644 index 649c702..0000000 --- a/src/main/webapp/WEB-INF/security-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - diff --git a/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml b/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml new file mode 100644 index 0000000..7cb66cc --- /dev/null +++ b/src/main/webapp/WEB-INF/springContext-dnetOpenaireUsersService.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + openid + + + + + + ${oidc.home} + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index 804d04b..2aa820e 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -2,15 +2,11 @@ uoa-user-management - - webAppRootKey - uoa-user-management - contextConfigLocation /WEB-INF/applicationContext.xml - /WEB-INF/security-context.xml + /WEB-INF/springContext-dnetOpenaireUsersService.xml @@ -63,17 +59,17 @@ /register - - Register2Servlet - Register2 - eu.dnetlib.openaire.usermanagement.Register2Servlet - 1 - + + + + + + - - Register2Servlet - /register2 - + + + + VerificationCodeServlet @@ -150,6 +146,17 @@ /* + + springSessionRepositoryFilter + org.springframework.web.filter.DelegatingFilterProxy + + + springSessionRepositoryFilter + /* + REQUEST + ERROR + + springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy @@ -160,4 +167,14 @@ /* - \ No newline at end of file + + 500 + /error.jsp + + + + 404 + /error404.jsp + + + diff --git a/src/main/webapp/error.jsp b/src/main/webapp/error.jsp index b291fa0..87b158e 100644 --- a/src/main/webapp/error.jsp +++ b/src/main/webapp/error.jsp @@ -45,7 +45,7 @@ <%--
Use the same credentials for all our services
--%>
-

Oops! Something went wrong

+

Oops! Something went wrong!

Something went wrong. Please try again later or contact OpenAIRE helpdesk. We apologize for the inconvenience.

@@ -56,17 +56,28 @@
-