/** * Sets the security context per last updater of the current process instance's job definition. * * @param applicationUser the application user */ protected void setSecurityContext(ApplicationUser applicationUser) { userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken( new SecurityUserWrapper(applicationUser.getUserId(), "", true, true, true, true, Collections.emptyList(), applicationUser), null)); }
/** * Gets the ApplicationUser in the current security context. Assumes the user is already authenticated, and the authenticated user is constructed through * the application's authentication mechanism. * * @return The ApplicationUser or null if not authenticated */ private ApplicationUser getApplicationUser() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal != null && principal instanceof SecurityUserWrapper) { SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) principal; return securityUserWrapper.getApplicationUser(); } return null; }
@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; }
/** * Asserts the given actual authentication's user ID is equal to the given expected user ID * * @param expectedUserId Expected user ID * @param actualAuthentication Actual authentication object */ private void assertAuthenticationUserIdEquals(String expectedUserId, Authentication actualAuthentication) { assertNotNull(actualAuthentication); assertEquals(PreAuthenticatedAuthenticationToken.class, actualAuthentication.getClass()); PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken = (PreAuthenticatedAuthenticationToken) actualAuthentication; Object principal = preAuthenticatedAuthenticationToken.getPrincipal(); assertNotNull(principal); assertEquals(SecurityUserWrapper.class, principal.getClass()); SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) principal; assertEquals(expectedUserId, securityUserWrapper.getUsername()); assertNotNull(securityUserWrapper.getApplicationUser()); assertEquals(expectedUserId, securityUserWrapper.getApplicationUser().getUserId()); } }
/** * Sets the security context per last updater of the current process instance's job definition. * * @param applicationUser the application user */ protected void setSecurityContext(ApplicationUser applicationUser) { userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken( new SecurityUserWrapper(applicationUser.getUserId(), "", true, true, true, true, Collections.emptyList(), applicationUser), null)); }
/** * Gets the ApplicationUser in the current security context. Assumes the user is already authenticated, and the authenticated user is constructed through * the application's authentication mechanism. * * @return The ApplicationUser or null if not authenticated */ private ApplicationUser getApplicationUser() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal != null && principal instanceof SecurityUserWrapper) { SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) principal; return securityUserWrapper.getApplicationUser(); } return null; }
@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; }
@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; } }
/** * Gets the existing user. * * @return the existing user or null if no existing user is present. */ protected ApplicationUser getExistingUser() { ApplicationUser applicationUser = null; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) authentication.getPrincipal(); if (securityUserWrapper != null) { applicationUser = securityUserWrapper.getApplicationUser(); LOGGER.trace("Existing Application User: " + applicationUser); return applicationUser; } } return applicationUser; }
@Test public void getAuthorizedNamespacesWhenNoApplicationUserInContextReturnEmpty() { SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper("username", "", true, true, true, true, Collections.emptyList(), null), null)); Set<String> authorizedNamespaces = namespaceSecurityHelper.getAuthorizedNamespaces(NamespacePermissionEnum.READ); assertEquals(0, authorizedNamespaces.size()); }
/** * 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; }
@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); }
@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); }
@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()); }
/** * Sets specified namespace authorizations for the current user by updating the security context. * * @param namespace the namespace * @param namespacePermissions the list of namespace permissions */ public void setCurrentUserNamespaceAuthorizations(String namespace, List<NamespacePermissionEnum> namespacePermissions) { String username = AbstractServiceTest.USER_ID; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); Set<NamespaceAuthorization> namespaceAuthorizations = new LinkedHashSet<>(); namespaceAuthorizations.add(new NamespaceAuthorization(namespace, namespacePermissions)); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); }
@Test public void getAuthorizedNamespacesWhenUserHasPermissionAssertReturnNamespace() { ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser .setNamespaceAuthorizations(new HashSet<>(Arrays.asList(new NamespaceAuthorization("namespace", Arrays.asList(NamespacePermissionEnum.READ))))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper("username", "", true, true, true, true, Collections.emptyList(), applicationUser), null)); Set<String> authorizedNamespaces = namespaceSecurityHelper.getAuthorizedNamespaces(NamespacePermissionEnum.READ); assertEquals(1, authorizedNamespaces.size()); assertTrue(authorizedNamespaces.contains("namespace")); }
@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 checkPermissionAssertNoErrorWhenMethodDoesNotHaveAnnotations() throws Exception { // Mock a join point of the method call // mockMethod(1); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod"); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); 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 checkPermissionAssertAccessDeniedWhenApplicationUserIsNull() 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.getParameterNames()).thenReturn(new String[] {"namespace"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); String userId = "userId"; SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), null), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage()); } }
@Test public void checkPermissionAssertNoExceptionWhenNamespaceBlank() throws Exception { // Mock a join point of the method call // mockMethod(" "); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {BLANK_TEXT}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }