Example usage for org.springframework.security.core Authentication getCredentials

List of usage examples for org.springframework.security.core Authentication getCredentials

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getCredentials.

Prototype

Object getCredentials();

Source Link

Document

The credentials that prove the principal is correct.

Usage

From source file:org.apache.atlas.web.security.AtlasLdapAuthenticationProvider.java

private Authentication getLdapAuthentication(Authentication authentication) {

    if (isDebugEnabled) {
        LOG.debug("==> AtlasLdapAuthenticationProvider getLdapAuthentication");
    }/*from w ww. ja  va 2 s.  co m*/

    try {
        // taking the user-name and password from the authentication
        // object.
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        // populating LDAP context source with LDAP URL and user-DN-pattern
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapURL);

        ldapContextSource.setCacheEnvironmentProperties(false);
        ldapContextSource.setAnonymousReadOnly(true);

        // Creating BindAuthenticator using Ldap Context Source.
        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern };
        String[] userDnPatterns = ldapUserDNPattern.split(";");
        bindAuthenticator.setUserDnPatterns(userDnPatterns);

        LdapAuthenticationProvider ldapAuthenticationProvider = null;

        if (!StringUtils.isEmpty(ldapGroupSearchBase) && !StringUtils.isEmpty(ldapGroupSearchFilter)) {
            // Creating LDAP authorities populator using Ldap context source and
            // Ldap group search base.
            // populating LDAP authorities populator with group search
            // base,group role attribute, group search filter.
            DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
                    ldapContextSource, ldapGroupSearchBase);
            defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(ldapGroupRoleAttribute);
            defaultLdapAuthoritiesPopulator.setGroupSearchFilter(ldapGroupSearchFilter);
            defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);

            // Creating Ldap authentication provider using BindAuthenticator and Ldap authentication populator
            ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator,
                    defaultLdapAuthoritiesPopulator);
        } else {
            ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);
        }

        // getting user authenticated
        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);

            final UserDetails principal = new User(userName, userPassword, grantedAuths);

            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);

            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            return authentication;
        }
    } catch (Exception e) {
        LOG.error("getLdapAuthentication LDAP Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasLdapAuthenticationProvider getLdapAuthentication");
    }
    return authentication;
}

From source file:org.apache.atlas.web.security.AtlasPamAuthenticationProvider.java

private Authentication getPamAuthentication(Authentication authentication) {
    try {/*from   w ww  . j  a v a2  s  .c o  m*/
        DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
        String loginModuleName = "org.apache.atlas.web.security.PamLoginModule";
        AppConfigurationEntry.LoginModuleControlFlag controlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
        Properties properties = ConfigurationConverter
                .getProperties(ApplicationProperties.get().subset("atlas.authentication.method.pam"));
        Map<String, String> options = new HashMap<>();
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            options.put(key, value);
        }
        if (!options.containsKey("service"))
            options.put("service", "atlas-login");
        AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(loginModuleName, controlFlag,
                options);
        AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
        Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
        appConfigurationEntriesOptions.put("SPRINGSECURITY", appConfigurationEntries);
        Configuration configuration = new InMemoryConfiguration(appConfigurationEntriesOptions);
        jaasAuthenticationProvider.setConfiguration(configuration);
        UserAuthorityGranter authorityGranter = new UserAuthorityGranter();
        UserAuthorityGranter[] authorityGranters = new UserAuthorityGranter[] { authorityGranter };
        jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
        jaasAuthenticationProvider.afterPropertiesSet();

        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        // getting user authenticated
        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);

            final UserDetails principal = new User(userName, userPassword, grantedAuths);

            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);

            authentication = jaasAuthenticationProvider.authenticate(finalAuthentication);
            authentication = getAuthenticationWithGrantedAuthority(authentication);
            return authentication;
        } else {
            return authentication;
        }

    } catch (Exception e) {
        logger.debug("Pam Authentication Failed:", e);
    }
    return authentication;
}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

private Authentication getGrantedAuthority(Authentication authentication) {
    UsernamePasswordAuthenticationToken result = null;
    if (authentication != null && authentication.isAuthenticated()) {
        final List<GrantedAuthority> grantedAuths = getAuthorities(authentication.getName().toString());
        final UserDetails userDetails = new User(authentication.getName().toString(),
                authentication.getCredentials().toString(), grantedAuths);
        result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(),
                grantedAuths);// w  ww. jav  a2s.c  o  m
        result.setDetails(authentication.getDetails());
        return result;
    }
    return authentication;
}

