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.georchestra.console.ws.backoffice.log.LogController.java

@RequestMapping(value = REQUEST_MAPPING
        + "/{limit}/{page}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@ResponseBody/*from  ww w  .  ja v  a  2s .  c  o m*/
public List<AdminLogEntry> find(HttpServletRequest request, @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)) {
        Set<String> users = this.advancedDelegationDao.findUsersUnderDelegation(auth.getName());
        return this.logDao.myFindByTargets(users,
                new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "date")));
    } else {
        return this.logDao.findAll(new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "date")))
                .getContent();
    }

}

From source file:org.georchestra.console.ws.backoffice.roles.RolesController.java

/**
 * Returns the detailed information of the role, with its list of users.
 *
 * <p>//from w ww.  ja va2  s.c o  m
 * If the role identifier is not present in the ldap store an {@link IOException} will be throw.
 * </p>
 * <p>
 * URL Format: [BASE_MAPPING]/roles/{cn}
 * </p>
 * <p>
 * Example: [BASE_MAPPING]/roles/role44
 * </p>
 *
 * @param cn Comon name of role
 * @throws IOException
 */
@RequestMapping(value = REQUEST_MAPPING
        + "/{cn:.+}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@ResponseBody
public Role findByCN(@PathVariable String cn) throws DataServiceException {
    Role res;

    if (cn.equals(RolesController.VIRTUAL_TEMPORARY_ROLE_NAME))
        res = this.generateTemporaryRole();
    else
        res = this.roleDao.findByCommonName(cn);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.getAuthorities().contains(ROLE_SUPERUSER)) {
        if (!Arrays.asList(this.delegationDao.findOne(auth.getName()).getRoles()).contains(cn))
            throw new AccessDeniedException("Role not under delegation");
        res.getUserList().retainAll(this.advancedDelegationDao.findUsersUnderDelegation(auth.getName()));
    }
    return res;
}

From source file:org.georchestra.console.ws.backoffice.roles.RolesController.java

/**
 * Updates the users of role. This method will add or delete the role of users from the list of roles.
 *
 * @param request   request [BASE_MAPPING]/roles_users body request {"users": [u1,u2,u3], "PUT": [g1,g2], "DELETE":[g3,g4] }
 * @param response//from   w w  w  .j  a  v  a  2  s .c  om
 * @throws IOException
 */
@RequestMapping(value = BASE_MAPPING + "/roles_users", method = RequestMethod.POST)
public void updateUsers(HttpServletRequest request, HttpServletResponse response)
        throws AccessDeniedException, IOException, JSONException, DataServiceException {

    JSONObject json = new JSONObject(FileUtils.asString(request.getInputStream()));

    List<String> users = createUserList(json, "users");
    List<String> putRole = createUserList(json, "PUT");
    List<String> deleteRole = createUserList(json, "DELETE");

    // Don't allow modification of ORGADMIN role
    if (putRole.contains("ORGADMIN") || deleteRole.contains("ORGADMIN"))
        throw new IllegalArgumentException("ORGADMIN role cannot be add or delete");

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_SUPERUSER")))
        this.checkAuthorization(auth.getName(), users, putRole, deleteRole);

    this.roleDao.addUsersInRoles(putRole, users, auth.getName());
    this.roleDao.deleteUsersInRoles(deleteRole, users, auth.getName());

    ResponseUtil.writeSuccess(response);
}

From source file:org.georchestra.console.ws.backoffice.users.UsersController.java

/**
 * <p>//from ww w .ja v  a 2s  . c o  m
 * Creates a new user.
 * </p>
 *
 * <pre>
 * <b>Request</b>
 *
 * user data:
 * {
  *  "sn": "surname",
  *   "givenName": "first name",
  *   "mail": "e-mail",
  *    "telephoneNumber": "telephone"
  *   "facsimileTelephoneNumber": "value",
  *    "street": "street",
  *    "postalCode": "postal code",
  *   "l": "locality",
  *    "postOfficeBox": "the post office box",
  *  "org": "the_organization"
  * }
  *
  * where <b>sn, givenName, mail</b> are mandatories
 * </pre>
 * <pre>
 * <b>Response</b>
 *
 * <b>- Success case</b>
 *
 * The generated uid is added to the user data. So, a succeeded response should look like:
 * {
 *    <b>"uid": generated uid</b>
 *
  *  "sn": "surname",
  *   "givenName": "first name",
  *   "mail": "e-mail",
  *    "telephoneNumber": "telephone"
  *   "facsimileTelephoneNumber": "value",
  *    "street": "street",
  *    "postalCode": "postal code",
  *   "l": "locality",
  *    "postOfficeBox": "the post office box"
  * }
 * </pre>
 *
 * <pre>
 * <b>- Error case</b>
 * If the provided e-mail exists in the LDAP store the response will contain:
 *
 *    { \"success\": false, \"error\": \"duplicated_email\"}
 *
 * Error: 409 conflict with the current state of resource
 *
 * </pre>
 *
 * @param request HTTP POST data contains the user data
 * @throws IOException
 */
