Example usage for org.springframework.security.core Authentication getAuthorities

List of usage examples for org.springframework.security.core Authentication getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getAuthorities.

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

From source file:it.geosolutions.geoserver.sira.security.config.Rule.java

/**
 * Checks if the rule applies to at least one of the roles granted to the user.
 *
 * @param user the user accessing the resource
 * @return {@code true} if the rule applies to this user (based on granted roles), {@code false} otherwise
 *///from w  ww.  j a v a2 s. co  m
public boolean matchRole(Authentication user) {
    if (this.matchesAnyRole()) {
        return true;
    }

    final Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    // should never be null, but you never know...
    if (authorities != null) {
        for (final GrantedAuthority authority : authorities) {
            final String role = authority.getAuthority();
            if (role != null && this.getRoles().contains(role)) {
                return true;
            }
        }
    }

    return false;
}

From source file:org.vaadin.spring.security.GenericVaadinSecurity.java

/**
 * {@inheritDoc}//from w  w w .ja  v  a 2 s .c o  m
 */
@Override
public boolean hasAuthority(String authority) {
    final Authentication authentication = getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return false;
    }

    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (authority.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }

    return false;
}

From source file:org.modeshape.example.springsecurity.web.RepositoryController.java

@RequestMapping(value = { "/", "/modeshape-spring-security-example/" }, method = {
        RequestMethod.GET }, produces = "text/html; charset=utf-8")
public @ResponseBody String jcrLogin(Authentication auth) {
    String html = "";
    try {/*  w w  w .  jav  a 2  s. co m*/
        Session session = repository.login(new SpringSecurityCredentials(auth));

        String repoName = session.getRepository()
                .getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME);
        String wsName = session.getWorkspace().getName();

        html = "<html>" + "<body>" + "<h3>Welcome " + (auth.getName()) + "!</h3>"
                + "<p>You have successfully logged in to [" + (repoName + "." + wsName) + "]</p>"
                + "<p>You have granted " + auth.getAuthorities().toString() + " roles.</p>"
                + "<p><a href='/login?logout'>logout</a></p>" + "</body>" + "</html>";
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    return html;
}

From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }//from w w  w .ja v  a2s. c o  m
    UsernamePasswordAuthenticationToken output = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        output = (UsernamePasswordAuthenticationToken) authentication;
    } else {
        output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());
        output.setAuthenticated(authentication.isAuthenticated());
        output.setDetails(authentication.getDetails());
    }
    boolean authenticated = false;
    Authentication auth = null;
    AuthenticationException lastException = null;
    for (int i = 0; i < delegates.length && (!authenticated); i++) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Attempting chained authentication of " + output + " with manager:" + delegates[i]);
            }
            auth = delegates[i].authenticate(output);
            authenticated = auth.isAuthenticated();
        } catch (AuthenticationException x) {
            if (logger.isDebugEnabled()) {
                logger.debug("Chained authentication exception:", x);
            }
            lastException = x;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i]
                    + "; Authenticated:" + authenticated);
        }
    }
    if (authenticated) {
        return auth;
    } else if (lastException != null) {
        //we had at least one authentication exception, throw it
        throw lastException;
    } else {
        //not authenticated, but return the last of the result
        return auth;
    }
}

From source file:org.italiangrid.storm.webdav.authz.CopyMoveAuthzVoter.java

@Override
public int vote(Authentication authentication, FilterInvocation filter,
        Collection<ConfigAttribute> attributes) {

    if (!isCopyOrMoveRequest(filter.getRequest())) {
        return ACCESS_ABSTAIN;
    }//from   ww w  . j  a va 2 s .  c o m

    String destination = filter.getRequest().getHeader(DESTINATION);
    if (destination == null) {
        return ACCESS_ABSTAIN;
    }

    try {

        StorageAreaInfo sa = getSAFromPath(destination);

        if (sa == null) {
            return ACCESS_DENIED;
        }

        if (authentication.getAuthorities().contains(SAPermission.canWrite(sa.name()))) {

            return ACCESS_GRANTED;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Access denied. Principal does not have write permissions on " + "storage area {}",
                    sa.name());

        }

        return ACCESS_DENIED;

    } catch (MalformedURLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

}

