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.openlmis.fulfillment.security.CustomUserAuthenticationConverterTest.java

@Test
public void shouldExtractAuthenticationWithPrincipalWithoutAuthorities() {
    Authentication authentication = userAuthenticationConverter
            .extractAuthentication(ImmutableMap.of(REFERENCE_DATA_USER_ID, userId.toString()));

    checkAuthentication(userId, authentication);
    assertTrue(authentication.getAuthorities().isEmpty());
}

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;//from w w  w.  java  2  s. c  om
        }
    }
    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:org.taverna.server.master.worker.PolicyImpl.java

private boolean isSelfAccess(String runId) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean self = false;
    String id = null;//  www . jav a  2 s  . c  o  m
    for (GrantedAuthority a : auth.getAuthorities()) {
        String aa = a.getAuthority();
        if (aa.equals(Roles.SELF)) {
            self = true;
            continue;
        }
        if (!aa.startsWith(PREFIX))
            continue;
        id = aa.substring(PREFIX.length());
    }
    return self && runId.equals(id);
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFactory.java

private Collection<? extends GrantedAuthority> addAuthority(Authentication authentication,
        GrantedAuthority newAuthority) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.addAll(authentication.getAuthorities());
    if (newAuthority != null) {
        if (!authorities.contains(newAuthority)) {
            authorities.add(newAuthority);
        }//from   w w  w .  ja  v  a 2  s. c  om
    }

    return authorities;
}

From source file:com.trenako.web.security.SpringSignupServiceTests.java

@Test
public void shouldAuthenticateAccounts() {
    SecurityContext mockContext = mock(SecurityContext.class);

    Account account = buildAccount();/*from w  w w . ja  v  a 2  s  .  c  o  m*/
    AccountDetails accountDetails = new AccountDetails(account);

    // inject the mock security context
    service.setSecurityContext(mockContext);
    service.authenticate(account);

    ArgumentCaptor<Authentication> arg = ArgumentCaptor.forClass(Authentication.class);
    verify(mockContext, times(1)).setAuthentication(arg.capture());
    Authentication auth = arg.getValue();
    assertEquals("pa$$word", auth.getCredentials());
    assertEquals(accountDetails, auth.getPrincipal());
    assertEquals(account.getRoles().toString(), auth.getAuthorities().toString());
}

From source file:waffle.spring.DelegatingNegotiateSecurityFilterTest.java

/**
 * Test the delegating filter ,in case no custom authentication was passed, the filter would store the auth in the
 * security context.//from   w  w  w.  j a va2s.c o  m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Test
public void testNegotiate() throws IOException, ServletException {
    final String securityPackage = "Negotiate";
    final SimpleFilterChain filterChain = new SimpleFilterChain();
    final SimpleHttpRequest request = new SimpleHttpRequest();

    final String clientToken = Base64.getEncoder()
            .encodeToString(WindowsAccountImpl.getCurrentUsername().getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", securityPackage + " " + clientToken);

    final SimpleHttpResponse response = new SimpleHttpResponse();
    this.filter.doFilter(request, response, filterChain);

    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Assertions.assertNotNull(auth);
    final Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    Assertions.assertNotNull(authorities);
    Assertions.assertEquals(3, authorities.size());

    final List<String> list = new ArrayList<>();
    for (final GrantedAuthority grantedAuthority : authorities) {
        list.add(grantedAuthority.getAuthority());
    }
    Collections.sort(list);
    Assertions.assertEquals("ROLE_EVERYONE", list.get(0));
    Assertions.assertEquals("ROLE_USER", list.get(1));
    Assertions.assertEquals("ROLE_USERS", list.get(2));
    Assertions.assertEquals(0, response.getHeaderNamesSize());
}

From source file:org.socialsignin.exfmproxy.mvc.workaround.auth.WorkaroundUsernamePasswordAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    Authentication a = super.attemptAuthentication(request, response);
    String[] usernameAndPassword = ((User) a.getPrincipal()).getUsername().split(USERNAME_PASSWORD_DELIMITER);
    User user = new User(usernameAndPassword[0], usernameAndPassword[1], a.getAuthorities());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
            usernameAndPassword[1], a.getAuthorities());
    setDetails(request, authentication);
    return authentication;

}

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  .  ja  v a2s.c o 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: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//from   ww w  .ja va 2 s  .c  o m
 * @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() + "'");
            }
        }
    }
}

From source file:architecture.user.security.authentication.impl.DefaultAuthenticationProvider.java

private boolean isGranted(String role) {

    Authentication auth = getAuthentication();
    if ((auth == null) || (auth.getPrincipal() == null)) {
        return false;
    }/*w  w  w  . j  av a  2 s  .c  o m*/
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    if (authorities == null) {
        return false;
    }
    for (GrantedAuthority grantedAuthority : authorities) {
        if (role.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }
    return false;
}