Skip to content

Commit

Permalink
fix: Add RememberMe Token authentication in Spring contexts - MEED-7310
Browse files Browse the repository at this point in the history
… - Meeds-io/meeds#2249 (#940)

Prior to this change, when the User HTTPSession is outdated and a REST
call is made directly on a Spring Context, the RememberMe Token isn't
recognized and authenticating the user. This change will introduce
filters to authenticate the user when a RememberMe Token is present as
Cookie in user request, same as any call to `/portal/rest`.
Besides, this will enhance security of RememberMe Token by increasing
the number of used bytes from `144` to `384` bits.
  • Loading branch information
boubaker authored and exo-swf committed Jul 25, 2024
1 parent 3a47fa5 commit 9755478
Show file tree
Hide file tree
Showing 15 changed files with 451 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public FilterRegistrationBean<HttpRequestLocaleFilter> httpRequestLocaleFilter()
FilterRegistrationBean<HttpRequestLocaleFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new HttpRequestLocaleFilter());
registrationBean.addUrlPatterns("/rest/*");
registrationBean.setOrder(3);
registrationBean.setOrder(4);
return registrationBean;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,48 +37,59 @@
import org.springframework.web.context.request.ServletRequestAttributes;

import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.UserStatus;
import org.exoplatform.services.security.Authenticator;
import org.exoplatform.services.security.ConversationRegistry;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.Identity;
import org.exoplatform.services.security.IdentityConstants;
import org.exoplatform.services.security.IdentityRegistry;
import org.exoplatform.services.security.StateKey;
import org.exoplatform.services.security.jaas.UserPrincipal;
import org.exoplatform.services.security.web.HttpSessionStateKey;

import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;

@Component
public class PortalAuthenticationManager implements AuthenticationProvider {

private static OrganizationService organizationService;

private static ConversationRegistry conversationRegistry;

private static IdentityRegistry identityRegistry;

private static Authenticator authenticator;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();

try {
ConversationState conversationState = getCurrentState(request);
Principal userPrincipal = request.getUserPrincipal();
if (conversationState == null
|| (!conversationState.getIdentity().isMemberOf("/platform/users")
&& !conversationState.getIdentity().isMemberOf("/platform/externals"))) {
Identity identity = getCurrentIdentity(request);
if (isAnonymousUser(identity)
&& authentication.getPrincipal() instanceof String username) {
identity = getCurrentIdentity(request, username);
}
if (isAnonymousUser(identity)) {
return new AnonymousAuthenticationToken(IdentityConstants.ANONIM,
authentication.getPrincipal(),
IdentityConstants.ANONIM,
Collections.singletonList(new JaasGrantedAuthority("guests",
userPrincipal)));
} else {
List<GrantedAuthority> authorities = getAuthorities(conversationState.getIdentity(),
userPrincipal);
List<GrantedAuthority> extendedAuthorities = getExtendedAuthorities(userPrincipal);
if (CollectionUtils.isNotEmpty(extendedAuthorities)) {
authorities = new ArrayList<>(authorities);
authorities.addAll(extendedAuthorities);
}
authentication.setAuthenticated(true);
return new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(),
null,
authorities);
new UserPrincipal(IdentityConstants.ANONIM))));
}
Principal userPrincipal = new UserPrincipal(identity.getUserId());
List<GrantedAuthority> authorities = getAuthorities(identity, userPrincipal);
List<GrantedAuthority> extendedAuthorities = getExtendedAuthorities(userPrincipal);
if (CollectionUtils.isNotEmpty(extendedAuthorities)) {
authorities = new ArrayList<>(authorities);
authorities.addAll(extendedAuthorities);
}
return new PreAuthenticatedAuthenticationToken(userPrincipal,
identity.getUserId(),
authorities);
} catch (Exception e) {
throw new AuthenticationServiceException("An unknown error is encountered while authenticating user", e);
}
Expand All @@ -89,25 +100,26 @@ public boolean supports(Class<?> authentication) {
return true;
}

