Compare commits

...

16 Commits

Author SHA1 Message Date
Konstantinos Triantafyllou a191ca62a6 [maven-release-plugin] prepare for next development iteration 2023-12-14 15:21:09 +02:00
Konstantinos Triantafyllou 2c523edebc [maven-release-plugin] prepare release uoa-login-core-2.1.1 2023-12-14 15:21:05 +02:00
Konstantinos Triantafyllou 8abd6b7307 Move WebMvcConfigurer under AuthenticiationConfiguration. 2023-12-14 15:20:48 +02:00
Konstantinos Triantafyllou 048e51269a [maven-release-plugin] prepare for next development iteration 2023-11-24 12:11:57 +02:00
Konstantinos Triantafyllou d25fb2fc53 [maven-release-plugin] prepare release uoa-login-core-2.1.0 2023-11-24 12:11:54 +02:00
Konstantinos Triantafyllou aecbab92a5 Add default empty authorities mapper and initialize openaire authorities mapper only if property has value eduperson_entitlement. 2023-11-24 12:11:26 +02:00
Konstantinos Triantafyllou 43f0d8f3da Add orcid in User 2023-09-07 11:17:35 +03:00
Konstantinos Triantafyllou cf6e4afcf0 [maven-release-plugin] prepare for next development iteration 2023-07-27 14:04:40 +03:00
Konstantinos Triantafyllou 8036b261cf [maven-release-plugin] prepare release uoa-login-core-2.0.3 2023-07-27 14:04:36 +03:00
Konstantinos Triantafyllou 57e6aa7ccd Change HealthController to LoginCoreDeployController 2023-07-27 14:04:12 +03:00
Konstantinos Triantafyllou eb3e6c82e7 Add Health Controller and global vars 2023-07-27 12:59:33 +03:00
Konstantinos Triantafyllou c3c6d66d29 Add revoke with refresh token method and remove deleteOldTokens 2023-07-26 18:23:20 +03:00
Konstantinos Triantafyllou 2d2796053d [maven-release-plugin] prepare for next development iteration 2023-07-06 15:06:39 +03:00
Konstantinos Triantafyllou a81dcd7ae1 [maven-release-plugin] prepare release uoa-login-core-2.0.2 2023-07-06 15:06:35 +03:00
Konstantinos Triantafyllou 0b93b16059 Add filter to convert getRequestURL in AuthenticationFilter. 2023-07-06 15:06:18 +03:00
Konstantinos Triantafyllou 4fee4ddd8d [maven-release-plugin] prepare for next development iteration 2023-06-30 12:15:16 +03:00
15 changed files with 184 additions and 163 deletions

View File

@ -7,17 +7,17 @@
<version>1.0.0</version>
</parent>
<artifactId>uoa-login-core</artifactId>
<version>2.0.1</version>
<version>2.1.2-SNAPSHOT</version>
<packaging>jar</packaging>
<name>uoa-login-core</name>
<scm>
<developerConnection>scm:git:gitea@code-repo.d4science.org:MaDgIK/uoa-login-core.git</developerConnection>
<tag>uoa-login-core-2.0.1</tag>
<tag>HEAD</tag>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<timestampLogincORE>${maven.build.timestamp}</timestampLogincORE>
<timestampLoginCore>${maven.build.timestamp}</timestampLoginCore>
<maven.build.timestamp.format>E MMM dd HH:mm:ss z yyyy</maven.build.timestamp.format>
</properties>
<dependencies>

View File

@ -1,38 +0,0 @@
package eu.dnetlib.authentication.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("api")
public class APIProperties {
private String title;
private String description;
private String version;
public APIProperties() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}

View File

@ -8,20 +8,25 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableConfigurationProperties({Properties.class, APIProperties.class})
@EnableConfigurationProperties({Properties.class, GlobalVars.class})
@ComponentScan(basePackages = {"eu.dnetlib.authentication"})
public class AuthenticationConfiguration {
private final Properties properties;
private final GlobalVars globalVars;
@Autowired
public AuthenticationConfiguration(Properties properties) {
public AuthenticationConfiguration(Properties properties, GlobalVars globalVars) {
this.properties = properties;
this.globalVars = globalVars;
}
public Map<String, String> getProperties() {
@ -40,6 +45,15 @@ public class AuthenticationConfiguration {
map.put("authentication.accessToken", properties.getAccessToken());
map.put("authentication.redirect", properties.getRedirect());
map.put("authentication.authorities-mapper", properties.getAuthoritiesMapper());
if(GlobalVars.date != null) {
map.put("Date of deploy", GlobalVars.date.toString());
}
if(globalVars.getBuildDate() != null) {
map.put("Date of build", globalVars.getBuildDate());
}
if (globalVars.getVersion() != null) {
map.put("Version", globalVars.getVersion());
}
return map;
}
@ -51,4 +65,16 @@ public class AuthenticationConfiguration {
restTemplate.getMessageConverters().add(converter);
return restTemplate;
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
.allowCredentials(true);
}
};
}
}

View File

