protected Profile createProfileWithSsoInfo(String username, Tenant tenant, HttpServletRequest request) throws ProfileException { Map<String, Object> attributes = null; List<AttributeDefinition> attributeDefinitions = tenant.getAttributeDefinitions(); String email = request.getHeader(emailHeaderName); for (AttributeDefinition attributeDefinition : attributeDefinitions) { String attributeName = attributeDefinition.getName(); String attributeValue = request.getHeader(mellonHeaderPrefix + attributeName); if (StringUtils.isNotEmpty(attributeValue)) { if (attributes == null) { attributes = new HashMap<>(); } attributes.put(attributeName, attributeValue); } } logger.info("Creating new profile with SSO info: username={}, email={}, tenant={}, attributes={}", username, email, tenant.getName(), attributes); return profileService.createProfile(tenant.getName(), username, null, email, true, null, attributes, null); }
protected Tenant getSsoEnabledTenant(String[] tenantNames) throws ProfileException { for (String tenantName : tenantNames) { Tenant tenant = tenantService.getTenant(tenantName); if (tenant != null && tenant.isSsoEnabled()) { return tenant; } } return null; }
/** * Returns a list with the names of all tenants. * * @param tenantService the service that retrieves the {@link org.craftercms.profile.api.Tenant}s. * * @return the list of tenant names */ public static List<String> getTenantNames(TenantService tenantService) throws ProfileException { List<Tenant> tenants = tenantService.getAllTenants(); List<String> tenantNames = new ArrayList<>(tenants.size()); if (CollectionUtils.isNotEmpty(tenants)) { for (Tenant tenant : tenants) { tenantNames.add(tenant.getName()); } } return tenantNames; }
@Override public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { HttpServletRequest request = context.getRequest(); String username = request.getHeader(usernameHeaderName); Authentication auth = SecurityUtils.getAuthentication(request); if (StringUtils.isNotEmpty(username) && (auth == null || !auth.getProfile().getUsername().equals(username))) { String[] tenantNames = tenantsResolver.getTenants(); Tenant tenant = getSsoEnabledTenant(tenantNames); if (tenant != null) { Profile profile = profileService.getProfileByUsername(tenant.getName(), username); if (profile == null) { profile = createProfileWithSsoInfo(username, tenant, request); } SecurityUtils.setAuthentication(request, authenticationManager.authenticateUser(profile)); } else { logger.warn("An SSO login was attempted, but none of the tenants [{}] is enabled for SSO", tenantNames); } } processorChain.processRequest(context); }