Add couple of toString / simplify

This commit is contained in:
AFaust
2021-12-05 12:48:02 +01:00
parent 1170f343c9
commit b1f97ada95
11 changed files with 232 additions and 128 deletions

View File

@@ -304,8 +304,6 @@ public class KeycloakAuthenticationComponent extends AbstractAuthenticationCompo
throw new AuthenticationException("Failed to authenticate against Keycloak", atex); throw new AuthenticationException("Failed to authenticate against Keycloak", atex);
} }
// TODO Override setCurrentUser to perform user existence validation and role retrieval for non-Keycloak logins
// (e.g. via public API setCurrentUser)
this.setCurrentUser(realUserName); this.setCurrentUser(realUserName);
this.handleUserTokens(accessTokenHolder.getAccessToken(), accessTokenHolder.getIdToken(), true); this.handleUserTokens(accessTokenHolder.getAccessToken(), accessTokenHolder.getIdToken(), true);
} }

View File

@@ -772,11 +772,10 @@ public class KeycloakAuthenticationFilter extends BaseAuthenticationFilter
} }
else if (authHeader != null && authHeader.toLowerCase(Locale.ENGLISH).startsWith("bearer ")) else if (authHeader != null && authHeader.toLowerCase(Locale.ENGLISH).startsWith("bearer "))
{ {
if (session == null) // even though we provide a remote user mapper, it may not be the first in the chain, so Bearer might not be processed (yet) and
{ // thus session not initialised
throw new IllegalStateException("Session should have been initialised by Bearer authentication in remote user mapper"); final AccessToken accessToken = session != null ? (AccessToken) session.getAttribute(KeycloakRemoteUserMapper.class.getName())
} : null;
final AccessToken accessToken = (AccessToken) session.getAttribute(KeycloakRemoteUserMapper.class.getName());
if (accessToken != null) if (accessToken != null)
{ {
if (accessToken.isActive()) if (accessToken.isActive())

View File

@@ -121,9 +121,6 @@ public class KeycloakRemoteUserMapper implements RemoteUserMapper, ActivateableB
final BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(this.keycloakDeployment); final BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(this.keycloakDeployment);
final AuthOutcome authOutcome = authenticator.authenticate(httpFacade); final AuthOutcome authOutcome = authenticator.authenticate(httpFacade);
// TODO Check on how to enable / add client/audience validation
// currently, Share token seems to be valid here, which it shouldn't be
// also, Share token may not contain Alfresco client roles (e.g. admin)
if (authOutcome == AuthOutcome.AUTHENTICATED) if (authOutcome == AuthOutcome.AUTHENTICATED)
{ {
final AccessToken token = authenticator.getToken(); final AccessToken token = authenticator.getToken();

View File

@@ -34,7 +34,6 @@ import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.extensions.surf.util.URLDecoder;
import org.springframework.extensions.webscripts.Description.RequiredAuthentication; import org.springframework.extensions.webscripts.Description.RequiredAuthentication;
import org.springframework.extensions.webscripts.Match; import org.springframework.extensions.webscripts.Match;
import org.springframework.extensions.webscripts.RuntimeContainer; import org.springframework.extensions.webscripts.RuntimeContainer;
@@ -116,7 +115,7 @@ public class KeycloakWebScriptSSOAuthenticationFilter extends BaseAuthentication
LOGGER.debug("Processing request: {} SID: {}", pathInfo, req.getSession(false) != null ? req.getSession().getId() : null); LOGGER.debug("Processing request: {} SID: {}", pathInfo, req.getSession(false) != null ? req.getSession().getId() : null);
final Match match = this.container.getRegistry().findWebScript(req.getMethod(), URLDecoder.decode(pathInfo)); final Match match = this.container.getRegistry().findWebScript(req.getMethod(), pathInfo);
if (match != null && match.getWebScript() != null) if (match != null && match.getWebScript() != null)
{ {
final RequiredAuthentication reqAuth = match.getWebScript().getDescription().getRequiredAuthentication(); final RequiredAuthentication reqAuth = match.getWebScript().getDescription().getRequiredAuthentication();

View File

@@ -109,4 +109,25 @@ public class AggregateRoleNameMapper implements InitializingBean, RoleNameMapper
} }
return mappedName; return mappedName;
} }
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("AggregateRoleNameMapper [");
if (this.granularMappers != null)
{
builder.append("granularMappers=");
builder.append(this.granularMappers);
builder.append(", ");
}
builder.append("upperCaseRoles=");
builder.append(this.upperCaseRoles);
builder.append("]");
return builder.toString();
}
} }

View File

@@ -15,6 +15,7 @@
*/ */
package de.acosix.alfresco.keycloak.repo.roles; package de.acosix.alfresco.keycloak.repo.roles;
import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
@@ -34,9 +35,9 @@ public class PatternRoleNameMapper implements RoleNameMapper
private static final Logger LOGGER = LoggerFactory.getLogger(PatternRoleNameMapper.class); private static final Logger LOGGER = LoggerFactory.getLogger(PatternRoleNameMapper.class);
protected Map<String, String> patternMappings; protected final Map<String, String> patternMappings = new HashMap<>();
protected Map<String, String> patternInverseMappings; protected final Map<String, String> patternInverseMappings = new HashMap<>();
protected boolean upperCaseRoles; protected boolean upperCaseRoles;
@@ -46,7 +47,11 @@ public class PatternRoleNameMapper implements RoleNameMapper
*/ */
public void setPatternMappings(final Map<String, String> patternMappings) public void setPatternMappings(final Map<String, String> patternMappings)
{ {
this.patternMappings = patternMappings; this.patternMappings.clear();
if (patternMappings != null)
{
this.patternMappings.putAll(patternMappings);
}
} }
/** /**
@@ -55,7 +60,11 @@ public class PatternRoleNameMapper implements RoleNameMapper
*/ */
public void setPatternInverseMappings(final Map<String, String> patternInverseMappings) public void setPatternInverseMappings(final Map<String, String> patternInverseMappings)
{ {
this.patternInverseMappings = patternInverseMappings; this.patternInverseMappings.clear();
if (patternInverseMappings != null)
{
this.patternInverseMappings.putAll(patternInverseMappings);
}
} }
/** /**
@@ -75,12 +84,8 @@ public class PatternRoleNameMapper implements RoleNameMapper
{ {
ParameterCheck.mandatoryString("roleName", roleName); ParameterCheck.mandatoryString("roleName", roleName);
Optional<String> result = Optional.empty();
if (this.patternMappings != null)
{
final Optional<String> matchingPattern = this.patternMappings.keySet().stream().filter(roleName::matches).findFirst(); final Optional<String> matchingPattern = this.patternMappings.keySet().stream().filter(roleName::matches).findFirst();
result = matchingPattern.map(pattern -> { final Optional<String> result = matchingPattern.map(pattern -> {
final String replacement = this.patternMappings.get(pattern); final String replacement = this.patternMappings.get(pattern);
LOGGER.debug("Role {} matches mapping pattern {} - applying replacement pattern {}", roleName, pattern, replacement); LOGGER.debug("Role {} matches mapping pattern {} - applying replacement pattern {}", roleName, pattern, replacement);
final String mappedName = roleName.replaceAll(pattern, replacement); final String mappedName = roleName.replaceAll(pattern, replacement);
@@ -92,7 +97,6 @@ public class PatternRoleNameMapper implements RoleNameMapper
{ {
LOGGER.debug("No matching pattern applies to role {}", roleName); LOGGER.debug("No matching pattern applies to role {}", roleName);
} }
}
return result; return result;
} }
@@ -125,4 +129,31 @@ public class PatternRoleNameMapper implements RoleNameMapper
return result; return result;
} }
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("PatternRoleNameMapper [");
if (this.patternMappings != null)
{
builder.append("patternMappings=");
builder.append(this.patternMappings);
builder.append(", ");
}
if (this.patternInverseMappings != null)
{
builder.append("patternInverseMappings=");
builder.append(this.patternInverseMappings);
builder.append(", ");
}
builder.append("upperCaseRoles=");
builder.append(this.upperCaseRoles);
builder.append("]");
return builder.toString();
}
} }

View File

@@ -96,4 +96,25 @@ public class PrefixAttachingRoleNameMapper implements RoleNameMapper
return result; return result;
} }
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("PrefixAttachingRoleNameMapper [");
if (this.prefix != null)
{
builder.append("prefix=");
builder.append(this.prefix);
builder.append(", ");
}
builder.append("upperCaseRoles=");
builder.append(this.upperCaseRoles);
builder.append("]");
return builder.toString();
}
} }

View File

@@ -15,6 +15,7 @@
*/ */
package de.acosix.alfresco.keycloak.repo.roles; package de.acosix.alfresco.keycloak.repo.roles;
import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.alfresco.util.ParameterCheck; import org.alfresco.util.ParameterCheck;
@@ -31,7 +32,7 @@ public class StaticRoleNameFilter implements RoleNameFilter
private static final Logger LOGGER = LoggerFactory.getLogger(StaticRoleNameFilter.class); private static final Logger LOGGER = LoggerFactory.getLogger(StaticRoleNameFilter.class);
protected Set<String> allowedRoles; protected final Set<String> allowedRoles = new HashSet<>();
/** /**
* @param allowedRoles * @param allowedRoles
@@ -39,7 +40,11 @@ public class StaticRoleNameFilter implements RoleNameFilter
*/ */
public void setAllowedRoles(final Set<String> allowedRoles) public void setAllowedRoles(final Set<String> allowedRoles)
{ {
this.allowedRoles = allowedRoles; this.allowedRoles.clear();
if (allowedRoles != null)
{
this.allowedRoles.addAll(allowedRoles);
}
} }
/** /**
@@ -50,15 +55,24 @@ public class StaticRoleNameFilter implements RoleNameFilter
{ {
ParameterCheck.mandatoryString("roleName", roleName); ParameterCheck.mandatoryString("roleName", roleName);
boolean exposed = false; final boolean exposed = this.allowedRoles.contains(roleName);
if (this.allowedRoles != null)
{
exposed = this.allowedRoles.contains(roleName);
LOGGER.debug("Determined exposure flag of {} for role {} using a static match set", exposed, roleName); LOGGER.debug("Determined exposure flag of {} for role {} using a static match set", exposed, roleName);
}
return exposed; return exposed;
} }
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("StaticRoleNameFilter [");
builder.append("allowedRoles=");
builder.append(this.allowedRoles);
builder.append("]");
return builder.toString();
}
} }

View File

@@ -15,6 +15,7 @@
*/ */
package de.acosix.alfresco.keycloak.repo.roles; package de.acosix.alfresco.keycloak.repo.roles;
import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,7 +35,7 @@ public class StaticRoleNameMapper implements RoleNameMapper
private static final Logger LOGGER = LoggerFactory.getLogger(StaticRoleNameMapper.class); private static final Logger LOGGER = LoggerFactory.getLogger(StaticRoleNameMapper.class);
protected Map<String, String> nameMappings; protected final Map<String, String> nameMappings = new HashMap<>();
protected boolean upperCaseRoles; protected boolean upperCaseRoles;
@@ -44,7 +45,11 @@ public class StaticRoleNameMapper implements RoleNameMapper
*/ */
public void setNameMappings(final Map<String, String> nameMappings) public void setNameMappings(final Map<String, String> nameMappings)
{ {
this.nameMappings = nameMappings; this.nameMappings.clear();
if (nameMappings != null)
{
this.nameMappings.putAll(nameMappings);
}
} }
/** /**
@@ -93,8 +98,6 @@ public class StaticRoleNameMapper implements RoleNameMapper
Optional<String> result = Optional.empty(); Optional<String> result = Optional.empty();
if (this.nameMappings != null)
{
for (final Entry<String, String> entry : this.nameMappings.entrySet()) for (final Entry<String, String> entry : this.nameMappings.entrySet())
{ {
if (entry.getValue().equals(authorityName) || (this.upperCaseRoles && entry.getValue().equalsIgnoreCase(authorityName))) if (entry.getValue().equals(authorityName) || (this.upperCaseRoles && entry.getValue().equalsIgnoreCase(authorityName)))
@@ -105,12 +108,29 @@ public class StaticRoleNameMapper implements RoleNameMapper
break; break;
} }
} }
if (!result.isPresent()) if (!result.isPresent())
{ {
LOGGER.debug("No static mapping applies to authority name {}", authorityName); LOGGER.debug("No static mapping applies to authority name {}", authorityName);
} }
}
return result; return result;
} }
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("StaticRoleNameMapper [");
builder.append("nameMappings=");
builder.append(this.nameMappings);
builder.append(", ");
builder.append("upperCaseRoles=");
builder.append(this.upperCaseRoles);
builder.append("]");
return builder.toString();
}
} }

View File

@@ -574,7 +574,8 @@
{ {
"clientScope": "alfresco-role-service", "clientScope": "alfresco-role-service",
"roles": [ "roles": [
"view-clients" "view-clients",
"view-realm"
] ]
} }
], ],
@@ -1135,7 +1136,8 @@
"query-groups", "query-groups",
"query-users", "query-users",
"view-users", "view-users",
"view-clients" "view-clients",
"view-realm"
] ]
} }
}, },

View File

@@ -609,7 +609,8 @@
{ {
"clientScope": "alfresco-role-service", "clientScope": "alfresco-role-service",
"roles": [ "roles": [
"view-clients" "view-clients",
"view-realm"
] ]
} }
], ],
@@ -1205,7 +1206,8 @@
"query-groups", "query-groups",
"query-users", "query-users",
"view-users", "view-users",
"view-clients" "view-clients",
"view-realm"
] ]
} }
}, },