public ConversationState getCurrentState(HttpServletRequest httpRequest) throws Exception {
private Identity getCurrentIdentity(HttpServletRequest httpRequest) throws Exception {
ConversationState state = ConversationState.getCurrent();
if (state != null) {
return state;
if (state == null) {
return getCurrentIdentity(httpRequest, httpRequest.getRemoteUser());
} else {
return state.getIdentity();
}
}

String userId = httpRequest.getRemoteUser();
private Identity getCurrentIdentity(HttpServletRequest httpRequest, String userId) throws Exception {
// only if user authenticated, otherwise there is no reason to do anythings
if (userId != null) {
StateKey stateKey = new HttpSessionStateKey(httpRequest.getSession());

state = getStateBySessionId(userId, stateKey);
ConversationState state = getStateBySessionId(userId, stateKey);
if (state == null) {
return buildState(userId, stateKey);
} else {
return state;
state = buildState(userId, stateKey);
}
return state == null ? null : state.getIdentity();
} else {
return new ConversationState(new Identity(IdentityConstants.ANONIM));
return new Identity(IdentityConstants.ANONIM);
}
}

Expand Down Expand Up @@ -139,34 +151,68 @@ private ConversationState buildState(String userId, StateKey stateKey) throws Ex
}

private ConversationState buildState(Identity identity, StateKey stateKey) {
ConversationRegistry conversationRegistry = ExoContainerContext.getService(ConversationRegistry.class);

ConversationState state = new ConversationState(identity);
conversationRegistry.register(stateKey, state);
getConversationRegistry().register(stateKey, state);
return state;
}

private Identity buildIdentity(String userId) throws Exception {
IdentityRegistry identityRegistry = ExoContainerContext.getService(IdentityRegistry.class);
Authenticator authenticator = ExoContainerContext.getService(Authenticator.class);

Identity identity = identityRegistry.getIdentity(userId);
Identity identity = getIdentityRegistry().getIdentity(userId);
if (identity == null) {
identity = authenticator.createIdentity(userId);
identityRegistry.register(identity);
identity = getAuthenticator().createIdentity(userId);
getIdentityRegistry().register(identity);
}
return identity;
}

private ConversationState getStateBySessionId(String userId, StateKey stateKey) {
ConversationRegistry conversationRegistry = ExoContainerContext.getService(ConversationRegistry.class);

ConversationState state = conversationRegistry.getState(stateKey);
ConversationState state = getConversationRegistry().getState(stateKey);
if (state != null && !userId.equals(state.getIdentity().getUserId())) {
state = null;
conversationRegistry.unregister(stateKey, false);
getConversationRegistry().unregister(stateKey, false);
}
return state;
}

@SneakyThrows
private boolean isDisabledUser(String username) {
return null == getOrganizationService().getUserHandler()
.findUserByName(username, UserStatus.ENABLED);
}

private boolean isAnonymousUser(Identity identity) {
return identity == null
|| IdentityConstants.ANONIM.equals(identity.getUserId())
|| (!identity.isMemberOf("/platform/users") && !identity.isMemberOf("/platform/externals"))
|| isDisabledUser(identity.getUserId());
}

private static Authenticator getAuthenticator() {
if (authenticator == null) {
authenticator = ExoContainerContext.getService(Authenticator.class);
}
return authenticator;
}

private static IdentityRegistry getIdentityRegistry() {
if (identityRegistry == null) {
identityRegistry = ExoContainerContext.getService(IdentityRegistry.class);
}
return identityRegistry;
}

private static OrganizationService getOrganizationService() {
if (organizationService == null) {
organizationService = ExoContainerContext.getService(OrganizationService.class);
}
return organizationService;
}

private static ConversationRegistry getConversationRegistry() {
if (conversationRegistry == null) {
conversationRegistry = ExoContainerContext.getService(ConversationRegistry.class);
}
return conversationRegistry;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* This file is part of the Meeds project (https://meeds.io/).
*
* Copyright (C) 2020 - 2023 Meeds Association [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

package io.meeds.spring.web.security;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import org.exoplatform.container.ExoContainer;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.container.web.AbstractFilter;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.security.Authenticator;
import org.exoplatform.services.security.ConversationRegistry;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.Identity;
import org.exoplatform.services.security.IdentityConstants;
import org.exoplatform.services.security.IdentityRegistry;
import org.exoplatform.services.security.StateKey;
import org.exoplatform.services.security.web.HttpSessionStateKey;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

/**
* A Web filter to retrieve currently authenticated user Identity to current Web
* context session.<br>
* Note: added to be included in class packages scan for Spring
*/
public class PortalIdentityFilter extends AbstractFilter {

private static final Log LOG = ExoLogger.getLogger(PortalIdentityFilter.class);

private static ConversationRegistry conversationRegistry;

private static IdentityRegistry identityRegistry;

private static Authenticator authenticator;

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {

HttpServletRequest httpRequest = (HttpServletRequest) request;
ExoContainer container = getContainer();

ExoContainerContext.setCurrentContainer(container);
try {
ConversationState.setCurrent(getCurrentState(container, httpRequest));
chain.doFilter(request, response);
} finally {
ConversationState.setCurrent(null);
ExoContainerContext.setCurrentContainer(null);
}
}

private ConversationState getCurrentState(ExoContainer container,
HttpServletRequest httpRequest) {
String userId = httpRequest.getRemoteUser();
if (StringUtils.isBlank(userId)) {
return new ConversationState(new Identity(IdentityConstants.ANONIM));
} else {
ConversationState state = null;
HttpSession httpSession = httpRequest.getSession(false);
if (httpSession != null) {
StateKey stateKey = new HttpSessionStateKey(httpSession);
if (LOG.isDebugEnabled()) {
LOG.debug("Looking for Conversation State " + httpSession.getId());
}
state = getConversationRegistry(container).getState(stateKey);
if (state != null && !userId.equals(state.getIdentity().getUserId())) {
state = null;
conversationRegistry.unregister(stateKey, false);
LOG.warn("The current conversation state with the session ID {} does not belong to the user {}. Identity registries has been cleared.",
httpSession.getId(),
userId);
}
}

if (state == null) {
Identity identity = getIdentity(container, userId);
if (identity != null) {
state = new ConversationState(identity);
getConversationRegistry(container).register(new HttpSessionStateKey(httpRequest.getSession()),
state);
}
}
return state;
}
}

private Identity getIdentity(ExoContainer container, String userId) {
Identity identity = getIdentityRegistry(container).getIdentity(userId);
if (identity == null) {
try {
identity = getAuthenticator(container).createIdentity(userId);
identityRegistry.register(identity);
} catch (Exception e) {
LOG.warn("Unable restore identity of user {}", userId, e);
}
}
return identity;
}

private static IdentityRegistry getIdentityRegistry(ExoContainer container) {
if (identityRegistry == null) {
identityRegistry = container.getComponentInstanceOfType(IdentityRegistry.class);
}
return identityRegistry;
}

private static ConversationRegistry getConversationRegistry(ExoContainer container) {
if (conversationRegistry == null) {
conversationRegistry = container.getComponentInstanceOfType(ConversationRegistry.class);
}
return conversationRegistry;
}

private static Authenticator getAuthenticator(ExoContainer container) {
if (authenticator == null) {
authenticator = container.getComponentInstanceOfType(Authenticator.class);
}
return authenticator;
}

}
Loading

0 comments on commit 9755478

Please sign in to comment.