Example usage for org.springframework.security.core GrantedAuthority getAuthority

List of usage examples for org.springframework.security.core GrantedAuthority getAuthority

Introduction

In this page you can find the example usage for org.springframework.security.core GrantedAuthority getAuthority.

Prototype

String getAuthority();

Source Link

Document

If the GrantedAuthority can be represented as a String and that String is sufficient in precision to be relied upon for an access control decision by an AccessDecisionManager (or delegate), this method should return such a String.

Usage

From source file:org.apache.kylin.rest.service.LegacyUserService.java

public List<String> listUserAuthorities() {
    List<String> all = new ArrayList<String>();
    for (UserDetails user : listUsers()) {
        for (GrantedAuthority auth : user.getAuthorities()) {
            if (!all.contains(auth.getAuthority())) {
                all.add(auth.getAuthority());
            }//from  w w w.j  a  v a  2  s  . co  m
        }
    }
    return all;
}

From source file:org.apache.kylin.rest.service.QueryService.java

private SQLResponse queryWithSqlMassage(SQLRequest sqlRequest) throws Exception {
    String userInfo = SecurityContextHolder.getContext().getAuthentication().getName();
    final Collection<? extends GrantedAuthority> grantedAuthorities = SecurityContextHolder.getContext()
            .getAuthentication().getAuthorities();
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        userInfo += ",";
        userInfo += grantedAuthority.getAuthority();
    }// w  ww  .  jav  a2  s  .co  m

    SQLResponse fakeResponse = TableauInterceptor.tableauIntercept(sqlRequest.getSql());
    if (null != fakeResponse) {
        logger.debug("Return fake response, is exception? " + fakeResponse.getIsException());
        return fakeResponse;
    }

    String correctedSql = QueryUtil.massageSql(sqlRequest.getSql(), sqlRequest.getProject(),
            sqlRequest.getLimit(), sqlRequest.getOffset());
    if (!correctedSql.equals(sqlRequest.getSql())) {
        logger.info("The corrected query: " + correctedSql);

        //CAUTION: should not change sqlRequest content!
        //sqlRequest.setSql(correctedSql);
    }

    // add extra parameters into olap context, like acceptPartial
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put(OLAPContext.PRM_USER_AUTHEN_INFO, userInfo);
    parameters.put(OLAPContext.PRM_ACCEPT_PARTIAL_RESULT, String.valueOf(sqlRequest.isAcceptPartial()));
    OLAPContext.setParameters(parameters);
    // force clear the query context before a new query
    OLAPContext.clearThreadLocalContexts();

    return execute(correctedSql, sqlRequest);

}

From source file:org.apache.syncope.core.misc.security.MustChangePasswordFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    if (request instanceof SecurityContextHolderAwareRequestWrapper) {
        boolean isMustChangePassword = IterableUtils.matchesAny(
                SecurityContextHolder.getContext().getAuthentication().getAuthorities(),
                new Predicate<GrantedAuthority>() {

                    @Override//from w w w . j a v  a  2 s . c om
                    public boolean evaluate(final GrantedAuthority authority) {
                        return StandardEntitlement.MUST_CHANGE_PASSWORD.equals(authority.getAuthority());
                    }
                });

        SecurityContextHolderAwareRequestWrapper wrapper = SecurityContextHolderAwareRequestWrapper.class
                .cast(request);
        if (isMustChangePassword && "GET".equalsIgnoreCase(wrapper.getMethod())
                && !ArrayUtils.contains(ALLOWED, wrapper.getPathInfo())) {

            throw new AccessDeniedException("Please change your password first");
        }
    }

    chain.doFilter(request, response);
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

private void setWicketRoles(Authentication authentication) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    String[] authorityRoles = new String[authorities.size()];
    int i = 0;/*from w w  w  . jav a2s .  co m*/
    for (GrantedAuthority authority : authorities) {
        String role = authority.getAuthority();
        authorityRoles[i] = role;
        i++;
    }
    roles = new Roles(authorityRoles);
}