From source file:org.carewebframework.security.spring.AbstractSecurityService.java

/**
 * Determine if the granted authority exists within the authentication context.
 * //from w ww.  j av a 2 s . com
 * @param grantedAuthority The granted authority to check.
 * @param authentication The authentication context.
 * @return True if the granted authority exists within the authentication context.
 */
private boolean isGranted(String grantedAuthority, Authentication authentication) {
    if (authentication == null) {
        log.info("Authentication context was null during check for granted authority '" + grantedAuthority
                + "'.");
        return false;
    }

    boolean result = authentication.getAuthorities().contains(new SimpleGrantedAuthority(grantedAuthority));

    if (!result) {
        String alias = authorityAlias.get(grantedAuthority);
        return alias != null && isGranted(alias, authentication);
    }

    return result;
}

From source file:eu.openanalytics.rsb.security.ApplicationPermissionEvaluator.java

private boolean isAuthenticationAuthorized(final Authentication authentication,
        final Set<String> authorizedPrincipals, final Set<String> authorizedRoles) {
    final String userName = getUserName(authentication);

    if ((StringUtils.isNotBlank(userName)) && (!CollectionUtils.isEmpty(authorizedPrincipals))
            && (authorizedPrincipals.contains(userName))) {
        return true;
    }/* w w  w . java  2s  .  com*/

    final Set<String> roles = new HashSet<String>();
    for (final GrantedAuthority authority : authentication.getAuthorities()) {
        roles.add(authority.getAuthority());
    }

    return CollectionUtils.containsAny(authorizedRoles, roles);
}

From source file:org.springframework.cloud.dataflow.server.controller.AboutController.java