From source file:org.apache.ranger.service.PasswordComparisonAuthenticator.java

public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password

    DirContextOperations user = null;/*from   w w  w  .  j a  v a 2 s.  c  o m*/
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    Iterator dns = getUserDns(username).iterator();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();

        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username, username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    String encodedPassword = passwordEncoder.encodePassword(password, null);
    byte[] passwordBytes = encodedPassword.getBytes();

    if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
        throw new BadCredentialsException(
                messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

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

public static void updateAuthenticatedUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    Authentication newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, "FAKE_PASSWORD", auth.getAuthorities()), auth.getCredentials(),
            auth.getAuthorities());// w  ww . j av  a 2 s  .com
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

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

/**
 * Attempts to authenticate the given credentials against internal storage and pass-through resources (if
 * configured): the first succeeding causes global success.
 *
 * @param authentication given credentials
 * @return {@code null} if no matching user was found, authentication result otherwise
 *///from w  w w. j a  va 2s  . c  o m
@Transactional(noRollbackFor = DisabledException.class)
public Pair<Long, Boolean> authenticate(final Authentication authentication) {
    Long key = null;
    Boolean authenticated = null;

    User user = userDAO.find(authentication.getName());
    if (user != null) {
        key = user.getKey();
        authenticated = false;

        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");
        }

        boolean userModified = false;
        authenticated = authenticate(user, authentication.getCredentials().toString());
        if (authenticated) {
            if (confDAO.find("log.lastlogindate", Boolean.toString(true)).getValues().get(0)
                    .getBooleanValue()) {
                user.setLastLoginDate(new Date());
                userModified = true;
            }

            if (user.getFailedLogins() != 0) {
                user.setFailedLogins(0);
                userModified = true;
            }

        } else {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userModified = true;
        }

        if (userModified) {
            userDAO.save(user);
        }
    }

    return ImmutablePair.of(key, authenticated);
}

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  av a2s. com*/

    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.AuthContextUtils.java

public static void updateUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, "FAKE_PASSWORD", auth.getAuthorities()), auth.getCredentials(),
            auth.getAuthorities());/*  w  ww  .  j  a va2s  .  c o  m*/
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

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

/**
 * Attempts to authenticate the given credentials against internal storage and pass-through resources (if
 * configured): the first succeeding causes global success.
 *
 * @param authentication given credentials
 * @return {@code null} if no matching user was found, authentication result otherwise
 *//*from w  w  w .j av  a  2s.  co m*/
@Transactional(noRollbackFor = DisabledException.class)
public Pair<User, Boolean> authenticate(final Authentication authentication) {
    User user = null;

    Optional<? extends CPlainAttr> authAttrs = confDAO.find("authentication.attributes");
    List<String> authAttrValues = authAttrs.isPresent() ? authAttrs.get().getValuesAsStrings()
            : Collections.singletonList("username");
    for (int i = 0; user == null && i < authAttrValues.size(); i++) {
        if ("username".equals(authAttrValues.get(i))) {
            user = userDAO.findByUsername(authentication.getName());
        } else {
            AttributeCond attrCond = new AttributeCond(AttributeCond.Type.EQ);
            attrCond.setSchema(authAttrValues.get(i));
            attrCond.setExpression(authentication.getName());
            List<User> users = searchDAO.search(SearchCond.getLeafCond(attrCond), AnyTypeKind.USER);
            if (users.size() == 1) {
                user = users.get(0);
            } else {
                LOG.warn("Value {} provided for {} does not uniquely identify a user", authentication.getName(),
                        authAttrValues.get(i));
            }
        }
    }

    Boolean authenticated = null;
    if (user != null) {
        authenticated = false;

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

        Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
        if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
            throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
        }

        boolean userModified = false;
        authenticated = AuthDataAccessor.this.authenticate(user, authentication.getCredentials().toString());
        if (authenticated) {
            if (confDAO.find("log.lastlogindate", true)) {
                user.setLastLoginDate(new Date());
                userModified = true;
            }

            if (user.getFailedLogins() != 0) {
                user.setFailedLogins(0);
                userModified = true;
            }

        } else {
            user.setFailedLogins(user.getFailedLogins() + 1);
            userModified = true;
        }

        if (userModified) {
            userDAO.save(user);
        }
    }

    return ImmutablePair.of(user, authenticated);
}

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;
    }/*from   ww  w . j a v a2s .  co m*/
    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;
}