uoa-repository-manager-service/src/main/java/eu/dnetlib/repo/manager/config/FrontEndLinkURIAuthenticati...

66 lines
2.5 KiB
Java

package eu.dnetlib.repo.manager.config;
import com.google.gson.JsonParser;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.session.FindByIndexNameSessionRepository;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private String frontEndURI;
private static final Logger LOGGER = Logger
.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class);
public void init() {
LOGGER.debug("Front end uri : " + frontEndURI);
}
@Value("${services.provide.aai.oidc.domain}")
private String domain;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
request.getSession().setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, authOIDC.getUserInfo().getEmail());
Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());
String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$";
Matcher matcher = Pattern.compile(regex).matcher(authOIDC.getAccessTokenValue());
if (matcher.find()) {
long exp = new JsonParser().parse(new String(Base64.getDecoder().decode(matcher.group(2)))).getAsJsonObject().get("exp").getAsLong();
accessToken.setMaxAge((int) (exp - (new Date().getTime() / 1000)));
} else {
accessToken.setMaxAge(3600);
}
accessToken.setDomain(domain);
accessToken.setPath("/");
response.addCookie(accessToken);
response.sendRedirect(frontEndURI);
}
public String getFrontEndURI() {
return frontEndURI;
}
public void setFrontEndURI(String frontEndURI) {
this.frontEndURI = frontEndURI;
}
}