66 lines
2.9 KiB
Java
66 lines
2.9 KiB
Java
package eu.dnetlib.loginservice.security.oidc;
|
|
|
|
import com.google.gson.JsonParser;
|
|
import eu.dnetlib.loginservice.properties.Properties;
|
|
import org.apache.log4j.Logger;
|
|
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.context.annotation.Configuration;
|
|
import org.springframework.security.core.Authentication;
|
|
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
|
import org.springframework.session.FindByIndexNameSessionRepository;
|
|
|
|
import javax.servlet.http.Cookie;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
import javax.servlet.http.HttpSession;
|
|
import java.io.IOException;
|
|
import java.util.Base64;
|
|
import java.util.Date;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
@Configuration
|
|
public class OpenAIREAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
|
|
|
private static final Logger logger = Logger.getLogger(OpenAIREAuthenticationSuccessHandler.class);
|
|
private final Properties properties;
|
|
|
|
@Autowired
|
|
public OpenAIREAuthenticationSuccessHandler(Properties properties) {
|
|
this.properties = properties;
|
|
}
|
|
|
|
@Override
|
|
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
|
|
throws IOException {
|
|
OIDCAuthenticationToken token = (OIDCAuthenticationToken) authentication;
|
|
HttpSession session = request.getSession();
|
|
String redirect = (String) session.getAttribute("redirect");
|
|
session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, token.getUserInfo().getSub());
|
|
try {
|
|
Cookie accessToken = new Cookie(properties.getAccessToken(), token.getAccessTokenValue());
|
|
String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$";
|
|
Matcher matcher = Pattern.compile(regex).matcher(token.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.setPath("/");
|
|
accessToken.setDomain(properties.getDomain());
|
|
response.addCookie(accessToken);
|
|
if(redirect != null) {
|
|
response.sendRedirect(redirect);
|
|
session.removeAttribute("redirect");
|
|
} else {
|
|
response.sendRedirect(properties.getRedirect());
|
|
}
|
|
} catch (IOException e) {
|
|
logger.error("IOException in redirection ", e);
|
|
throw new IOException(e);
|
|
}
|
|
}
|
|
}
|