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: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.
 *//*from  w w  w  .j  a  va  2 s  . c  om*/
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;
}

From source file:org.cms.config.CustomUrlAuthenticationSuccessHandler.java

protected String determineTargetUrl(Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
            isUser = true;/*from   w  ww. j av  a2  s  . c  om*/
            break;
        } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
            isAdmin = true;
            break;
        }
    }
    if (isUser) {
        return "/pocetna";
    } else if (isAdmin) {
        return "/admin/home";
    } else {
        throw new IllegalStateException();
    }
}

From source file:org.collectionspace.services.authorization.spring.SpringPermissionEvaluator.java

private void debug(CSpaceResource res, Authentication authToken, Serializable objectIdId, String objectIdType,
        Permission perm) {/*  w ww  .  j a  v a2s .com*/
    if (log.isTraceEnabled() == true) {
        log.debug(this.getClass().getCanonicalName() + ":" + this);
        String resourceTarget = "[" + res.getId() + "]" + " | " + "[" + "objectIdId: " + objectIdType + "("
                + objectIdId + ")]";
        System.out.println("PERMISSION CHECK FOR: " + resourceTarget);
        System.out.println("\tPrincipal: " + authToken.getName() + "\tTenant ID: " + res.getTenantId());
        System.out.println("\tRoles: " + authToken.getAuthorities());
        System.out.println(
                "\tPermission Mask: " + perm.getMask() + " - Permission Pattern: " + perm.getPattern());
        System.out.println("");
    }
}

From source file:org.dspace.rest.Resource.java

/**
 * Create context to work with DSpace database. It can create context
 * with or without a logged in user (retrieved from SecurityContextHolder). Throws
 * WebApplicationException caused by: SQLException if there was a problem
 * with reading from database. Throws AuthorizeException if there was
 * a problem with authorization to read from the database. Throws Exception
 * if there was a problem creating context.
 * //from w w w .j av  a 2 s. c om
 * @return Newly created context with the logged in user unless the specified user was null.
 *     If user is null, create the context without a logged in user.
 * @throws ContextException
 *     Thrown in case of a problem creating context. Can be caused by
 *     SQLException error in creating context or finding the user to
 *     log in. Can be caused by AuthorizeException if there was a
 *     problem authorizing the found user.
 * @throws SQLException
 *     An exception that provides information on a database access error or other errors.
 */
protected static org.dspace.core.Context createContext() throws ContextException, SQLException {
    org.dspace.core.Context context = new org.dspace.core.Context();
    //context.getDBConnection().setAutoCommit(false); // Disable autocommit.

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        Collection<SimpleGrantedAuthority> specialGroups = (Collection<SimpleGrantedAuthority>) authentication
                .getAuthorities();
        for (SimpleGrantedAuthority grantedAuthority : specialGroups) {
            context.setSpecialGroup(EPersonServiceFactory.getInstance().getGroupService()
                    .findByName(context, grantedAuthority.getAuthority()).getID());
        }
        context.setCurrentUser(EPersonServiceFactory.getInstance().getEPersonService().findByEmail(context,
                authentication.getName()));
    }

    return context;
}

From source file:org.encuestame.core.security.EnMeRoleVoter.java

/**
 *
 *///w ww  . j  a va 2s.  c  om
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int result = ACCESS_GRANTED;
    final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    log.debug("Authoritiez size " + authorities.size());
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            result = ACCESS_DENIED;
            // Attempt to find a matching granted authority
            log.debug("Attribute" + attribute.getAttribute());
            for (GrantedAuthority authority : authorities) {
                log.debug("authority.getAuthority())" + authority.getAuthority());
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    return ACCESS_GRANTED;
                }
            }
        }
    }
    log.debug("Result " + result);
    return result;
}

From source file:org.encuestame.core.security.web.SecurityUtils.java

/**
 * Check is Session is Expired./*from  w  w  w.j  a v  a2s .  c o m*/
 * Iterate the existing permission stored in the {@link Authentication} and check if at least
 * the ENCUESTAME_USER exist and return true if this condition exist.
 * @param authentication
 * @return
 */
public static boolean checkIsSessionIsExpired(final Authentication authentication) {
    boolean session = true;
    if (authentication != null) {
        session = authentication.isAuthenticated();
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            SimpleGrantedAuthority auth = (SimpleGrantedAuthority) authority;
            if (auth.getAuthority().equals(EnMePermission.ENCUESTAME_USER.toString())) {
                session = false;
                break;
            }
        }
    }
    log.trace("checkIsSessionIsExpired->" + session);
    return session;
}

From source file:org.encuestame.mvc.interceptor.SignInInterceptor.java

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    String context = arg0.getContextPath();
    StringBuilder path = new StringBuilder(context);
    path.append(PathUtil.signIn);//w  ww.j av a  2 s . com
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    log.trace("Sign In Auth:{ " + authentication);
    if (arg0.getRequestURI().equals(path.toString())) {
        log.debug("Sign In are equals:{ " + arg0.getRequestURI());
        if (authentication != null) {
            if (!SecurityUtils.checkIsSessionIsAnonymousUser(authentication)) {
                log.debug("Sign In session is valid");
                for (GrantedAuthority auth : authentication.getAuthorities()) {
                    log.debug("Sign In Auth:{ " + auth.getAuthority());
                    if (EnumerationUtils.getEnumFromString(EnMePermission.class, auth.getAuthority())
                            .equals(EnMePermission.ENCUESTAME_USER)) {
                        log.debug("User is logged, redirec to dashboard");
                        arg1.sendRedirect(arg0.getContextPath() + "/user/dashboard");
                        break;
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.esupportail.pay.web.admin.PayEvtController.java

@RequestMapping(produces = "text/html")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER') or hasRole('ROLE_VIEWER')")
public String list(@RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size,
        @RequestParam(value = "sortFieldName", required = false) String sortFieldName,
        @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    boolean isAdmin = auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
    boolean isManagerOrViewer = auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_MANAGER"))
            || auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_VIEWER"));

    if (sortFieldName == null) {
        sortFieldName = "id";
        sortOrder = "desc";
    }//from www .  ja  v a2s.  c om

    if (isAdmin) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("payevts",
                    PayEvt.findPayEvtEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) PayEvt.countPayEvts() / sizeNo;
            uiModel.addAttribute("maxPages",
                    (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("payevts", PayEvt.findAllPayEvts(sortFieldName, sortOrder));
        }
    } else if (isManagerOrViewer) {
        RespLogin respLogin = RespLogin.findOrCreateRespLogin(auth.getName());
        List<RespLogin> loginList = Arrays.asList(new RespLogin[] { respLogin });
        uiModel.addAttribute("payevts", PayEvt
                .findPayEvtsByRespLoginsOrByViewerLogins(loginList, sortFieldName, sortOrder).getResultList());
    }

    return "admin/evts/list";
}

From source file:org.esupportail.pay.web.anonyme.PayController.java

@RequestMapping("/")
public String index(Model uiModel) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth.isAuthenticated() && (auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))
            || auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_MANAGER"))
            || auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_VIEWER")))) {
        return "redirect:/admin";
    }/*from w  w w  .j  a  v a  2 s. c  o  m*/

    return "index";
}

From source file:org.georchestra.console.ws.backoffice.log.LogController.java

/**
 * Returns array of logs using json syntax.
 * <pre>/*from   w ww. j a  va 2  s.  c o m*/
 *     {"logs": [
 *      {
 *         "admin": "testadmin",
  *         "date": "2016-03-22T15:26:21.087+0100",
 *         "target": "testeditor",
 *         "type": "Email sent"
 *      },
 *      {
 *         "admin": "testadmin",
 *         "date": "2016-03-21T17:50:09.258+0100",
 *         "target": "joe",
 *         "type": "Email sent"
 *      },
 *      {
 *         "admin": "testadmin",
 *         "date": "2016-03-21T17:50:09.258+0100",
 *         "target": "marie",
 *         "type": "Email sent"
 *      }
 *   ]}
 * </pre>
 *
 */
@RequestMapping(value = REQUEST_MAPPING
        + "/{target}/{limit}/{page}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@ResponseBody
public List<AdminLogEntry> find(@PathVariable String target, @PathVariable int limit, @PathVariable int page) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    // Filter logs by orgs users if user is not SUPERUSER
    if (!auth.getAuthorities().contains(ROLE_SUPERUSER)) {
        List<String> users = new ArrayList<String>();
        DelegationEntry delegation = this.delegationDao.findOne(auth.getName());
        String[] orgs = delegation.getOrgs();
        for (String org : orgs)
            users.addAll(this.orgsDao.findByCommonName(org).getMembers());
        if (!users.contains(target))
            throw new AccessDeniedException("User not under delegation");
    }

    return this.logDao.findByTarget(target,
            new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "date")));
}