Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getAuthorities

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getAuthorities.

Prototype

public Collection<GrantedAuthority> getAuthorities() 

Source Link

Usage

From source file:com.hp.autonomy.frontend.find.idol.test.IdolMvcIntegrationTestUtils.java

@Override
protected Authentication createAuthentication(final Collection<GrantedAuthority> authorities) {
    final CommunityPrincipal communityPrincipal = mock(CommunityPrincipal.class);
    when(communityPrincipal.getId()).thenReturn(1L);
    when(communityPrincipal.getUsername()).thenReturn("user");

    final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class);
    when(authentication.isAuthenticated()).thenReturn(true);
    when(authentication.getPrincipal()).thenReturn(communityPrincipal);
    when(authentication.getAuthorities()).thenReturn(authorities);

    return authentication;
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "\"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": true, \"details\": null, "
            + "\"authorities\" : [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();//from w ww.  j a  v a 2  s .  c  o  m
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest()
        throws IOException, JSONException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + " \"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": false, \"details\": null, "
            + "\"authorities\": [\"java.util.ArrayList\", []], \"name\": \"user1\"}";
    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();//from w ww  .  j  a  v  a  2s  .  com
    assertThat(token.isAuthenticated()).isEqualTo(false);
    assertThat(token.getAuthorities()).isNotNull().hasSize(0);
}

From source file:org.mule.modules.basicauthsecurity.strategy.JDBCSecurityProvider.java

public void validate(String auth, List<String> acceptedRoles) throws UnauthorizedException {
    List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    for (String role : acceptedRoles) {
        list.add(new SimpleGrantedAuthority(role));
    }//from   w  w  w . j  a v  a 2  s.  c om
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(getUser(auth),
            getPass(auth), list);
    Authentication authResult = providerManager.authenticate(authRequest);

    Boolean containsKey = false;
    for (GrantedAuthority grantedAuthority : authResult.getAuthorities()) {
        if (authRequest.getAuthorities().contains(grantedAuthority)) {
            containsKey = true;
        }
    }

    if (!containsKey) {
        throw new UnauthorizedException("result");
    }
    if (!authResult.isAuthenticated()) {
        throw new UnauthorizedException("result");
    }
}

From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class })
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    boolean authenticated;
    SyncopeUser passwordUser = new SyncopeUser();
    SyncopeUser user = null;//from  w  w w .jav  a2 s  . c om

    if (adminUser.equals(authentication.getPrincipal())) {
        passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0);

        authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword());
    } else {
        String username;
        try {
            username = authentication.getPrincipal().toString();
        } catch (NumberFormatException e) {
            throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e);
        }

        user = userDAO.find(username);
        if (user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }

        passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0);

        authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword());
    }

    Authentication result;

    if ((user == null || !user.getSuspended()) && authenticated) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), null, userDetailsService
                        .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());
        token.setDetails(authentication.getDetails());

        result = token;

        LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities());

        if (user != null) {
            user.setLastLoginDate(new Date());
            user.setFailedLogins(0);
            userDAO.save(user);
        }

    } else {
        result = authentication;

        if (user != null && !user.getSuspended()) {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userDAO.save(user);
        }

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return result;
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": true, \"enabled\": true, "
            + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\","
            + "[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"credentials\": \"pass\","
            + "\"details\": null, \"name\": \"user\", \"authenticated\": true,"
            + "\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    ObjectMapper mapper = buildObjectMapper();
    UsernamePasswordAuthenticationToken token = mapper.readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();//w  w w . j a va 2s  .  c om
    assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
    assertThat(((User) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1)
            .contains(new SimpleGrantedAuthority("ROLE_USER"));
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithCustomUserTest()
        throws Exception {
    String tokenJson = "{"
            + "  \"@class\" : \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "  \"details\" : null," + "  \"authorities\" : [ \"java.util.ArrayList\", [ {"
            + "    \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\","
            + "    \"role\" : \"ROLE_USER\"" + "  } ] ]," + "  \"authenticated\" : true,"
            + "  \"principal\" : {"
            + "    \"@class\" : \"org.springframework.security.jackson2.CustomUserForTest\","
            + "    \"username\" : \"user\"," + "    \"password\" : \"pass\","
            + "    \"customProperty\" : \"custom\"," + "    \"authorities\" : [ \"java.util.ArrayList\", [ {"
            + "      \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\","
            + "      \"role\" : \"ROLE_USER\"" + "    } ] ]," + "    \"accountNonExpired\" : true,"
            + "    \"accountNonLocked\" : true," + "    \"credentialsNonExpired\" : true,"
            + "    \"enabled\" : true" + "  }," + "  \"credentials\" : \"pass\"," + "  \"name\" : \"user\""
            + "}";

    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);

    assertThat(token).isNotNull();//from   w  ww .j  av  a2  s.co  m
    assertThat(token.getPrincipal()).isNotNull().isInstanceOf(CustomUserForTest.class);
    assertThat(((CustomUserForTest) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1)
            .contains(new SimpleGrantedAuthority("ROLE_USER"));
    assertThat(((CustomUserForTest) token.getPrincipal()).getCustomProperty()).isNotNull().isEqualTo("custom");
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.apache.syncope.core.misc.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class, DisabledException.class })
public Authentication authenticate(final Authentication authentication) {
    boolean authenticated = false;
    User user = null;/*ww  w.j  a  v a  2s.c  om*/

    String username = authentication.getName();
    if (anonymousUser.equals(username)) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(username)) {
        authenticated = encryptor.verify(authentication.getCredentials().toString(),
                CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
    } else {
        user = userDAO.find(username);

        if (user != null) {
            if (user.isSuspended() != null && user.isSuspended()) {
                throw new DisabledException("User " + user.getUsername() + " is suspended");
            }

            CPlainAttr authStatuses = confDAO.find("authentication.statuses");
            if (authStatuses != null && !authStatuses.getValuesAsStrings().contains(user.getStatus())) {
                throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
            }

            authenticated = authenticate(user, authentication.getCredentials().toString());

            updateLoginAttributes(user, authenticated);
        }
    }

    UsernamePasswordAuthenticationToken token;
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), null, userDetailsService
                .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());

        token.setDetails(authentication.getDetails());

        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.SUCCESS, null, authenticated, authentication,
                "Successfully authenticated, with groups: " + token.getAuthorities());

        LOG.debug("User {} successfully authenticated, with groups {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.FAILURE, null, authenticated, authentication,
                "User " + authentication.getPrincipal() + " not authenticated");

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}