@ -0,0 +1,31 @@
package eu.dnetlib.authentication.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Date;
@ConfigurationProperties("authentication.global-vars")
public class GlobalVars {
public static Date date = new Date();
private Date buildDate;
private String version;
public String getBuildDate() {
if(buildDate == null) {
return null;
}
return buildDate.toString();
}
public void setBuildDate(Date buildDate) {
this.buildDate = buildDate;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
}

View File

@ -0,0 +1,39 @@
package eu.dnetlib.authentication.controllers;
import eu.dnetlib.authentication.configuration.AuthenticationConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/login-core")
public class LoginCoreCheckDeployController {
private final Logger log = LogManager.getLogger(this.getClass());
private final AuthenticationConfiguration configuration;
@Autowired
public LoginCoreCheckDeployController(AuthenticationConfiguration configuration) {
this.configuration = configuration;
}
@RequestMapping(value = {"", "/health_check"}, method = RequestMethod.GET)
public String hello() {
log.debug("Hello from Login Core");
return "Hello from Login Core!";
}
@PreAuthorize("hasAnyAuthority('PORTAL_ADMINISTRATOR')")
@RequestMapping(value = "/health_check/advanced", method = RequestMethod.GET)
public Map<String, String> checkEverything() {
Map<String, String> response = configuration.getProperties();
return response;
}
}

View File

@ -40,10 +40,10 @@ public class UserController {
return ResponseEntity.ok(this.userInfoService.getAccessToken(refreshToken));
}
@RequestMapping(value = "/refresh", method = RequestMethod.DELETE)
@RequestMapping(value = "/revoke", method = RequestMethod.POST)
@PreAuthorize("@SecurityService.hasRefreshToken()")
public void deleteOldRefreshToken() {
this.userInfoService.deleteOldRefreshTokens();
public void revoke() {
this.userInfoService.revoke();
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)

View File

@ -1,72 +0,0 @@
package eu.dnetlib.authentication.entities;
import java.util.Arrays;
public class RefreshToken {
private String value;
private int id;
private String[] scopes;
private String clientId;
private String userId;
private String expiration;
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 getExpiration() {
return expiration;
}
public void setExpiration(String expiration) {
this.expiration = expiration;
}
@Override
public String toString() {
return "RefreshToken{" +
"value='" + value + '\'' +
", id=" + id +
", scopes=" + Arrays.toString(scopes) +
", clientId='" + clientId + '\'' +
", userId='" + userId + '\'' +
", expiration='" + expiration + '\'' +
'}';
}
}

View File

@ -13,6 +13,7 @@ public class User {
private String given_name;
private String family_name;
private String email;
private String orcid;
private Set<String> roles;
private String accessToken;
private String refreshToken;
@ -23,6 +24,9 @@ public class User {
this.given_name = token.getUserInfo().getGivenName();
this.family_name = token.getUserInfo().getFamilyName();
this.email = token.getUserInfo().getEmail();
if(token.getUserInfo().getSource().get("orcid") != null) {
this.orcid = token.getUserInfo().getSource().get("orcid").getAsString();
}
this.roles = token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
this.accessToken = token.getAccessTokenValue();
this.refreshToken = token.getRefreshTokenValue();
@ -68,6 +72,14 @@ public class User {
this.email = email;
}
public String getOrcid() {
return orcid;
}
public void setOrcid(String orcid) {
this.orcid = orcid;
}
public Set<String> getRoles() {
return roles;
}

View File

@ -1,16 +0,0 @@
package eu.dnetlib.authentication.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
.allowCredentials(true);
}
}

View File

@ -1,12 +1,13 @@
package eu.dnetlib.authentication.security.initiliazers;
import eu.dnetlib.authentication.configuration.Properties;
import eu.dnetlib.authentication.security.oidc.OpenAIREAuthoritiesMapper;
import eu.dnetlib.authentication.security.oidc.DefaultAuthoritiesMapper;
import eu.dnetlib.authentication.security.oidc.OpenAIREUserInfoFetcher;
import eu.dnetlib.authentication.utils.PropertyReader;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.model.RegisteredClient;
import org.mitre.openid.connect.client.OIDCAuthenticationProvider;
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
import org.mitre.openid.connect.config.ServerConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@ -14,19 +15,20 @@ import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
@Configuration
public class Configurations {
private final Properties properties;
private final PropertyReader scopeReader;
private final OpenAIREAuthoritiesMapper authoritiesMapper;
private final OpenAIREUserInfoFetcher userInfoFetcher;
private final OIDCAuthoritiesMapper authoritiesMapper;
@Autowired
public Configurations(Properties properties, OpenAIREAuthoritiesMapper authoritiesMapper, OpenAIREUserInfoFetcher userInfoFetcher, PropertyReader scopeReader) {
public Configurations(Properties properties, Optional<OIDCAuthoritiesMapper> authoritiesMapper, OpenAIREUserInfoFetcher userInfoFetcher, PropertyReader scopeReader) {
this.properties = properties;
this.authoritiesMapper = authoritiesMapper;
this.authoritiesMapper = authoritiesMapper.orElse(new DefaultAuthoritiesMapper());
this.userInfoFetcher = userInfoFetcher;
this.scopeReader = scopeReader;
}
@ -37,7 +39,7 @@ public class Configurations {
if(properties.getKeycloak()) {
provider.setUserInfoFetcher(this.userInfoFetcher);
}
if(this.properties.getAuthoritiesMapper() != null && this.scopeReader.getScopes().contains(this.properties.getAuthoritiesMapper())) {
if(this.authoritiesMapper != null) {
provider.setAuthoritiesMapper(this.authoritiesMapper);
}
return provider;
@ -54,7 +56,7 @@ public class Configurations {
serverConfiguration.setTokenEndpointUri(issuer + "/protocol/openid-connect/token");
serverConfiguration.setUserInfoUri(issuer + "/protocol/openid-connect/userinfo");
serverConfiguration.setJwksUri(issuer + "/protocol/openid-connect/certs");
serverConfiguration.setRevocationEndpointUri(issuer + "/revoke");
serverConfiguration.setRevocationEndpointUri(issuer + "/protocol/openid-connect/revoke");
} else {
serverConfiguration.setAuthorizationEndpointUri(issuer + "authorize");
serverConfiguration.setTokenEndpointUri(issuer + "token");

View File

@ -0,0 +1,17 @@
package eu.dnetlib.authentication.security.oidc;
import com.nimbusds.jwt.JWT;
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
import org.mitre.openid.connect.model.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
import java.util.HashSet;
public class DefaultAuthoritiesMapper implements OIDCAuthoritiesMapper {
@Override
public Collection<? extends GrantedAuthority> mapAuthorities(JWT jwtToken, UserInfo userInfo) {
return new HashSet<>();
}
}

View File

@ -6,7 +6,12 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@ -20,6 +25,24 @@ public class OpenAIREAuthenticationFilter extends OIDCAuthenticationFilter {
this.properties = properties;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper((HttpServletRequest) req) {
@Override
public StringBuffer getRequestURL() {
final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
if(originalUrl.toString().contains(OIDCAuthenticationFilter.FILTER_PROCESSES_URL)) {
return new StringBuffer(properties.getOidc().getHome());
} else if(properties.getOidc().getRedirect() != null){
return new StringBuffer(properties.getOidc().getRedirect());
} else {
return originalUrl;
}
}
};
super.doFilter(wrapped, res, chain);
}
@Override
protected void handleAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
Redirect.setRedirect(request, properties);

View File

@ -7,12 +7,16 @@ import eu.dnetlib.authentication.utils.AuthoritiesMapper;
import org.mitre.openid.connect.client.OIDCAuthoritiesMapper;
import org.mitre.openid.connect.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collection;
@Component
@ConditionalOnProperty(
value="authentication.authorities-mapper",
havingValue = "eduperson_entitlement")
public class OpenAIREAuthoritiesMapper implements OIDCAuthoritiesMapper {
private final Properties properties;

View File

@ -1,7 +1,6 @@
package eu.dnetlib.authentication.services;
import eu.dnetlib.authentication.configuration.Properties;
import eu.dnetlib.authentication.entities.RefreshToken;
import eu.dnetlib.authentication.entities.TokenResponse;
import eu.dnetlib.authentication.entities.User;
import eu.dnetlib.authentication.exception.ResourceNotFoundException;
@ -19,10 +18,6 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserInfoService {
@ -65,29 +60,24 @@ public class UserInfoService {
return map;
}
public void deleteOldRefreshTokens() {
public void revoke() {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + authentication.getAccessTokenValue());
HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(revokeTokenRequest(authentication.getRefreshTokenValue()), headers);
try {
ResponseEntity<RefreshToken[]> response = restTemplate.exchange(this.issuer + "/api/tokens/refresh/", HttpMethod.GET, requestEntity, RefreshToken[].class);
List<RefreshToken> old = Arrays.stream(response.getBody()).
filter(token -> !token.getValue().equals(authentication.getRefreshTokenValue())).collect(Collectors.toList());
for(RefreshToken token: old) {
try {
ResponseEntity<String> delete = restTemplate.exchange(this.issuer + "/api/tokens/refresh/" + token.getId(), HttpMethod.DELETE, requestEntity, String.class);
if (delete.getStatusCode() != HttpStatus.OK) {
logger.warn(delete.getStatusCode() + " - Something went wrong for token: " + token.getId());
}
} catch (Exception e) {
logger.warn("Couldn't delete token: " + token.getId());
}
}
restTemplate.exchange(server.getRevocationEndpointUri(), HttpMethod.POST, entity, String.class);
} catch (Exception e) {
logger.error("Couldn't fetch refresh tokens");
logger.error("Couldn't revoke refresh Tokens");
}
}
public MultiValueMap<String, String> revokeTokenRequest(String refreshToken) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("client_id", this.client.getClientId());
map.add("client_secret", this.client.getClientSecret());
map.add("token", refreshToken);
return map;
}
}

View File

@ -14,3 +14,6 @@ authentication.accessToken=AccessToken
authentication.redirect=http://mpagasas.di.uoa.gr:4600/reload
#authentication.authorities-mapper=eduperson_entitlement
authentication.global-vars.buildDate=@timestampLoginCore@
authentication.global-vars.version=@project.version@