From source file:org.broadleafcommerce.openadmin.server.security.ldap.BroadleafAdminLdapUserDetailsMapper.java

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
        Collection<? extends GrantedAuthority> authorities) {
    HashSet<String> newRoles = new HashSet<String>();

    if (roleNameSubstitutions != null && !roleNameSubstitutions.isEmpty()) {
        for (GrantedAuthority authority : authorities) {
            if (roleNameSubstitutions.containsKey(authority.getAuthority())) {
                String[] roles = roleNameSubstitutions.get(authority.getAuthority());
                for (String role : roles) {
                    newRoles.add(role.trim());
                }//from w  w  w  . ja  v a 2  s  . co  m
            } else {
                newRoles.add(authority.getAuthority());
            }
        }
    } else {
        for (GrantedAuthority authority : authorities) {
            newRoles.add(authority.getAuthority());
        }
    }

    Collection<GrantedAuthority> newAuthorities = new HashSet<GrantedAuthority>();
    for (String perm : AdminSecurityService.DEFAULT_PERMISSIONS) {
        newAuthorities.add(new SimpleGrantedAuthority(perm));
    }

    HashSet<AdminRole> grantedRoles = new HashSet<AdminRole>();
    List<AdminRole> adminRoles = securityService.readAllAdminRoles();
    if (adminRoles != null) {
        for (AdminRole role : adminRoles) {
            if (newRoles.contains(role.getName())) {
                grantedRoles.add(role);
                Set<AdminPermission> permissions = role.getAllPermissions();
                if (permissions != null && !permissions.isEmpty()) {
                    for (AdminPermission permission : permissions) {
                        if (permission.isFriendly()) {
                            for (AdminPermission childPermission : permission.getAllChildPermissions()) {
                                newAuthorities.add(new SimpleGrantedAuthority(childPermission.getName()));
                            }
                        } else {
                            newAuthorities.add(new SimpleGrantedAuthority(permission.getName()));
                        }
                    }
                }
            }
        }
    }

    String email = (String) ctx.getObjectAttribute("mail");
    String firstName = (String) ctx.getObjectAttribute("givenName");
    String lastName = (String) ctx.getObjectAttribute("sn");
    AdminUser adminUser = securityService.readAdminUserByUserName(username);
    if (adminUser == null) {
        adminUser = new AdminUserImpl();
        adminUser.setLogin(username);
    }

    if (StringUtils.isNotBlank(email)) {
        adminUser.setEmail(email);
    }

    StringBuilder name = new StringBuilder();
    if (StringUtils.isNotBlank(firstName)) {
        name.append(firstName).append(" ");
    }
    if (StringUtils.isNotBlank(lastName)) {
        name.append(lastName);
    }

    String fullName = name.toString();
    if (StringUtils.isNotBlank(fullName)) {
        adminUser.setName(fullName);
    } else {
        adminUser.setName(username);
    }

    adminUser = saveAdminUserAndSecurityData(adminUser, grantedRoles);

    return new AdminUserDetails(adminUser.getId(), username, "", true, true, true, true, newAuthorities);
}

From source file:org.broadleafcommerce.openadmin.server.security.service.AdminUserProvisioningServiceImpl.java

