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:de.iew.services.impl.UserDetailsServiceImpl.java

/**
 * {@inheritDoc}/*from   w ww.  j  a  v a 2  s .  c  om*/
 * <p>
 * Die Implementierung wurde von Spring bernommen.
 * </p>
 *
 * @see org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper#isGranted(String)
 */
public boolean isAuthenticatedUserInRole(String role) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null || auth.getPrincipal() == null) {
        return false;
    }

    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    if (authorities == null) {
        return false;
    }

    for (GrantedAuthority grantedAuthority : authorities) {
        if (role.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }

    return false;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.security.impl.SecurityUtilImpl.java

/**
 * @return an array of String representing the authorities (<code>GrantedAuthority</code>) granted to the authenticated principal
 *//*from  w  w w . j a  v a 2s . co  m*/
public String[] getAuthenticatedPrincipalAuthorities() {

    List<String> result = new ArrayList<String>();

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        Collection<GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
        if (grantedAuthorities != null) {
            for (GrantedAuthority grantedAuthority : grantedAuthorities) {
                result.add(grantedAuthority.getAuthority());
            }
        } else {
            logger.debug("The authenticated user's authorities are null for user "
                    + getAuthenticatedPrincipalLoginName());
        }
    }

    return (String[]) result.toArray();
}

From source file:com.web.mavenproject6.controller.MainController.java

@RequestMapping(value = { "/" })
public String login(Model model, @RequestParam(required = false) String message) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isSecure = false;
    for (GrantedAuthority role : auth.getAuthorities()) {
        if (role.getAuthority().equals("ROLE_SECURE")) {
            isSecure = true;// www  .jav  a2 s  . com
        }
    }
    if (isSecure) {
        return "thy/camera";
    }

    UserDetails ud = (UserDetails) auth.getPrincipal();

    Users u = userService.getRepository().findUserByEmail(ud.getUsername());
    if (u == null) {
        u = userService.getRepository().findUserByLogin(ud.getUsername());
    }

    if (u == null) {
        return "thy/error/404";
    }

    model.addAttribute("propId", u.getPerson().getAccessNumber());
    return "thy/personal/profile";
}

From source file:gmc.gestaxi.controller.UserServiceImpl.java

@Override
public boolean isUserAuthorizedWithRole(String roleToTest) {
    boolean isAuthorized = false;
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    if (userAuth != null) {
        Collection<GrantedAuthority> roles = (Collection<GrantedAuthority>) userAuth.getAuthorities();
        for (GrantedAuthority role : roles) {
            if (role.getAuthority().equalsIgnoreCase(roleToTest)) {
                isAuthorized = true;//w  ww .  j a v a2s  .  c o m
            }
        }
    }
    return isAuthorized;
}

From source file:net.solarnetwork.central.dras.aop.SecurityAspectSupport.java

/**
 * Test if the current user has a specific role.
 * //from  w w w.  ja  v a  2  s  . c o  m
 * <p>If more than one role is provided, any role is allowed to match,
 * i.e. the set of roles is treated as an "or" style match.</p>
 * 
 * @param role the roles to test for
 * @return <em>true</em> if the current user has the role
 */
