@Override public Object getPrincipal() { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(USER_ID); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser); }
@Override public UserAuthorizations getCurrentUser() { // Create the user authorizations. UserAuthorizations userAuthorizations = new UserAuthorizations(); // Get the application user. Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) authentication.getPrincipal(); ApplicationUser applicationUser = securityUserWrapper.getApplicationUser(); userAuthorizations.setUserId(applicationUser.getUserId()); // If roles are present on the application user then filter the herd-specific security roles and add that information to the Current user. if (CollectionUtils.isNotEmpty(applicationUser.getRoles())) { userAuthorizations.setSecurityRoles(new ArrayList<>(getValidSecurityRoles(applicationUser.getRoles()))); } // Get all granted authorities for this user. Collection<GrantedAuthority> grantedAuthorities = securityUserWrapper.getAuthorities(); // Add relative security functions as per granted authorities, if any are present. if (CollectionUtils.isNotEmpty(grantedAuthorities)) { userAuthorizations.setSecurityFunctions( grantedAuthorities.stream().map(grantedAuthority -> new String(grantedAuthority.getAuthority())).collect(Collectors.toList())); } userAuthorizations.setNamespaceAuthorizations(new ArrayList<>(applicationUser.getNamespaceAuthorizations())); } return userAuthorizations; }
/** * Builds the application user. * * @param request the HTTP servlet request. * @param includeRoles If true, the user's roles will be included. Otherwise, not. * * @return the application user. */ protected ApplicationUser buildUser(HttpServletRequest request, boolean includeRoles) { ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(TRUSTED_USER_ID); applicationUser.setFirstName(TRUSTED_USER_FIRST_NAME); applicationUser.setLastName(TRUSTED_USER_LAST_NAME); applicationUser.setEmail(TRUSTED_USER_EMAIL); applicationUser.setSessionId(request.getSession().getId()); applicationUser.setNamespaceAuthorizations(userNamespaceAuthorizationHelper.getAllNamespaceAuthorizations()); if (includeRoles) { Set<String> roles = new HashSet<>(); roles.add(TRUSTED_USER_ROLE); applicationUser.setRoles(roles); } return applicationUser; } }
@Override public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException { ApplicationUser user = (ApplicationUser) token.getPrincipal(); Set<GrantedAuthority> authorities = new HashSet<>(); // Add all functional points per given collection of user roles. authorities.addAll(securityHelper.mapRolesToFunctions(user.getRoles())); // Add all function points that are not mapped to any roles in the system. authorities.addAll(securityHelper.getUnrestrictedFunctions()); SecurityUserWrapper result = new SecurityUserWrapper(user.getUserId(), "N/A", true, true, true, true, authorities, user); LOGGER.debug("Loaded User: " + result); return result; } }
@Override public Object getPrincipal() { List<SimpleGrantedAuthority> authorities = Lists.newArrayList(new SimpleGrantedAuthority(SECURITY_FUNCTION)); ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(USER_ID); applicationUser.setRoles(roles); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser); }
@Test public void checkPermissionAssertNoErrorWhenUserHasMultiplePermissions() throws Exception { // Mock a join point of the method call // mockMethod("foo"); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class); when(methodSignature.getMethod()).thenReturn(method); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations() .add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ, NamespacePermissionEnum.WRITE))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }
@Test public void testBuildNamespaceAuthorizationsAssertWildcardEntityNotAddedIfMatchFails() { ApplicationUser applicationUser = new ApplicationUser(getClass()); String userId = "userId"; applicationUser.setUserId(userId); when(configurationHelper.getBooleanProperty(any())).thenReturn(true); List<UserNamespaceAuthorizationEntity> wildcardEntities = new ArrayList<>(); UserNamespaceAuthorizationEntity wildcardEntity = new UserNamespaceAuthorizationEntity(); wildcardEntity.setUserId("wildcardEntityUserId"); NamespaceEntity namespaceEntity = new NamespaceEntity(); namespaceEntity.setCode("namespace"); wildcardEntity.setNamespace(namespaceEntity); wildcardEntities.add(wildcardEntity); when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserIdStartsWith(any())).thenReturn(wildcardEntities); when(wildcardHelper.matches(any(), any())).thenReturn(false); userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); assertEquals(0, applicationUser.getNamespaceAuthorizations().size()); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId)); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN)); verify(wildcardHelper).matches(eq(userId.toUpperCase()), eq(wildcardEntity.getUserId().toUpperCase())); verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper); } }
/** * Gets the existing user Id. * * @return the existing user Id, session Id, or null if no existing user is present. */ protected String getExistingUserId() { String existingUserId = null; ApplicationUser applicationUser = getExistingUser(); if (applicationUser != null) { existingUserId = applicationUser.getUserId(); } return existingUserId; }
@Test public void getAuthorizedNamespacesWhenUserHasNoPermissionAssertReturnEmpty() { ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser .setNamespaceAuthorizations(new HashSet<>(Arrays.asList(new NamespaceAuthorization("namespace", Arrays.asList(NamespacePermissionEnum.WRITE))))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper("username", "", true, true, true, true, Collections.emptyList(), applicationUser), null)); Set<String> authorizedNamespaces = namespaceSecurityHelper.getAuthorizedNamespaces(NamespacePermissionEnum.READ); assertEquals(0, authorizedNamespaces.size()); }
/** * Retrieves application user per last updater of the current process instance's job definition. * * @param execution the delegate execution * * @return the application user */ protected ApplicationUser getApplicationUser(DelegateExecution execution) { String processDefinitionId = execution.getProcessDefinitionId(); // Get process definition by process definition ID from Activiti. ProcessDefinition processDefinition = activitiService.getProcessDefinitionById(processDefinitionId); // Validate that we retrieved the process definition from Activiti. if (processDefinition == null) { throw new ObjectNotFoundException(String.format("Failed to find Activiti process definition for processDefinitionId=\"%s\".", processDefinitionId)); } // Retrieve the process definition key. String processDefinitionKey = processDefinition.getKey(); // Get the job definition key. JobDefinitionAlternateKeyDto jobDefinitionKey = jobDefinitionHelper.getJobDefinitionKey(processDefinitionKey); // Get the job definition from the Herd repository and validate that it exists. JobDefinitionEntity jobDefinitionEntity = jobDefinitionDaoHelper.getJobDefinitionEntity(jobDefinitionKey.getNamespace(), jobDefinitionKey.getJobName()); // Set the security context per last updater of the job definition. String updatedByUserId = jobDefinitionEntity.getUpdatedBy(); ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(updatedByUserId); return applicationUser; }
String userId = applicationUser.getUserId(); applicationUser.setNamespaceAuthorizations(getAllNamespaceAuthorizations()); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); for (UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity : userNamespaceAuthorizationDao .getUserNamespaceAuthorizationsByUserId(userId))
LOGGER.debug("Current user Id: " + applicationUserNoRoles.getUserId() + ", Session Init Time: " + applicationUserNoRoles.getSessionInitTime()); LOGGER.debug("User is logged in."); invalidateUser(servletRequest, false);
/** * A Factory Method for creating a new <code>ApplicationUser</code>. Provide ability for subclasses to override this if a custom user class is required. The * custom user class must extend <code>ApplicationUser</code>. * * @return ApplicationUser (or a subtype) */ protected ApplicationUser createNewApplicationUser() { return new ApplicationUser(this.getClass()); }
/** * Returns true if the application user is authorized to the given namespace and has the given permissions. * * @param applicationUser the application user * @param namespace the namespace * @param permissions the permissions * * @return true if authorized, false otherwise */ private boolean isAuthorized(ApplicationUser applicationUser, String namespace, NamespacePermissionEnum... permissions) { if (applicationUser != null && applicationUser.getNamespaceAuthorizations() != null) { for (NamespaceAuthorization currentUserAuthorization : applicationUser.getNamespaceAuthorizations()) { List<NamespacePermissionEnum> currentUserNamespacePermissions = currentUserAuthorization.getNamespacePermissions(); if (currentUserNamespacePermissions == null) { currentUserNamespacePermissions = Collections.emptyList(); } if (StringUtils.equalsIgnoreCase(currentUserAuthorization.getNamespace(), namespace) && currentUserNamespacePermissions.stream().anyMatch(Arrays.asList(permissions)::contains)) { return true; } } } return false; }
/** * Builds a user Id. * * @param applicationUser the application user. * @param httpHeaders the HTTP headers. * @param headerName the header name for the user Id. */ protected void buildUserId(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName) { String userId = getHeaderValueString(headerName, httpHeaders); if (userId == null) { throw new IllegalArgumentException("userId is required. No value for userId was found in the header " + headerName); } applicationUser.setUserId(userId); }
/** * Parses the header and assigns roles to the given user object. The header value of the given header name will be parsed for roles. See parseRoles(String, * Set) method for details on the parsing process. * * @param applicationUser - the user object to populate the roles to * @param httpHeaders - the HTTP headers given in the current request * @param headerName - the name of the header containing the roles */ protected void buildRoles(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName) { Set<String> roles = new HashSet<>(); applicationUser.setRoles(roles); String rolesHeaderValue = getHeaderValueString(headerName, httpHeaders); if (rolesHeaderValue != null) { parseRoles(rolesHeaderValue, roles); } /* * If we need to have a mechanism to retrieve roles such that a single header represents a unique role, then the extra code to handle this situation * could be added here. */ }
/** * Gets the existing session init time. * * @return the existing session init time or null if no existing user is present. */ protected Date getExistingSessionInitTime() { Date existingSessionInitTime = null; ApplicationUser applicationUser = getExistingUser(); if (applicationUser != null) { existingSessionInitTime = applicationUser.getSessionInitTime(); } return existingSessionInitTime; }
/** * Checks whether the user was generated by. * * @param authentication the Authentication containing the user object. * @param generatedByClass the class to check that the user was generated by. * * @return boolean */ public boolean isUserGeneratedByClass(Authentication authentication, Class<?> generatedByClass) { boolean isGeneratedBy = false; if (authentication != null) { SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) authentication.getPrincipal(); if (securityUserWrapper != null && securityUserWrapper.getApplicationUser().getGeneratedByClass().equals(generatedByClass)) { isGeneratedBy = true; } } return isGeneratedBy; }
ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ))); applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("bar", Arrays.asList(NamespacePermissionEnum.WRITE))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
@Override public Object getPrincipal() { List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(SECURITY_FUNCTION), new SimpleGrantedAuthority(SECURITY_FUNCTION_2)); ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(USER_ID); applicationUser.setRoles(roles); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser); }