List of usage examples for org.springframework.security.core Authentication getAuthorities
Collection<? extends GrantedAuthority> getAuthorities();
AuthenticationManager
to indicate the authorities that the principal has been granted. From source file:org.pentaho.platform.engine.security.acls.PentahoGrantedAuthorityEffectiveAclsResolver.java
public IAclEntry[] resolveEffectiveAcls(IAclEntry[] allAcls, Authentication filteredBy) { if ((allAcls == null) || (allAcls.length == 0)) { return null; }//from ww w. ja va2 s . co m List list = new Vector(); if (logger.isDebugEnabled()) { logger.debug("Locating AclEntry[]s (from set of " + ((allAcls == null) ? 0 : allAcls.length) + ") that apply to Authentication: " + filteredBy); } for (int i = 0; i < allAcls.length; i++) { if (!(allAcls[i] instanceof IPentahoBasicAclEntry)) { continue; } Object recipient = ((IPentahoBasicAclEntry) allAcls[i]).getRecipient(); // Allow the Authentication's getPrincipal to decide whether // the presented recipient is "equal" (allows BasicAclDaos to // return Strings rather than proper objects in simple cases) if (filteredBy.getPrincipal().equals(recipient)) { if (logger.isDebugEnabled()) { logger.debug("Principal matches AclEntry recipient: " + recipient); } list.add(allAcls[i]); } else if (filteredBy.getPrincipal() instanceof UserDetails && ((UserDetails) filteredBy.getPrincipal()).getUsername().equals(recipient)) { if (logger.isDebugEnabled()) { logger.debug("Principal (from UserDetails) matches AclEntry recipient: " + recipient); } list.add(allAcls[i]); } else { // No direct match against principal; try each authority. // As with the principal, allow each of the Authentication's // granted authorities to decide whether the presented // recipient is "equal" Collection<? extends GrantedAuthority> authoritiesCollection = filteredBy.getAuthorities(); GrantedAuthority[] authorities = authoritiesCollection.toArray(new GrantedAuthority[] {}); if ((authorities == null) || (authorities.length == 0)) { if (logger.isDebugEnabled()) { logger.debug("Did not match principal and there are no granted authorities, " + "so cannot compare with recipient: " + recipient); } continue; } for (int k = 0; k < authorities.length; k++) { if (authorities[k].equals(recipient)) { if (logger.isDebugEnabled()) { logger.debug( "GrantedAuthority: " + authorities[k] + " matches recipient: " + recipient); } list.add(allAcls[i]); } } } } // return null if appropriate (as per interface contract) if (list.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Returning effective AclEntry array with " + list.size() + " elements"); } return (IPentahoBasicAclEntry[]) list.toArray(new IPentahoBasicAclEntry[] {}); } else { if (logger.isDebugEnabled()) { logger.debug("Returning null AclEntry array as zero effective AclEntrys found"); } return null; } }
From source file:org.slc.sli.api.service.BasicService.java
protected Collection<GrantedAuthority> getAuths(boolean isSelf) { Collection<GrantedAuthority> result = new HashSet<GrantedAuthority>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); result.addAll(auth.getAuthorities()); if (isSelf) { SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); result.addAll(principal.getSelfRights()); }//from w ww.j a v a 2 s . c o m return result; }
From source file:org.springframework.security.access.intercept.MethodInvocationPrivilegeEvaluator.java
public boolean isAllowed(MethodInvocation mi, Authentication authentication) { Assert.notNull(mi, "MethodInvocation required"); Assert.notNull(mi.getMethod(), "MethodInvocation must provide a non-null getMethod()"); Collection<ConfigAttribute> attrs = securityInterceptor.obtainSecurityMetadataSource().getAttributes(mi); if (attrs == null) { if (securityInterceptor.isRejectPublicInvocations()) { return false; }//from w w w . jav a2 s . co m return true; } if (authentication == null || authentication.getAuthorities().isEmpty()) { return false; } try { securityInterceptor.getAccessDecisionManager().decide(authentication, mi, attrs); } catch (AccessDeniedException unauthorized) { if (logger.isDebugEnabled()) { logger.debug(mi.toString() + " denied for " + authentication.toString(), unauthorized); } return false; } return true; }
From source file:org.springframework.security.access.vote.LabelBasedAclVoter.java
/** * Vote on whether or not the user has all the labels necessary to match the method argument's labeled data. * * @return ACCESS_ABSTAIN, ACCESS_GRANTED, or ACCESS_DENIED. *//*from w ww . j av a 2 s . c om*/ public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { int result = ACCESS_ABSTAIN; if (logger.isDebugEnabled()) { logger.debug("=========================================================="); } if (this.supports(attributes.iterator().next())) { result = ACCESS_DENIED; /* Parse out the user's labels by examining the security context, and checking * for matches against the label map. */ List<String> userLabels = new ArrayList<String>(); for (GrantedAuthority authority : authentication.getAuthorities()) { String userLabel = authority.getAuthority(); if (labelMap.containsKey(userLabel)) { userLabels.add(userLabel); logger.debug("Adding " + userLabel + " to <<<" + authentication.getName() + "'s>>> authorized label list"); } } MethodInvocation invocation = (MethodInvocation) object; int matches = 0; int misses = 0; int labeledArguments = 0; for (int j = 0; j < invocation.getArguments().length; j++) { if (invocation.getArguments()[j] instanceof LabeledData) { labeledArguments++; boolean matched = false; String argumentDataLabel = ((LabeledData) invocation.getArguments()[j]).getLabel(); logger.debug("Argument[" + j + "/" + invocation.getArguments()[j].getClass().getName() + "] has a data label of " + argumentDataLabel); List<String> validDataLabels = new ArrayList<String>(); for (int i = 0; i < userLabels.size(); i++) { validDataLabels.addAll(labelMap.get(userLabels.get(i))); } logger.debug("The valid labels for user label " + userLabels + " are " + validDataLabels); for (String validDataLabel : validDataLabels) { if (argumentDataLabel.equals(validDataLabel)) { logger.debug(userLabels + " maps to " + validDataLabel + " which matches the argument"); matched = true; } } if (matched) { logger.debug("We have a match!"); matches++; } else { logger.debug("We have a miss!"); misses++; } } } Assert.isTrue((matches + misses) == labeledArguments, "The matches (" + matches + ") and misses (" + misses + " ) don't add up (" + labeledArguments + ")"); logger.debug("We have " + matches + " matches and " + misses + " misses and " + labeledArguments + " labeled arguments."); /* The result has already been set to ACCESS_DENIED. Only if there is a proper match of * labels will this be overturned. However, if none of the attributes are actually labeled, * the result is dependent on allowAccessIfNoAttributesAreLabeled. */ if ((matches > 0) && (misses == 0)) { result = ACCESS_GRANTED; } else if (labeledArguments == 0) { if (allowAccessIfNoAttributesAreLabeled) { result = ACCESS_GRANTED; } else { result = ACCESS_DENIED; } } } if (logger.isDebugEnabled()) { switch (result) { case ACCESS_GRANTED: logger.debug("===== Access is granted ====="); break; case ACCESS_DENIED: logger.debug("===== Access is denied ====="); break; case ACCESS_ABSTAIN: logger.debug("===== Abstaining ====="); break; } } return result; }
From source file:org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java
License:asdf
@Test public void authenticateSuccess() throws Exception { Authentication auth = provider.authenticate(token); assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal()); assertThat(auth.getCredentials()).isEqualTo(token.getCredentials()); assertThat(auth.isAuthenticated()).isEqualTo(true); assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false); verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class)); verifyNoMoreInteractions(publisher); }
From source file:org.talend.daikon.security.access.RequiresAuthorityAspect.java
/** * Check if user should be allowed to an actions requiring supplied authority. * * @param authority the authority needed to proceed. * @return true if user is authenticated and has the permission, false otherwise. */// w ww . j a v a 2 s . co m private static boolean isAllowed(String authority) { if (authority == null) { return false; } // because of the security setup, auth must always be set final Authentication authentication = getContext().getAuthentication(); if (authentication != null) { // sonar is not able to understand that RestrictedAction implements GrantedAuthority if (authentication.getAuthorities().stream() .noneMatch(a -> StringUtils.equals(a.getAuthority(), authority))) { LOGGER.debug("User has not been allowed to use: {}", authority); return false; } else { LOGGER.debug("User has been allowed to use: {}", authority); return true; } } return false; }
From source file:org.training.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) @RequireHardLogIn//from w w w . j av a2 s. c o m public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { getEmailValidator().validate(updateEmailForm, bindingResult); String returnAction = REDIRECT_TO_UPDATE_EMAIL_PAGE; if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) { bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {}, "validation.checkEmail.equals"); } if (bindingResult.hasErrors()) { returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } else { try { customCustomerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword()); GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER, "text.account.profile.confirmationUpdated", null); // Replace the spring security authentication with the new UID final String newUid = customCustomerFacade.getCurrentCustomer().getUid().toLowerCase(); final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication(); final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( newUid, null, oldAuthentication.getAuthorities()); newAuthentication.setDetails(oldAuthentication.getDetails()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); } catch (final DuplicateUidException e) { bindingResult.rejectValue("email", "profile.email.unique"); returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } catch (final PasswordMismatchException passwordMismatchException) { bindingResult.rejectValue("password", PROFILE_CURRENT_PASSWORD_INVALID); returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } } return returnAction; }
From source file:org.waterforpeople.mapping.app.web.rest.dto.UserAuthorizationPayload.java
private boolean isAcceptablePath(String objectPath) { if (StringUtils.isNotBlank(objectPath)) { if ("/".equals(objectPath)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication.getAuthorities().contains(AppRole.SUPER_ADMIN); } else {/*from ww w . j a v a 2 s . co m*/ return true; } } else { return false; } }
From source file:org.yes.cart.bulkjob.bulkimport.LocalFileShareImportListenerImpl.java
private void runShopRootScan(final Logger defaultLog, final File shopDir, final String importDirPath, final Set<String> importGroupNames) { final Shop shop = shopService.getShopByCode(shopDir.getName()); if (shop != null) { ShopCodeContext.setShopCode(shop.getCode()); ShopCodeContext.setShopId(shop.getShopId()); final Logger shopLog = ShopCodeContext.getLog(this); try {/*w w w . j av a 2s . c om*/ defaultLog.info("Scanning processed directory for shop {}", shop.getCode()); shopLog.info("Scanning processed directory"); final File config = ensureDirectoryExists(defaultLog, shopLog, shopDir, shop, "config"); final File configProps = new File(config, "config.properties"); if (!configProps.exists()) { defaultLog.info("Configuration file is missing for shop {} ... skipping", shop.getCode()); shopLog.info("Configuration file is missing ... skipping"); return; } final Map<Pattern, Map<String, String>> patternGroupMap = loadShopAutoImportConfigurations(shopLog, configProps, importGroupNames); final File processed = ensureDirectoryExists(defaultLog, shopLog, shopDir, shop, "processed"); final File[] readyForImport = processed.listFiles(); if (readyForImport == null || readyForImport.length == 0) { defaultLog.info("No new files to import for shop {}", shop.getCode()); shopLog.info("No new files to import for shop {}", shop.getCode()); return; } final SimpleDateFormat format = new SimpleDateFormat("_yyyy-MMM-dd-hh-mm-ss-SSS"); for (final File toImport : prioritiseProcessedFiles(readyForImport)) { final String timestamp = format.format(new Date()); final File targetDirectory = new File(importDirPath + File.separator + PRINCIPAL + timestamp); targetDirectory.mkdirs(); defaultLog.info("Moving files to '{}' for shop {}", targetDirectory.getAbsolutePath(), shop.getCode()); shopLog.info("Moving files to '{}' for shop {}", targetDirectory.getAbsolutePath(), shop.getCode()); Map<String, String> groupData = null; for (final Map.Entry<Pattern, Map<String, String>> group : patternGroupMap.entrySet()) { if (group.getKey().matcher(toImport.getName()).matches()) { groupData = group.getValue(); break; } } if (groupData == null) { defaultLog.warn("Importing '{}' for shop {} ... skipping (no valid import group)", toImport.getAbsolutePath(), shop.getCode()); shopLog.warn("Importing '{}' for shop {} ... skipping (no valid import group)", toImport.getAbsolutePath(), shop.getCode()); continue; } final String groupName = groupData.get("group"); defaultLog.info("Importing '{}' for shop {} using group {}", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName }); shopLog.info("Importing '{}' for shop {} using group {}", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName }); final String destination = moveFileToImportDirectory(toImport, targetDirectory); try { final String user = groupData.get("user"); final String pass = groupData.get("pass"); final Authentication shopAuth = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(user, pass)); if (shopAuth.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication( new RunAsUserAuthentication(user, pass, shopAuth.getAuthorities())); // Make this synchronous since we are already in async process final String importToken = importDirectorService.doImport(groupName, destination, false); final JobStatus importStatus = importDirectorService.getImportStatus(importToken); defaultLog.info("Importing '{}' for shop {} using group {} ... completed [{}]", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName, importStatus.getCompletion() }); shopLog.info("Importing '{}' for shop {} using group {} ... completed [{}]", new Object[] { toImport.getAbsolutePath(), shop.getCode(), groupName, importStatus.getCompletion() }); remoteDevService.evictAllCache(); if (importStatus.getCompletion() == JobStatus.Completion.OK) { final boolean reindex = Boolean.valueOf(groupData.get("reindex")); if (reindex) { defaultLog.info("Re-indexed products for shop {} using group {} ... starting", new Object[] { shop.getCode(), groupName }); shopLog.info("Re-indexed products for shop {} using group {} ... starting", new Object[] { shop.getCode(), groupName }); Thread.sleep(INDEX_GET_READY_TIMEOUT); // let cache invalidation run before index final String indexToken = reindexService .reindexShopProducts(ShopCodeContext.getShopId()); while (true) { Thread.sleep(INDEX_PING_INTERVAL); JobStatus reindexStatus = reindexService.getIndexAllStatus(indexToken); if (reindexStatus.getState() == JobStatus.State.FINISHED) { defaultLog.info( "Re-indexed products for shop {} using group {} ... completed [{}]", new Object[] { shop.getCode(), groupName, reindexStatus.getCompletion() }); shopLog.info( "Re-indexed products for shop {} using group {} ... completed [{}]", new Object[] { shop.getCode(), groupName, reindexStatus.getCompletion() }); remoteDevService.evictAllCache(); Thread.sleep(WARMUP_GET_READY_TIMEOUT); remoteDevService.warmUp(); break; } } } } } else { defaultLog.warn("Invalid credentials for '{}' for shop {} using group {}", new Object[] { user, shop.getCode(), groupName }); shopLog.warn("Invalid credentials for '{}' for shop {} using group {}", new Object[] { user, shop.getCode(), groupName }); } } finally { // Reinstate global context of AutoImport SecurityContextHolder.getContext().setAuthentication(global); } } } catch (Exception exp) { defaultLog.error("Failed import configuration " + shop.getCode(), exp); shopLog.error("Failed import configuration " + shop.getCode(), exp); } finally { ShopCodeContext.clear(); } } }
From source file:pl.bcichecki.rms.services.impl.PrivilegesServiceImpl.java
@Override @SuppressWarnings("unchecked") public Set<PrivilegeType> getAuthenticatedUsersPrivileges() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return SetUtils.EMPTY_SET; }/* www . j av a 2s .co m*/ Set<PrivilegeType> privileges = new HashSet<PrivilegeType>(); for (GrantedAuthority g : authentication.getAuthorities()) { privileges.add(PrivilegeType.fromString(g.getAuthority())); } return privileges; }