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:com.linuxbox.enkive.permissions.SpringContextPermissionService.java

/**
 * If the security principal is an EnkiveUserDetails, can test directly if
 * user is an enkive admin. Otherwise we have to search through the granted
 * authorities one by one.// w w  w .java2s  .  c  o m
 */
public boolean isAdmin() throws CannotGetPermissionsException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    final Object detailsObj = authentication.getPrincipal();
    if (detailsObj instanceof EnkiveUserDetails) {
        final boolean isAdmin = ((EnkiveUserDetails) detailsObj).isEnkiveAdmin();
        return isAdmin;
    }

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

    return false;
}

From source file:com.amediamanager.controller.UserController.java

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String userPost(@ModelAttribute User user, BindingResult result, RedirectAttributes attr,
        HttpSession session) {/*w  w w .  j  a  va2  s  .  c  o  m*/
    // Don't allow user name changes
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    user.setId(auth.getName());
    user.setEmail(auth.getName());

    // Update user and re-set val in session
    userService.update(user);

    // Update user auth object in security context
    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(auth.getName(), null,
            auth.getAuthorities());
    newAuth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(newAuth);

    return "redirect:/user";
}

From source file:org.openinfinity.sso.identityprovisioning.bpmn.ProcessEngineBridgeImpl.java

public Collection<org.openinfinity.sso.identityprovisioning.bpmn.Task> queryForTasksByUserRoles() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    IdentityService identityService = processEngine.getIdentityService();
    identityService.setAuthenticatedUserId(authentication.getName());
    TaskService taskService = processEngine.getTaskService();
    Collection<? extends GrantedAuthority> grantedAuthorities = authentication.getAuthorities();
    List<String> candidateGroups = new ArrayList<String>();
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        if (grantedAuthority.getAuthority() != null)
            candidateGroups.add(grantedAuthority.getAuthority());
    }// w w w  .j a va 2s.  c om
    List<Task> tasks = taskService.createTaskQuery().taskCandidateGroupIn(candidateGroups).list();
    Collection<org.openinfinity.sso.identityprovisioning.bpmn.Task> simpleTasks = mapTasks(tasks);
    return Collections.unmodifiableCollection(simpleTasks);
}

From source file:com.qpark.eip.core.spring.security.EipRoleVoter.java

public String getGrantedRoles(final Authentication authentication) {
    TreeSet<String> ts = new TreeSet<String>();
    StringBuffer sb = new StringBuffer(1024);
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority authority : authorities) {
        ts.add(authority.getAuthority());
    }//from   w  w w .j a  v a 2  s .co m
    for (String string : ts) {
        if (sb.length() > 0) {
            sb.append(", ");
        }
        sb.append(string);
    }

    return sb.toString();
}

From source file:net.ljcomputing.ecsr.security.service.impl.JwtTokenServiceImpl.java

/**
 * @see net.ljcomputing.ecsr.security.service.impl.JwtTokenService
 *    #create(org.springframework.security.core.Authentication)
 *///from www.j a  v a2 s  .  co m
@Override
public String create(final Authentication authentication) {
    if (authentication == null) {
        LOGGER.error("NO TOKEN");
        throw new BadCredentialsException("No authentication provided.");
    }

    final String authorities = authentication.getAuthorities().stream() // NOPMD
            .map(authority -> authority.getAuthority()).collect(Collectors.joining(","));

    final String result = Jwts.builder() // NOPMD
            .setSubject(authentication.getName()).setIssuer(tokenIssuer).setIssuedAt(now())
            .setExpiration(expirationDate()).claim(WebSecurityConfiguration.AUTHORITIES_KEY, authorities)
            .signWith(SignatureAlgorithm.HS512, tokenSigningKey).compact();

    if (!isValid(result)) {
        throw new BadCredentialsException("Token is invalid");
    }

    return result;
}

From source file:de.blizzy.documentr.access.DocumentrPermissionEvaluator.java