/**
 * Return meta information about the dataflow server.
 *
 * @return Detailed information about the enabled features, versions of implementation
 * libraries, and security configuration
 *///from  w w  w.j av a 2 s.co m
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public AboutResource getAboutResource() {
    final AboutResource aboutResource = new AboutResource();
    final FeatureInfo featureInfo = new FeatureInfo();
    featureInfo.setStreamsEnabled(featuresProperties.isStreamsEnabled());
    featureInfo.setTasksEnabled(featuresProperties.isTasksEnabled());
    featureInfo.setSchedulesEnabled(featuresProperties.isSchedulesEnabled());
    featureInfo.setGrafanaEnabled(this.grafanaProperties.isGrafanaEnabled());

    final VersionInfo versionInfo = getVersionInfo();

    aboutResource.setFeatureInfo(featureInfo);
    aboutResource.setVersionInfo(versionInfo);

    final boolean authenticationEnabled = securityStateBean.isAuthenticationEnabled();

    final SecurityInfo securityInfo = new SecurityInfo();
    securityInfo.setAuthenticationEnabled(authenticationEnabled);

    if (authenticationEnabled && SecurityContextHolder.getContext() != null) {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            securityInfo.setAuthenticated(authentication.isAuthenticated());
            securityInfo.setUsername(authentication.getName());

            for (Object authority : authentication.getAuthorities()) {
                final GrantedAuthority grantedAuthority = (GrantedAuthority) authority;
                securityInfo.addRole(grantedAuthority.getAuthority());
            }
        }
    }

    aboutResource.setSecurityInfo(securityInfo);

    final RuntimeEnvironment runtimeEnvironment = new RuntimeEnvironment();

    if (!authenticationEnabled
            || (authenticationEnabled && SecurityContextHolder.getContext().getAuthentication() != null)) {
        if (this.streamDeployer != null) {
            try {
                final RuntimeEnvironmentInfo deployerEnvironmentInfo = this.streamDeployer.environmentInfo();
                final RuntimeEnvironmentDetails deployerInfo = new RuntimeEnvironmentDetails();

                deployerInfo
                        .setDeployerImplementationVersion(deployerEnvironmentInfo.getImplementationVersion());
                deployerInfo.setDeployerName(deployerEnvironmentInfo.getImplementationName());
                deployerInfo.setDeployerSpiVersion(deployerEnvironmentInfo.getSpiVersion());
                deployerInfo.setJavaVersion(deployerEnvironmentInfo.getJavaVersion());
                deployerInfo.setPlatformApiVersion(deployerEnvironmentInfo.getPlatformApiVersion());
                deployerInfo.setPlatformClientVersion(deployerEnvironmentInfo.getPlatformClientVersion());
                deployerInfo.setPlatformHostVersion(deployerEnvironmentInfo.getPlatformHostVersion());
                deployerInfo.setPlatformSpecificInfo(deployerEnvironmentInfo.getPlatformSpecificInfo());
                deployerInfo.setPlatformHostVersion(deployerEnvironmentInfo.getPlatformHostVersion());
                deployerInfo.setPlatformType(deployerEnvironmentInfo.getPlatformType());
                deployerInfo.setSpringBootVersion(deployerEnvironmentInfo.getSpringBootVersion());
                deployerInfo.setSpringVersion(deployerEnvironmentInfo.getSpringVersion());

                runtimeEnvironment.setAppDeployer(deployerInfo);
            } catch (ResourceAccessException rae) {
                logger.warn("Skipper Server is not accessible", rae);
            }
        }
        if (this.launcherRepository != null) {
            final List<RuntimeEnvironmentDetails> taskLauncherInfoList = new ArrayList<RuntimeEnvironmentDetails>();
            for (Launcher launcher : this.launcherRepository.findAll()) {
                TaskLauncher taskLauncher = launcher.getTaskLauncher();
                RuntimeEnvironmentDetails taskLauncherInfo = new RuntimeEnvironmentDetails();
                final RuntimeEnvironmentInfo taskLauncherEnvironmentInfo = taskLauncher.environmentInfo();
                taskLauncherInfo.setDeployerImplementationVersion(
                        taskLauncherEnvironmentInfo.getImplementationVersion());
                taskLauncherInfo.setDeployerName(taskLauncherEnvironmentInfo.getImplementationName());
                taskLauncherInfo.setDeployerSpiVersion(taskLauncherEnvironmentInfo.getSpiVersion());
                taskLauncherInfo.setJavaVersion(taskLauncherEnvironmentInfo.getJavaVersion());
                taskLauncherInfo.setPlatformApiVersion(taskLauncherEnvironmentInfo.getPlatformApiVersion());
                taskLauncherInfo
                        .setPlatformClientVersion(taskLauncherEnvironmentInfo.getPlatformClientVersion());
                taskLauncherInfo.setPlatformHostVersion(taskLauncherEnvironmentInfo.getPlatformHostVersion());
                taskLauncherInfo.setPlatformSpecificInfo(taskLauncherEnvironmentInfo.getPlatformSpecificInfo());
                taskLauncherInfo.setPlatformHostVersion(taskLauncherEnvironmentInfo.getPlatformHostVersion());
                taskLauncherInfo.setPlatformType(taskLauncherEnvironmentInfo.getPlatformType());
                taskLauncherInfo.setSpringBootVersion(taskLauncherEnvironmentInfo.getSpringBootVersion());
                taskLauncherInfo.setSpringVersion(taskLauncherEnvironmentInfo.getSpringVersion());
                taskLauncherInfoList.add(taskLauncherInfo);
            }
            runtimeEnvironment.setTaskLaunchers(taskLauncherInfoList);
        }
    }
    aboutResource.setRuntimeEnvironment(runtimeEnvironment);

    if (this.grafanaProperties.isGrafanaEnabled()) {
        final GrafanaInfo grafanaInfo = new GrafanaInfo();
        grafanaInfo.setUrl(this.grafanaProperties.getUrl());
        grafanaInfo.setRefreshInterval(this.grafanaProperties.getRefreshInterval());
        aboutResource.setGrafanaInfo(grafanaInfo);
    }

    aboutResource.add(ControllerLinkBuilder.linkTo(AboutController.class).withSelfRel());

    return aboutResource;
}