Commit 0777d93e authored by Sonia Zorba's avatar Sonia Zorba
Browse files

Changes for the refactored AuthLib version

parent d313d3e9
package it.inaf.ia2.gms;
import it.inaf.ia2.aa.ServiceLocator;
import it.inaf.ia2.rap.client.RapClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
......@@ -13,4 +16,9 @@ public class GmsApplication {
public static void main(String[] args) {
SpringApplication.run(GmsApplication.class, args);
}
@Bean
public RapClient rapClient() {
return ServiceLocator.getInstance().getRapClient();
}
}
package it.inaf.ia2.gms.authn;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SigningKeyResolver;
import it.inaf.ia2.aa.ServiceLocator;
import it.inaf.ia2.gms.persistence.LoggingDAO;
import it.inaf.ia2.rap.client.RapClient;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
......@@ -20,11 +17,11 @@ import javax.servlet.http.HttpServletResponse;
public class JWTFilter implements Filter {
private final LoggingDAO loggingDAO;
private final SigningKeyResolver signingKeyResolver;
private final RapClient rapClient;
public JWTFilter(LoggingDAO loggingDAO) {
public JWTFilter(LoggingDAO loggingDAO, RapClient rapClient) {
this.loggingDAO = loggingDAO;
this.signingKeyResolver = ServiceLocator.getInstance().getTokenManager().getSigningKeyResolver();
this.rapClient = rapClient;
}
@Override
......@@ -40,13 +37,10 @@ public class JWTFilter implements Filter {
return;
}
authHeader = authHeader.replace("Bearer", "").trim();
String token = authHeader.replace("Bearer", "").trim();
Jwt jwt = Jwts.parser()
.setSigningKeyResolver(signingKeyResolver)
.parse(authHeader);
Map<String, Object> claims = (Map<String, Object>) jwt.getBody();
rapClient.setAccessToken(token);
Map<String, Object> claims = rapClient.parseIdTokenClaims(token);
if (claims.get("sub") == null) {
loggingDAO.logAction("Attempt to access WS with invalid token", request);
......
package it.inaf.ia2.gms.authn;
import it.inaf.ia2.gms.persistence.LoggingDAO;
import it.inaf.ia2.rap.client.RapClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
......@@ -47,9 +48,9 @@ public class SecurityConfig {
* Checks JWT for web services.
*/
@Bean
public FilterRegistrationBean serviceJWTFilter(LoggingDAO loggingDAO) {
public FilterRegistrationBean serviceJWTFilter(LoggingDAO loggingDAO, RapClient rapClient) {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new JWTFilter(loggingDAO));
bean.setFilter(new JWTFilter(loggingDAO, rapClient));
bean.addUrlPatterns("/ws/jwt/*");
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
......
package it.inaf.ia2.gms.authn;
import it.inaf.ia2.aa.data.User;
import it.inaf.ia2.rap.client.RapClient;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
......@@ -14,58 +15,44 @@ public class SessionData {
private static final String USER_DATA = "user_data";
private User user;
@Autowired
private HttpServletRequest request;
private String userId;
private String userName;
private String accessToken;
private String refreshToken;
private long expiration;
@Autowired
private RapClient rapClient;
@PostConstruct
public void init() {
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute(USER_DATA) != null) {
User user = (User) session.getAttribute(USER_DATA);
userId = user.getName();
userName = user.getUserLabel();
accessToken = user.getAccessToken();
refreshToken = user.getRefreshToken();
setExpiresIn(user.getExpiresIn());
setUser((User) session.getAttribute(USER_DATA));
}
}
public String getUserId() {
return userId;
}
public String getAccessToken() {
return accessToken;
public void setUser(User user) {
this.user = user;
rapClient.setAccessToken(user.getAccessToken());
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
public String getUserId() {
return user.getName();
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
public String getUserName() {
return user.getUserLabel();
}
public String getUserName() {
return userName;
public String getAccessToken() {
return user.getAccessToken();
}
public void setExpiresIn(long expiresIn) {
this.expiration = System.currentTimeMillis() + expiresIn * 1000;
public String getRefreshToken() {
return user.getRefreshToken();
}
public long getExpiresIn() {
return (expiration - System.currentTimeMillis()) / 1000;
return user.getExpiresIn();
}
}
......@@ -7,7 +7,6 @@ import it.inaf.ia2.gms.manager.InvitedRegistrationManager;
import it.inaf.ia2.gms.manager.MembershipManager;
import it.inaf.ia2.gms.manager.PermissionsManager;
import it.inaf.ia2.gms.model.Permission;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.model.response.UserPermission;
import it.inaf.ia2.gms.persistence.GroupsDAO;
import it.inaf.ia2.gms.persistence.PermissionsDAO;
......@@ -19,6 +18,7 @@ import it.inaf.ia2.gms.service.GroupsService;
import it.inaf.ia2.gms.service.JoinService;
import it.inaf.ia2.gms.service.PermissionUtils;
import it.inaf.ia2.gms.service.SearchService;
import it.inaf.ia2.rap.data.RapUser;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
......@@ -340,7 +340,7 @@ public class JWTWebServiceController {
try ( PrintWriter pw = new PrintWriter(response.getOutputStream())) {
for (RapUser member : membershipManager.getMembers(groupEntity)) {
if (selectedUserIds == null || selectedUserIds.contains(member.getId())) {
pw.println(member.getPrimaryEmail());
pw.println(member.getPrimaryEmailAddress());
}
}
}
......
package it.inaf.ia2.gms.controller;
import it.inaf.ia2.aa.ServiceLocator;
import it.inaf.ia2.aa.UserManager;
import it.inaf.ia2.gms.authn.SessionData;
import it.inaf.ia2.gms.rap.RapClient;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -19,14 +21,17 @@ public class KeepAliveController {
@Autowired
private SessionData sessionData;
@Autowired
private RapClient rapClient;
private final UserManager userManager;
public KeepAliveController() {
userManager = ServiceLocator.getInstance().getUserManager();
}
@GetMapping(value = "/keepAlive", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> keepAlive() {
public ResponseEntity<?> keepAlive(HttpServletRequest request) {
LOG.trace("Keepalive called");
if (sessionData.getExpiresIn() < 60) {
rapClient.refreshToken();
sessionData.setUser(userManager.refreshToken(request));
LOG.trace("RAP token refreshed");
}
// empty JSON object response
......
......@@ -4,12 +4,12 @@ import it.inaf.ia2.gms.manager.MembershipManager;
import it.inaf.ia2.gms.manager.PermissionsManager;
import it.inaf.ia2.gms.model.request.AddMemberRequest;
import it.inaf.ia2.gms.model.response.PaginatedData;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.model.request.PaginatedModelRequest;
import it.inaf.ia2.gms.model.request.RemoveMemberRequest;
import it.inaf.ia2.gms.model.request.TabRequest;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import it.inaf.ia2.gms.service.GroupsService;
import it.inaf.ia2.rap.data.RapUser;
import java.util.Collections;
import java.util.List;
import javax.validation.Valid;
......
package it.inaf.ia2.gms.controller;
import it.inaf.ia2.gms.authn.SessionData;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.model.response.PaginatedData;
import it.inaf.ia2.gms.model.response.SearchResponseItem;
import it.inaf.ia2.gms.model.response.UserSearchResponse;
......
package it.inaf.ia2.gms.controller;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.rap.RapClient;
import it.inaf.ia2.rap.client.RapClient;
import it.inaf.ia2.rap.data.RapUser;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
......@@ -18,6 +18,6 @@ public class UsersController {
@GetMapping(value = "users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<RapUser>> searchUsers(@RequestParam("search") String searchText) {
return ResponseEntity.ok(rapClient.searchUsers(searchText));
return ResponseEntity.ok(rapClient.getUsers(searchText));
}
}
......@@ -2,14 +2,14 @@ package it.inaf.ia2.gms.manager;
import it.inaf.ia2.gms.exception.UnauthorizedException;
import it.inaf.ia2.gms.model.Permission;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.persistence.GroupsDAO;
import it.inaf.ia2.gms.persistence.MembershipsDAO;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import it.inaf.ia2.gms.persistence.model.MembershipEntity;
import it.inaf.ia2.gms.rap.RapClient;
import it.inaf.ia2.gms.service.GroupNameService;
import it.inaf.ia2.gms.service.GroupsService;
import it.inaf.ia2.rap.client.RapClient;
import it.inaf.ia2.rap.data.RapUser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
......@@ -77,7 +77,7 @@ public class GroupStatusManager extends UserAwareComponent {
Map<String, String> usersMap = new HashMap<>();
for (RapUser user : rapClient.getUsers(memberships.stream()
.map(u -> u.getUserId()).collect(Collectors.toSet()))) {
usersMap.put(user.getId(), user.getPrimaryEmail());
usersMap.put(user.getId(), user.getPrimaryEmailAddress());
}
List<String[]> rows = new ArrayList<>();
......
......@@ -13,8 +13,8 @@ import it.inaf.ia2.gms.persistence.MembershipsDAO;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import it.inaf.ia2.gms.persistence.model.InvitedRegistration;
import it.inaf.ia2.gms.persistence.model.MembershipEntity;
import it.inaf.ia2.gms.rap.RapClient;
import it.inaf.ia2.gms.service.PermissionsService;
import it.inaf.ia2.rap.client.RapClient;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
......
......@@ -2,15 +2,15 @@ package it.inaf.ia2.gms.manager;
import it.inaf.ia2.gms.exception.UnauthorizedException;
import it.inaf.ia2.gms.model.Permission;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.persistence.GroupsDAO;
import it.inaf.ia2.gms.persistence.LoggingDAO;
import it.inaf.ia2.gms.persistence.MembershipsDAO;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import it.inaf.ia2.gms.persistence.model.MembershipEntity;
import it.inaf.ia2.gms.persistence.model.PermissionEntity;
import it.inaf.ia2.gms.rap.RapClient;
import it.inaf.ia2.gms.service.PermissionUtils;
import it.inaf.ia2.rap.client.RapClient;
import it.inaf.ia2.rap.data.RapUser;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
......
......@@ -2,14 +2,14 @@ package it.inaf.ia2.gms.manager;
import it.inaf.ia2.gms.exception.UnauthorizedException;
import it.inaf.ia2.gms.model.Permission;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.gms.model.UserPermission;
import it.inaf.ia2.gms.persistence.LoggingDAO;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import it.inaf.ia2.gms.persistence.model.PermissionEntity;
import it.inaf.ia2.gms.rap.RapClient;
import it.inaf.ia2.gms.service.PermissionUtils;
import it.inaf.ia2.gms.service.PermissionsService;
import it.inaf.ia2.rap.client.RapClient;
import it.inaf.ia2.rap.data.RapUser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
......
package it.inaf.ia2.gms.model;
import it.inaf.ia2.rap.data.RapUser;
public class UserPermission {
private RapUser user;
......
package it.inaf.ia2.gms.model.response;
import it.inaf.ia2.gms.model.RapUser;
import it.inaf.ia2.rap.data.RapUser;
import java.util.List;
public class UserSearchResponse {
......
......@@ -3,7 +3,6 @@ package it.inaf.ia2.gms.rap;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.inaf.ia2.gms.authn.SessionData;
import it.inaf.ia2.gms.model.RapUser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
......@@ -51,124 +50,124 @@ public class RapClient {
@Autowired(required = false)
private SessionData sessionData;
private final RestTemplate rapRestTemplate;
private final RestTemplate refreshTokenRestTemplate;
// private final RestTemplate rapRestTemplate;
//
// private final RestTemplate refreshTokenRestTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
public RapClient(RestTemplate rapRestTemplate) {
this.rapRestTemplate = rapRestTemplate;
this.refreshTokenRestTemplate = new RestTemplate();
}
public RapUser getUser(String userId) {
String url = rapBaseUrl + "/user/" + userId;
return httpCall(entity -> {
return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<RapUser>() {
}).getBody();
});
}
public List<RapUser> getUsers(Set<String> identifiers) {
if (identifiers.isEmpty()) {
return new ArrayList<>();
}
String url = rapBaseUrl + "/user?identifiers=" + String.join(",", identifiers);
return httpCall(entity -> {
return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
}).getBody();
});
}
public List<RapUser> searchUsers(String searchText) {
if (searchText == null || searchText.trim().isEmpty()) {
return new ArrayList<>();
}
String url = rapBaseUrl + "/user?search=" + searchText;
return httpCall(entity -> {
return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
}).getBody();
});
}
private <R> R httpCall(Function<HttpEntity<?>, R> function) {
return httpCall(function, null);
}
private <R, T> R httpCall(Function<HttpEntity<?>, R> function, T body) {
try {
try {
return function.apply(getEntity(body));
} catch (HttpClientErrorException.Unauthorized ex) {
if (request.getSession(false) == null || sessionData.getExpiresIn() > 0) {
// we can't refresh the token without a session
throw ex;
}
refreshToken();
return function.apply(getEntity(body));
}
} catch (HttpStatusCodeException ex) {
try {
Map<String, String> map = objectMapper.readValue(ex.getResponseBodyAsString(), Map.class);
if (map.containsKey("error")) {
String error = map.get("error");
if (ex instanceof HttpClientErrorException) {
throw new HttpClientErrorException(ex.getStatusCode(), error);
} else if (ex instanceof HttpServerErrorException) {
throw new HttpServerErrorException(ex.getStatusCode(), error);
}
}
} catch (JsonProcessingException ignore) {
}
throw ex;
}
}
private <T> HttpEntity<T> getEntity(T body) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
if (request.getSession(false) != null) {
headers.add("Authorization", "Bearer " + sessionData.getAccessToken());
} else {
// from JWT web service
headers.add("Authorization", request.getHeader("Authorization"));
}
return new HttpEntity<>(body, headers);
}
public void refreshToken() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setBasicAuth(clientId, clientSecret);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "refresh_token");
map.add("refresh_token", sessionData.getRefreshToken());
map.add("scope", scope.replace(",", " "));
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = refreshTokenRestTemplate.postForEntity(accessTokenUri, request, Map.class);
Map<String, Object> values = response.getBody();
sessionData.setAccessToken((String) values.get("access_token"));
sessionData.setRefreshToken((String) values.get("refresh_token"));
sessionData.setExpiresIn((int) values.get("expires_in"));
}
//
// @Autowired
// public RapClient(RestTemplate rapRestTemplate) {
// this.rapRestTemplate = rapRestTemplate;
// this.refreshTokenRestTemplate = new RestTemplate();
// }
//
// public RapUser getUser(String userId) {
//
// String url = rapBaseUrl + "/user/" + userId;
//
// return httpCall(entity -> {
// return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<RapUser>() {
// }).getBody();
// });
// }
//
// public List<RapUser> getUsers(Set<String> identifiers) {
//
// if (identifiers.isEmpty()) {
// return new ArrayList<>();
// }
//
// String url = rapBaseUrl + "/user?identifiers=" + String.join(",", identifiers);
//
// return httpCall(entity -> {
// return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
// }).getBody();
// });
// }
//
// public List<RapUser> searchUsers(String searchText) {
//
// if (searchText == null || searchText.trim().isEmpty()) {
// return new ArrayList<>();
// }
//
// String url = rapBaseUrl + "/user?search=" + searchText;
//
// return httpCall(entity -> {
// return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
// }).getBody();
// });
// }
//
// private <R> R httpCall(Function<HttpEntity<?>, R> function) {
// return httpCall(function, null);
// }
//
// private <R, T> R httpCall(Function<HttpEntity<?>, R> function, T body) {
// try {
// try {
// return function.apply(getEntity(body));
// } catch (HttpClientErrorException.Unauthorized ex) {
// if (request.getSession(false) == null || sessionData.getExpiresIn() > 0) {
// // we can't refresh the token without a session
// throw ex;
// }
// refreshToken();
// return function.apply(getEntity(body));
// }
// } catch (HttpStatusCodeException ex) {
// try {
// Map<String, String> map = objectMapper.readValue(ex.getResponseBodyAsString(), Map.class);
// if (map.containsKey("error")) {
// String error = map.get("error");
// if (ex instanceof HttpClientErrorException) {
// throw new HttpClientErrorException(ex.getStatusCode(), error);
// } else if (ex instanceof HttpServerErrorException) {
// throw new HttpServerErrorException(ex.getStatusCode(), error);
// }
// }
// } catch (JsonProcessingException ignore) {
// }
// throw ex;
// }
// }
//
// private <T> HttpEntity<T> getEntity(T body) {
//
// HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// if (request.getSession(false) != null) {
// headers.add("Authorization", "Bearer " + sessionData.getAccessToken());
// } else {
// // from JWT web service
// headers.add("Authorization", request.getHeader("Authorization"));
// }
//
// return new HttpEntity<>(body, headers);