Skip to content

Commit

Permalink
fix(Login): Google Login redirect to previously requested url (#176)
Browse files Browse the repository at this point in the history
  • Loading branch information
hirokiterashima authored Sep 9, 2022
1 parent 3fd2622 commit 3f548fe
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,12 @@ public GoogleOpenIdConnectFilter(String defaultFilterProcessesUrl) {
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException, IOException {
saveRequestParameter(request, "accessCode");
saveRequestParameter(request, "redirectUrl");
OAuth2AccessToken accessToken;
try {
String accessCodeFromParameter = request.getParameter("accessCode");
String accessCodeFromState = (String) googleOpenIdRestTemplate.getOAuth2ClientContext()
.removePreservedState("accessCode");
googleOpenIdRestTemplate.getOAuth2ClientContext()
.setPreservedState("accessCode", accessCodeFromParameter);
request.setAttribute("accessCode", accessCodeFromState);
accessToken = googleOpenIdRestTemplate.getAccessToken();
} catch (final OAuth2Exception e) {
throw new BadCredentialsException("Could not obtain access token", e);
Expand All @@ -101,7 +98,8 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
String kid = JwtHelper.headers(idToken).get("kid");
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(),
Map.class);
verifyClaims(authInfo);
String googleUserId = authInfo.get("sub");
final UserDetails user = userDetailsService.loadUserByGoogleUserId(googleUserId);
Expand All @@ -116,16 +114,25 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ
}
}

private void saveRequestParameter(HttpServletRequest request, String parameterName) {
String parameterValue = request.getParameter(parameterName);
String parameterFromState = (String) googleOpenIdRestTemplate.getOAuth2ClientContext()
.removePreservedState(parameterName);
googleOpenIdRestTemplate.getOAuth2ClientContext().setPreservedState(parameterName,
parameterValue);
request.setAttribute(parameterName, parameterFromState);
}

private void invalidateAccesToken() {
googleOpenIdRestTemplate.getOAuth2ClientContext().setAccessToken((OAuth2AccessToken)null);
googleOpenIdRestTemplate.getOAuth2ClientContext().setAccessToken((OAuth2AccessToken) null);
}

public void verifyClaims(Map claims) {
int exp = (int) claims.get("exp");
Date expireDate = new Date(exp * 1000L);
Date now = new Date();
if (expireDate.before(now) || !claims.get("iss").equals(googleIssuer) ||
!claims.get("aud").equals(googleClientId)) {
if (expireDate.before(now) || !claims.get("iss").equals(googleIssuer)
|| !claims.get("aud").equals(googleClientId)) {
throw new RuntimeException("Invalid claims");
}
}
Expand All @@ -143,8 +150,10 @@ public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
private static class NoopAuthenticationManager implements AuthenticationManager {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
throw new UnsupportedOperationException(
"No authentication should be done with this AuthenticationManager");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (c) 2008-2019 Regents of the University of California (Regents).
* Copyright (c) 2008-2022 Regents of the University of California (Regents).
* Created by WISE, Graduate School of Education, University of California, Berkeley.
*
* This software is distributed under the GNU General Public License, v3,
Expand Down Expand Up @@ -30,9 +30,6 @@
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.wise.portal.dao.ObjectNotFoundException;
import org.wise.portal.domain.authentication.MutableUserDetails;
Expand All @@ -49,7 +46,6 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

/**
Expand All @@ -75,30 +71,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
Locale locale = getLocale(request, userDetails);

if (userDetails instanceof StudentUserDetails) {
String accessCode = (String) request.getAttribute("accessCode");
String studentHomeUrl = getStudentHomeUrl(locale);
if (request.getServletPath().contains("google-login") ||
ControllerUtil.isUserPreviousAdministrator()) {
if (accessCode != null && !accessCode.equals("")) {
response.sendRedirect(studentHomeUrl + "?accessCode=" + accessCode);
return;
}
response.sendRedirect(studentHomeUrl);
return;
}
// pLT= previous login time (not this time, but last time)
Date lastLoginTime = ((StudentUserDetails) userDetails).getLastLoginTime();
long pLT = 0L; // previous last log in time
if (lastLoginTime != null) {
pLT = lastLoginTime.getTime();
}
setDefaultTargetUrl(WISEAuthenticationProcessingFilter.STUDENT_DEFAULT_TARGET_PATH + "?pLT=" + pLT);
setDefaultTargetUrl(WISEAuthenticationProcessingFilter.STUDENT_DEFAULT_TARGET_PATH);
} else if (userDetails instanceof TeacherUserDetails) {
if (request.getServletPath().contains("google-login") ||
ControllerUtil.isUserPreviousAdministrator()) {
response.sendRedirect(getTeacherHomeUrl(locale));
return;
}
this.setDefaultTargetUrl(WISEAuthenticationProcessingFilter.TEACHER_DEFAULT_TARGET_PATH);
GrantedAuthority researcherAuth = null;
try {
Expand Down Expand Up @@ -132,12 +106,13 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
Portal portal = portalService.getById(new Integer(1));
if (!userIsAdmin && !portal.isLoginAllowed()) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
SecurityContextHolder.getContext().setAuthentication(null);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + WISEAuthenticationProcessingFilter.LOGIN_DISABLED_MESSGE_PAGE);
response.sendRedirect(
contextPath + WISEAuthenticationProcessingFilter.LOGIN_DISABLED_MESSGE_PAGE);
return;
}
} catch (ObjectNotFoundException e) {
Expand All @@ -147,33 +122,61 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
}

request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
userDetailsService.updateStatsOnSuccessfulLogin((MutableUserDetails) userDetails);
String redirectUrl = (String) request.getAttribute("redirectUrl");
if (redirectUrl != null) {
handleRedirectRequest(redirectUrl, request, response, userDetails, locale);
} else if (request.getServletPath().contains("google-login")) {
handleGoogleLogin(request, response, userDetails, locale);
}
if (ControllerUtil.isUserPreviousAdministrator()) {
response.sendRedirect(getUserHomeUrl(userDetails, locale));
}
//super.handle(request, response, authentication);
}

// redirect if specified in the login request
SavedRequest savedRequest =
new HttpSessionRequestCache().getRequest(request, response);
if (savedRequest != null) {
String redirectUrl = savedRequest.getRedirectUrl();
if (StringUtils.hasText(redirectUrl) && !redirectUrl.contains("login")) {
this.setDefaultTargetUrl(redirectUrl);
}
private void handleRedirectRequest(String redirectUrl, HttpServletRequest request,
HttpServletResponse response, MutableUserDetails userDetails, Locale locale)
throws IOException {
if (redirectUrl.equals("/")) {
response.sendRedirect(getUserHomeUrl(userDetails, locale));
} else if (redirectUrl.startsWith("http")) {
response.sendRedirect(redirectUrl);
} else {
response.sendRedirect(getHomeUrlWithLocale(locale) + redirectUrl);
}
}

userDetailsService.updateStatsOnSuccessfulLogin((MutableUserDetails) userDetails);
//super.handle(request, response, authentication);
private void handleGoogleLogin(HttpServletRequest request, HttpServletResponse response,
MutableUserDetails userDetails, Locale locale) throws IOException {
String accessCode = (String) request.getAttribute("accessCode");
String homeUrl = getUserHomeUrl(userDetails, locale);
if (accessCode != null && !accessCode.equals("")) {
response.sendRedirect(homeUrl + "?accessCode=" + accessCode);
}
response.sendRedirect(homeUrl);
}

private String getTeacherHomeUrl(Locale locale) {
String teacherHomeUrl = appProperties.getProperty("wise.hostname") +
getLocalePath(locale) +
WISEAuthenticationProcessingFilter.TEACHER_DEFAULT_TARGET_PATH;
return teacherHomeUrl;
return getHomeUrlWithLocale(locale)
+ WISEAuthenticationProcessingFilter.TEACHER_DEFAULT_TARGET_PATH;
}

private String getStudentHomeUrl(Locale locale) {
String studentHomeUrl = appProperties.getProperty("wise.hostname") +
getLocalePath(locale) +
WISEAuthenticationProcessingFilter.STUDENT_DEFAULT_TARGET_PATH;
return studentHomeUrl;
return getHomeUrlWithLocale(locale)
+ WISEAuthenticationProcessingFilter.STUDENT_DEFAULT_TARGET_PATH;
}

private String getHomeUrlWithLocale(Locale locale) {
return appProperties.getProperty("wise.hostname") + getLocalePath(locale);
}

private String getUserHomeUrl(MutableUserDetails userDetails, Locale locale) {
if (userDetails instanceof StudentUserDetails) {
return getStudentHomeUrl(locale);
} else {
return getTeacherHomeUrl(locale);
}
}

private String getLocalePath(Locale locale) {
Expand All @@ -200,7 +203,7 @@ private Locale getLocale(HttpServletRequest request, MutableUserDetails userDeta
if (userLanguage != null) {
if (userLanguage.contains("_")) {
String language = userLanguage.substring(0, userLanguage.indexOf("_"));
String country = userLanguage.substring(userLanguage.indexOf("_")+1);
String country = userLanguage.substring(userLanguage.indexOf("_") + 1);
locale = new Locale(language, country);
} else {
locale = new Locale(userLanguage);
Expand Down

0 comments on commit 3f548fe

Please sign in to comment.