From source file:org.apache.syncope.core.spring.security.SyncopeAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain();
    if (StringUtils.isBlank(domainKey)) {
        domainKey = SyncopeConstants.MASTER_DOMAIN;
    }//ww w .  ja  v a 2s.c  om
    SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).setDomain(domainKey);

    Boolean authenticated;
    if (anonymousUser.equals(authentication.getName())) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(authentication.getName())) {
        if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) {
            authenticated = encryptor.verify(authentication.getCredentials().toString(),
                    CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
        } else {
            final String domainToFind = domainKey;
            authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN,
                    new Executable<Boolean>() {

                        @Override
                        public Boolean exec() {
                            Domain domain = dataAccessor.findDomain(domainToFind);

                            return encryptor.verify(authentication.getCredentials().toString(),
                                    domain.getAdminCipherAlgorithm(), domain.getAdminPwd());
                        }
                    });
        }
    } else {
        final Pair<String, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<Pair<String, Boolean>>() {

                    @Override
                    public Pair<String, Boolean> exec() {
                        return dataAccessor.authenticate(authentication);
                    }
                });
        authenticated = authResult.getValue();
        if (authenticated != null && !authenticated) {
            AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

                @Override
                public Void exec() {
                    provisioningManager.internalSuspend(authResult.getKey());
                    return null;
                }
            });
        }
    }

    final boolean isAuthenticated = authenticated != null && authenticated;
    UsernamePasswordAuthenticationToken token;
    if (isAuthenticated) {
        token = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<UsernamePasswordAuthenticationToken>() {

                    @Override
                    public UsernamePasswordAuthenticationToken exec() {
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                authentication.getPrincipal(), null,
                                userDetailsService.loadUserByUsername(authentication.getPrincipal().toString())
                                        .getAuthorities());
                        token.setDetails(authentication.getDetails());

                        dataAccessor.audit(AuditElements.EventCategoryType.LOGIC,
                                AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT,
                                Result.SUCCESS, null, isAuthenticated, authentication,
                                "Successfully authenticated, with entitlements: " + token.getAuthorities());
                        return token;
                    }
                });

        LOG.debug("User {} successfully authenticated, with entitlements {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

            @Override
            public Void exec() {
                dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                        null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication,
                        "User " + authentication.getPrincipal() + " not authenticated");
                return null;
            }
        });

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}

From source file:org.apache.syncope.core.spring.security.UsernamePasswordAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain();

    final String[] username = new String[1];
    Boolean authenticated;/*from w  ww .  j a va2s. c o  m*/

    if (anonymousUser.equals(authentication.getName())) {
        username[0] = anonymousUser;
        credentialChecker.checkIsDefaultAnonymousKeyInUse();
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(authentication.getName())) {
        username[0] = adminUser;
        if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) {
            credentialChecker.checkIsDefaultAdminPasswordInUse();
            authenticated = ENCRYPTOR.verify(authentication.getCredentials().toString(),
                    CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
        } else {
            final String domainToFind = domainKey;
            authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN, () -> {
                Domain domain = dataAccessor.findDomain(domainToFind);

                return ENCRYPTOR.verify(authentication.getCredentials().toString(),
                        domain.getAdminCipherAlgorithm(), domain.getAdminPwd());
            });
        }
    } else {
        final Pair<User, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey,
                () -> dataAccessor.authenticate(authentication));
        authenticated = authResult.getValue();
        if (authResult.getLeft() != null && authResult.getRight() != null) {
            username[0] = authResult.getLeft().getUsername();

            if (!authResult.getRight()) {
                AuthContextUtils.execWithAuthContext(domainKey, () -> {
                    provisioningManager.internalSuspend(authResult.getLeft().getKey());
                    return null;
                });
            }
        }
    }
    if (username[0] == null) {
        username[0] = authentication.getPrincipal().toString();
    }

    final boolean isAuthenticated = authenticated != null && authenticated;
    UsernamePasswordAuthenticationToken token;
    if (isAuthenticated) {
        token = AuthContextUtils.execWithAuthContext(domainKey, () -> {
            UsernamePasswordAuthenticationToken token1 = new UsernamePasswordAuthenticationToken(username[0],
                    null, dataAccessor.getAuthorities(username[0]));
            token1.setDetails(authentication.getDetails());
            dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                    null, AuditElements.LOGIN_EVENT, Result.SUCCESS, null, isAuthenticated, authentication,
                    "Successfully authenticated, with entitlements: " + token1.getAuthorities());
            return token1;
        });

        LOG.debug("User {} successfully authenticated, with entitlements {}", username[0],
                token.getAuthorities());
    } else {
        AuthContextUtils.execWithAuthContext(domainKey, () -> {
            dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                    null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication,
                    "User " + username[0] + " not authenticated");
            return null;
        });

        LOG.debug("User {} not authenticated", username[0]);

        throw new BadCredentialsException("User " + username[0] + " not authenticated");
    }

    return token;
}