protected final boolean currentUserHasRole(final String... role) {
    // see if we return ALL programs, or just those for the current user
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    for (GrantedAuthority ga : auth.getAuthorities()) {
        for (String r : role) {
            if (r.equalsIgnoreCase(ga.getAuthority())) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.castlemock.war.config.SecurityInterceptor.java

/**
 * The method will check if the logged in user is still valid.
 * @param request The incoming request./*w ww  . j av  a 2  s . c  o m*/
 * @param response The outgoing response
 * @param handler The handler contains information about the method and controller that will process the incoming request
 * @return Returns true if the logged in users information is still valid. Returns false if the user is not valid
 * @throws IOException Upon unable to send a redirect as a response
 * @throws ServletException Upon unable to logout the user
 */
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws IOException, ServletException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return true;
    }

    final String loggedInUsername = authentication.getName();
    if (ANONYMOUS_USER.equals(loggedInUsername)) {
        return true;
    }

    final ReadUserByUsernameInput readUserByUsernameInput = new ReadUserByUsernameInput(loggedInUsername);
    final ReadUserByUsernameOutput readUserByUsernameOutput = serviceProcessor.process(readUserByUsernameInput);
    final UserDto loggedInUser = readUserByUsernameOutput.getUser();
    if (loggedInUser == null) {
        LOGGER.info("The following logged in user is not valid anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else if (!Status.ACTIVE.equals(loggedInUser.getStatus())) {
        LOGGER.info("The following logged in user is not active anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else {
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            Role role = Role.valueOf(grantedAuthority.getAuthority());
            if (!loggedInUser.getRole().equals(role)) {
                LOGGER.info("The following logged in user's authorities has been updated: " + loggedInUsername);
                final UserDetails userDetails = userDetailSecurityService.loadUserByUsername(loggedInUsername);
                final Authentication newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
                        userDetails.getPassword(), userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(newAuthentication);
            }
        }
        return true;
    }
}

From source file:de.itsvs.cwtrpc.sample1.server.service.SampleServiceImpl.java

public String getInfo() {
    final StringBuilder info = new StringBuilder();
    final Authentication auth;
    boolean first;

    auth = SecurityContextHolder.getContext().getAuthentication();
    log.info("User '" + auth.getName() + "' is requesting info");

    info.append("Number of Requests: " + (++infoCount) + "\n");
    info.append("User Name: " + auth.getName() + "\n");
    info.append("Roles: ");

    first = true;//  w w w .jav  a  2s.c  om
    for (GrantedAuthority ga : auth.getAuthorities()) {
        if (!first) {
            info.append(", ");
        }
        first = false;
        info.append(ga.getAuthority());
    }

    return info.toString();
}

From source file:com.wooki.services.security.WookiSecurityContextImpl.java

public boolean hasAuthority(GrantedAuthority authority) {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
        for (GrantedAuthority auth : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            if (auth.getAuthority().equals(authority.getAuthority())) {
                return true;
            }/*from w w  w. j a  va 2  s.c  o m*/
        }
    }
    return false;
}

From source file:org.openinfinity.core.aspect.AuditTrailAspect.java

private void writeRolesToAuditTrailIfEnabled(ArgumentBuilder builder, AuditTrail auditTrail,
        Authentication authentication) {
    if (auditTrail.isRolesEnabled() && authentication != null && authentication.getAuthorities() != null) {
        Collection<? extends GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
        builder.append(" with granted authorities: [");
        for (GrantedAuthority grantedAuthority : grantedAuthorities)
            builder.append("{" + grantedAuthority.getAuthority() + "}");
        builder.append("] ");
    }/*from  w  w w  .j  a  va  2s .c  o  m*/
}

From source file:org.openmrs.contrib.metadatarepository.service.UserSecurityAdvice.java

/**
 * Method to enforce security and only allow administrators to modify users. Regular
 * users are allowed to modify themselves.
 *
 * @param method the name of the method executed
 * @param args the arguments to the method
 * @param target the target class/*www.ja va  2s .  c  om*/
 * @throws Throwable thrown when args[0] is null or not a User object
 */
public void before(Method method, Object[] args, Object target) throws Throwable {
    SecurityContext ctx = SecurityContextHolder.getContext();

    if (ctx.getAuthentication() != null) {
        Authentication auth = ctx.getAuthentication();
        boolean administrator = false;
        Collection<GrantedAuthority> roles = auth.getAuthorities();
        for (GrantedAuthority role1 : roles) {
            if (role1.getAuthority().equals(Constants.ADMIN_ROLE)) {
                administrator = true;
                break;
            }
        }

        User user = (User) args[0];

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
        boolean signupUser = resolver.isAnonymous(auth);

        if (!signupUser) {
            User currentUser = getCurrentUser(auth);

            if (user.getId() != null && !user.getId().equals(currentUser.getId()) && !administrator) {
                log.warn("Access Denied: '" + currentUser.getUsername() + "' tried to modify '"
                        + user.getUsername() + "'!");
                throw new AccessDeniedException(ACCESS_DENIED);
            } else if (user.getId() != null && user.getId().equals(currentUser.getId()) && !administrator) {
                // get the list of roles the user is trying add
                Set<String> userRoles = new HashSet<String>();
                if (user.getRoles() != null) {
                    for (Object o : user.getRoles()) {
                        Role role = (Role) o;
                        userRoles.add(role.getName());
                    }
                }

                // get the list of roles the user currently has
                Set<String> authorizedRoles = new HashSet<String>();
                for (GrantedAuthority role : roles) {
                    authorizedRoles.add(role.getAuthority());
                }

                // if they don't match - access denied
                // regular users aren't allowed to change their roles
                if (!CollectionUtils.isEqualCollection(userRoles, authorizedRoles)) {
                    log.warn("Access Denied: '" + currentUser.getUsername()
                            + "' tried to change their role(s)!");
                    throw new AccessDeniedException(ACCESS_DENIED);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Registering new user '" + user.getUsername() + "'");
            }
        }
    }
}