@RequestMapping(value = REQUEST_MAPPING, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public Account create(HttpServletRequest request)
        throws IOException, DuplicatedEmailException, DataServiceException, DuplicatedUidException {

    Account account = createAccountFromRequestBody(request.getInputStream());
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    // Verify that org is under delegation if user is not SUPERUSER
    if (!auth.getAuthorities().contains(this.advancedDelegationDao.ROLE_SUPERUSER)) {
        DelegationEntry delegation = this.delegationDao.findOne(auth.getName());
        if (!Arrays.asList(delegation.getOrgs()).contains(account.getOrg()))
            throw new AccessDeniedException("Org not under delegation");
    }

    if (this.userRule.isProtected(account.getUid()))
        throw new AccessDeniedException("The user is protected: " + account.getUid());

    // Saves the user in the LDAP
    this.accountDao.insert(account, Role.USER, auth.getName());

    return account;
}

From source file:org.georchestra.console.ws.backoffice.users.UsersController.java

/**
 * Modifies the user data using the fields provided in the request body.
 * <p>//from w  w  w.j a  v  a2  s.  c o m
 * The fields that are not present in the parameters will remain untouched in the LDAP store.
 * </p>
 * <p>
 * The request format is:
 * [BASE_MAPPING]/users/{uid}
 * </p>
 * <p>
 * The request body should contains a the fields to modify using the JSON syntax.
 * </p>
 * <p>
 * Example:
 * </p>
 * <pre>
 * <b>Request</b>
 * [BASE_MAPPING]/users/hsimpson
 *
 * <b>Body request: </b>
 * {"sn": "surname",
 *  "givenName": "first name",
 *  "mail": "e-mail",
 *  "telephoneNumber": "telephone",
 *  "facsimileTelephoneNumber": "value",
  *    "street": "street",
  *  "postalCode": "postal code",
  *  "l": "locality",
  *  "postOfficeBox": "the post office box"
  * }
 *
 * </pre>
 * @param request
 *
 * @throws IOException if the uid does not exist or fails to access to the LDAP store.
 * @throws NameNotFoundException
 */
@RequestMapping(value = REQUEST_MAPPING
        + "/{uid:.+}", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
@ResponseBody
public Account update(@PathVariable String uid, HttpServletRequest request) throws IOException,
        NameNotFoundException, DataServiceException, DuplicatedEmailException, ParseException, JSONException {

    if (this.userRule.isProtected(uid))
        throw new AccessDeniedException("The user is protected, it cannot be updated: " + uid);

    // check if user is under delegation for delegated admins
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    this.checkAuthorization(uid);

    // searches the account
    Account account = this.accountDao.findByUID(uid);
    String originalOrg = account.getOrg();

    // modifies the account data
    final Account modified = modifyAccount(AccountFactory.create(account), request.getInputStream());

    if (!modified.getOrg().equals(originalOrg)) {
        if (!auth.getAuthorities().contains(ROLE_SUPERUSER))
            if (!Arrays.asList(this.delegationDao.findOne(auth.getName()).getOrgs())
                    .contains(modified.getOrg()))
                throw new AccessDeniedException("User not under delegation");
        if (originalOrg.length() > 0)
            this.orgDao.removeUser(originalOrg, uid);
        if (modified.getOrg().length() > 0)
            this.orgDao.addUser(modified.getOrg(), uid);
    }

    // Finally store account in LDAP
    this.accountDao.update(account, modified, auth.getName());

    boolean uidChanged = (!modified.getUid().equals(account.getUid()));
    if ((uidChanged) && (warnUserIfUidModified)) {
        this.mailService.sendAccountUidRenamed(request.getSession().getServletContext(), modified.getUid(),
                modified.getCommonName(), modified.getEmail());
    }
    return modified;
}

From source file:org.georchestra.console.ws.backoffice.users.UsersController.java

/**
 * Check Authorization of current logged user against specified uid and throw a AccessDeniedException
 * if current user is not SUPERUSER and user 'uid' is not under the delegation.
 * @param uid Identifier of user to search in delegation of connected user
 *
 * @throws AccessDeniedException if current user does not have permission to edit user 'uid'
 *///from  w  ww  . j av a2 s. c  o  m
private void checkAuthorization(String uid) {
    // check if user is under delegation for delegated admins
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.getAuthorities().contains(this.advancedDelegationDao.ROLE_SUPERUSER))
        if (!this.advancedDelegationDao.findUsersUnderDelegation(auth.getName()).contains(uid))
            throw new AccessDeniedException("User " + uid + " not under delegation");
}

From source file:org.georchestra.console.ws.backoffice.users.UsersExport.java

/**
 * Parse JSON string and check that connected user has permissions to view data on requested users
 *
 * @param rawUsers JSON string to parse/*from ww w  . j a  v  a2 s . c  om*/
 * @return Parsed user list
 * @throws AccessDeniedException if current user does not have permissions to view data of all requested users
 */
private Set<String> parseRequest(String rawUsers) throws JSONException {
    JSONArray jsonUsers = new JSONArray(rawUsers);
    Set<String> users = new HashSet<>();
    for (int i = 0; i < jsonUsers.length(); i++)
        users.add(jsonUsers.getString(i));

    // check if user is under delegation for delegated admins
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.getAuthorities().contains(this.advancedDelegationDao.ROLE_SUPERUSER))
        if (!this.advancedDelegationDao.findUsersUnderDelegation(auth.getName()).containsAll(users))
            throw new AccessDeniedException("Some user not under delegation");
    return users;
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Check if recipient is under delegation for delegated admins
 *
 * @param recipient/*from   w  w  w .  java  2 s. c  o m*/
 * @throws AccessDeniedException if current does not have permissions on recipient
 */
private void checkAuthorisation(String recipient) {
    // check if recipient is under delegation for delegated admins
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!auth.getAuthorities().contains(this.advancedDelegationDao.ROLE_SUPERUSER))
        if (!this.advancedDelegationDao.findUsersUnderDelegation(auth.getName()).contains(recipient))
            throw new AccessDeniedException("User " + recipient + " not under delegation");
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * Checks if the specified authentication contains the specified role.
 * //from   w w w  .j  av  a 2s  .com
 * If the current {@link HttpServletRequest} has security disabled,
 * this method always returns <code>true</code>.
 * 
 * @return <code>true</code> if the authenticated contains the role, otherwise <code>false</false>
 */
public boolean checkAuthenticationForRole(Authentication auth, GeoServerRole role) {

    if (GeoServerSecurityFilterChainProxy.isSecurityEnabledForCurrentRequest() == false)
        return true; // No security means any role is granted

    if (auth == null || !auth.isAuthenticated()) {
        return false;
    }
    for (GrantedAuthority authority : auth.getAuthorities()) {
        if (role.getAuthority().equals(authority.getAuthority())) {
            return true;
        }
    }
    return false;
}

From source file:org.jamwiki.authentication.JAMWikiPostAuthenticationFilter.java

/**
 *
 *//*  w  w w. j a va  2s .  co  m*/
private void handleAnonymousUser(Authentication auth) {
    if (!this.getUseJAMWikiAnonymousRoles()) {
        // the configuration file indicates that JAMWiki anonymous roles should not be 
        // used, so assume that an external system is providing this information.
        return;
    }
    // get arrays of existing Spring Security roles and JAMWiki anonymous user roles
    Collection<GrantedAuthority> springSecurityAnonymousAuthorities = auth.getAuthorities();
    Collection<GrantedAuthority> jamwikiAnonymousAuthorities = JAMWikiAuthenticationConfiguration
            .getJamwikiAnonymousAuthorities();
    if (springSecurityAnonymousAuthorities == null || jamwikiAnonymousAuthorities == null) {
        return;
    }
    List<GrantedAuthority> anonymousAuthorities = new ArrayList<GrantedAuthority>();
    anonymousAuthorities.addAll(springSecurityAnonymousAuthorities);
    anonymousAuthorities.addAll(jamwikiAnonymousAuthorities);
    // replace the existing anonymous authentication object with the new authentication array
    AnonymousAuthenticationToken jamwikiAuth = new AnonymousAuthenticationToken(this.getKey(),
            auth.getPrincipal(), anonymousAuthorities);
    jamwikiAuth.setDetails(auth.getDetails());
    jamwikiAuth.setAuthenticated(auth.isAuthenticated());
    SecurityContextHolder.getContext().setAuthentication(jamwikiAuth);
}