public boolean hasBranchPermission(Authentication authentication, String projectName, String branchName,
        Permission permission) {/*from w w w .  j  av a 2s .c  o  m*/

    String targetId = projectName + "/" + branchName; //$NON-NLS-1$
    for (GrantedAuthority authority : authentication.getAuthorities()) {
        if (authority instanceof PermissionGrantedAuthority) {
            PermissionGrantedAuthority pga = (PermissionGrantedAuthority) authority;
            GrantedAuthorityTarget target = pga.getTarget();
            Type type = target.getType();
            String id = target.getTargetId();
            if ((type == Type.BRANCH) && id.equals(targetId) && hasPermission(pga, permission)) {

                return true;
            }
        }
    }
    return hasProjectPermission(authentication, projectName, permission);
}

From source file:org.geonode.security.GeoNodeAnonymousProcessingFilter.java

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

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final boolean authenticationRequired = existingAuth == null || !existingAuth.isAuthenticated();

    if (authenticationRequired) {
        try {/*from   www. j a v a 2  s  .  co m*/
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new AnonymousGeoNodeAuthenticationToken(principal, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            securityContext.setAuthentication(authResult);
            LOGGER.finer("GeoNode Anonymous filter kicked in.");
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java

private Set<String> getGrantedAuthorities(Authentication authentication) {
    final Set<String> grantedAuthorities = Sets.newHashSet();
    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        grantedAuthorities.add(grantedAuthority.getAuthority());
    }//ww w  .java2s . co  m

    return grantedAuthorities;
}

From source file:org.geonode.security.DatabaseSecurityClientTest.java

@Test
public void testAuthenticateUserPassword() throws Exception {
    String username = "aang";
    String password = "katara";
    final String[] requestHeaders = { "Authorization",
            "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes())) };

    final String response = "{\"superuser\": true, \"user\": \"aang\", \"geoserver\": \"false\"}";

    EasyMock.expect(mockHttpClient.sendGET(EasyMock.eq("http://localhost:8000/layers/resolve_user"),
            EasyMock.aryEq(requestHeaders))).andReturn(response);
    EasyMock.replay(mockHttpClient);//from w ww  . j a  v a2  s .  c o m

    Authentication authentication = client.authenticateUserPwd(username, password);
    EasyMock.verify(mockHttpClient);

    assertNotNull(authentication);
    assertTrue(authentication instanceof UsernamePasswordAuthenticationToken);
    assertTrue(authentication.isAuthenticated());
    assertEquals("aang", ((UserDetails) authentication.getPrincipal()).getUsername());

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.addAll(authentication.getAuthorities());
    assertTrue(authorities.contains(GeoServerRole.ADMIN_ROLE));
    assertTrue(authorities.contains(GeoServerRole.AUTHENTICATED_ROLE));
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Entry point for resource access authorization request. Redirects to the
 * login page. In addition to standard OAuth parameters, it is possible to
 * specify a comma-separated list of authorities to be used for login as
 * 'authorities' parameter/*ww w . j a  v  a  2s .  com*/
 * 
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/authorize")
public ModelAndView authorise(Device device, HttpServletRequest req,
        @RequestParam(value = "authorities", required = false) String loginAuthorities) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    String clientId = req.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(req, device, client.getScope(), client.getDisplayName());
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.getAuthorities() != null
            && auth.getAuthorities().stream()
                    .anyMatch(a -> a.getAuthority().equals(AUTHORITY.ROLE_USER.toString()))
            && req.getSession().getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST) != null) {
        AACOAuthRequest old = (AACOAuthRequest) req.getSession()
                .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
        oauthRequest.setAuthority(old.getAuthority());
        // update existing session data
        AbstractAuthenticationToken a = new AACAuthenticationToken(auth.getPrincipal(), null,
                oauthRequest.getAuthority(), auth.getAuthorities());
        a.setDetails(oauthRequest);
        SecurityContextHolder.getContext().setAuthentication(a);
    }
    if (StringUtils.isEmpty(oauthRequest.getAuthority()) && loginAuthorities != null) {
        oauthRequest.setAuthority(loginAuthorities.split(",")[0].trim());
    }
    req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);

    String target = prepareRedirect(req, "/eauth/pre-authorize");
    return new ModelAndView("redirect:" + target);
}