@Override
public AdminUserDetails provisionAdminUser(BroadleafExternalAuthenticationUserDetails details) {
    HashSet<String> newRoles = new HashSet<String>();

    if (roleNameSubstitutions != null && !roleNameSubstitutions.isEmpty()) {
        for (GrantedAuthority authority : details.getAuthorities()) {
            if (roleNameSubstitutions.containsKey(authority.getAuthority())) {
                String[] roles = roleNameSubstitutions.get(authority.getAuthority());
                for (String role : roles) {
                    newRoles.add(role.trim());
                }//from ww w. ja  va2 s .  c  om
            } else {
                newRoles.add(authority.getAuthority());
            }
        }
    } else {
        for (GrantedAuthority authority : details.getAuthorities()) {
            newRoles.add(authority.getAuthority());
        }
    }

    HashSet<GrantedAuthority> newAuthorities = new HashSet<GrantedAuthority>();
    for (String perm : AdminSecurityService.DEFAULT_PERMISSIONS) {
        newAuthorities.add(new SimpleGrantedAuthority(perm));
    }

    HashSet<AdminRole> grantedRoles = new HashSet<AdminRole>();
    List<AdminRole> adminRoles = securityService.readAllAdminRoles();
    if (adminRoles != null) {
        for (AdminRole role : adminRoles) {
            if (newRoles.contains(role.getName())) {
                grantedRoles.add(role);
                Set<AdminPermission> permissions = role.getAllPermissions();
                if (permissions != null && !permissions.isEmpty()) {
                    for (AdminPermission permission : permissions) {
                        if (permission.isFriendly()) {
                            for (AdminPermission childPermission : permission.getAllChildPermissions()) {
                                newAuthorities.add(new SimpleGrantedAuthority(childPermission.getName()));
                            }
                        } else {
                            newAuthorities.add(new SimpleGrantedAuthority(permission.getName()));
                        }
                    }
                }
            }
        }
    }

    AdminUser adminUser = securityService.readAdminUserByUserName(details.getUsername());
    if (adminUser == null) {
        adminUser = new AdminUserImpl();
        adminUser.setLogin(details.getUsername());
    }

    if (StringUtils.isNotBlank(details.getEmail())) {
        adminUser.setEmail(details.getEmail());
    }

    StringBuilder name = new StringBuilder();
    if (StringUtils.isNotBlank(details.getFirstName())) {
        name.append(details.getFirstName()).append(" ");
    }
    if (StringUtils.isNotBlank(details.getLastName())) {
        name.append(details.getLastName());
    }

    String fullName = name.toString();
    if (StringUtils.isNotBlank(fullName)) {
        adminUser.setName(fullName);
    } else {
        adminUser.setName(details.getUsername());
    }

    //We have to do this because BLC replies on the role relationships being stored in the DB
    Set<AdminRole> roleSet = adminUser.getAllRoles();
    //First, remove all roles associated with the user if they already existed
    if (roleSet != null) {
        //First, remove all role relationships in case they have changed
        roleSet.clear();
    } else {
        roleSet = new HashSet<AdminRole>();
        adminUser.setAllRoles(roleSet);
    }

    //Now, add all of the role relationships back.
    if (adminRoles != null) {
        for (AdminRole role : adminRoles) {
            roleSet.add(role);
        }
    }

    //Add optional support for things like Multi-Tenant, etc...
    adminExternalLoginExtensionManager.getProxy().performAdditionalAuthenticationTasks(adminUser, details);

    //Save the user data and all of the roles...
    adminUser = securityService.saveAdminUser(adminUser);

    return new AdminUserDetails(adminUser.getId(), details.getUsername(), "", true, true, true, true,
            newAuthorities);
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected Collection<? extends GrantedAuthority> mapAuthorities(String origin,
        Collection<? extends GrantedAuthority> authorities) {
    Collection<GrantedAuthority> result = new LinkedList<>();
    for (GrantedAuthority authority : authorities) {
        String externalGroup = authority.getAuthority();
        for (ScimGroupExternalMember internalGroup : externalMembershipManager
                .getExternalGroupMapsByExternalGroup(externalGroup, origin)) {
            result.add(new SimpleGrantedAuthority(internalGroup.getDisplayName()));
        }//from   w w w .j  av a 2s  . co  m
    }
    return result;
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenKeyEndpoint.java

protected boolean includeSymmetricalKeys(Principal principal) {
    if (principal != null) {
        if (principal instanceof AnonymousAuthenticationToken) {
            return false;
        } else if (principal instanceof Authentication) {
            Authentication auth = (Authentication) principal;
            if (auth.getAuthorities() != null) {
                for (GrantedAuthority authority : auth.getAuthorities()) {
                    if ("uaa.resource".equals(authority.getAuthority())) {
                        return true;
                    }/* w  ww .  j a  v  a 2  s . c  o  m*/
                }
            }
        }
    }
    return false;
}

From source file:org.cloudfoundry.identity.uaa.scim.bootstrap.ScimUserBootstrap.java

@Override
public void onApplicationEvent(AuthEvent event) {
    if (event instanceof InvitedUserAuthenticatedEvent) {
        ScimUser user = getScimUser(event.getUser());
        updateUser(user, event.getUser(), false);
        return;//  ww w .  j  a va 2 s  . co m
    }

    if (event instanceof ExternalGroupAuthorizationEvent) {
        ExternalGroupAuthorizationEvent exEvent = (ExternalGroupAuthorizationEvent) event;
        //delete previous membership relation ships
        String origin = exEvent.getUser().getOrigin();
        if (!OriginKeys.UAA.equals(origin)) {//only delete non UAA relationships
            membershipManager.delete(
                    "member_id eq \"" + event.getUser().getId() + "\" and origin eq \"" + origin + "\"");
        }
        for (GrantedAuthority authority : exEvent.getExternalAuthorities()) {
            addToGroup(exEvent.getUser().getId(), authority.getAuthority(), exEvent.getUser().getOrigin(),
                    exEvent.isAddGroups());
        }
        //update the user itself
        if (event.isUserModified()) {
            //update the user itself
            ScimUser user = getScimUser(event.getUser());
            updateUser(user, event.getUser(), false);
        }
        return;
    }

    if (event instanceof NewUserAuthenticatedEvent) {
        addUser(event.getUser());
        return;
    }
}

From source file:org.cloudifysource.rest.security.CustomPermissionEvaluator.java

/**
 * Returns the names of the roles (authorities) the user is granted.
 * @param authentication The authentication object of the current user
 * @return A Collection of roles (authorities) the user is granted.
 *///  www .j  a v  a2  s  .c o m
private Collection<String> getUserRoles(final Authentication authentication) {
    Set<String> userRoles = new HashSet<String>();

    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        throw new AccessDeniedException("Anonymous user is not supported");
    }

    if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
        throw new AccessDeniedException(
                "Authentication object type not supported. " + "Verify your Spring configuration is valid.");
    }

    for (GrantedAuthority authority : authentication.getAuthorities()) {
        userRoles.add(authority.getAuthority());
    }

    return userRoles;
}