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.ligoj.app.plugin.id.ldap.resource.LdapPluginResource.java

@Override
public Authentication authenticate(final Authentication authentication, final String node,
        final boolean primary) {
    final UserLdapRepository repository = (UserLdapRepository) self.getConfiguration(node).getUserRepository();

    // Authenticate the user
    if (repository.authenticate(authentication.getName(), (String) authentication.getCredentials())) {
        // Return a new authentication based on resolved application user
        return primary ? authentication
                : new UsernamePasswordAuthenticationToken(toApplicationUser(repository, authentication), null);
    }//from w  w w .ja  va  2 s .c  o  m
    throw new BadCredentialsException("");
}

From source file:org.linagora.linshare.auth.sso.SSOAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    // Getting user name from context
    final String userName = (String) authentication.getPrincipal();
    logger.debug("Retrieving user detail for sso authentication with login : " + userName);

    User foundUser = null;/*from www. java  2s. c  o  m*/
    try {
        foundUser = authentificationFacade.loadUserDetails(userName);
    } catch (BusinessException e) {
        logger.error(e);
        throw new AuthenticationServiceException("Could not find user account : " + userName, e);
    }

    if (foundUser == null) {
        return null;
    }

    try {
        authentificationFacade.logAuthSuccess(foundUser);
    } catch (BusinessException e) {
        logger.error(e.getMessage());
        logger.debug(e.getStackTrace());
    }

    List<GrantedAuthority> grantedAuthorities = RoleProvider.getRoles(foundUser);
    UserDetails userDetail = new org.springframework.security.core.userdetails.User(foundUser.getLsUuid(), "",
            true, true, true, true, grantedAuthorities);

    return new UsernamePasswordAuthenticationToken(userDetail, authentication.getCredentials(),
            grantedAuthorities);
}

From source file:org.ojbc.web.portal.controllers.ErrorController.java

@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accesssDenied(Principal user, Authentication authentication, HttpServletRequest request,
        Map<String, Object> model) {
    if (authentication != null) {
        model.put("samlAssertion", authentication.getCredentials());
    }//from  w  ww  .  j av a2 s. co m

    SecurityContextHolder.getContext().setAuthentication(null);

    Map<String, Object> params = new HashMap<String, Object>();

    params.put("policyUrlUserName", policyUrlUserName);
    params.put("policyUrlPassword", policyUrlPassword);
    params.put("helpDeskContactInfo", helpDeskContactInfo);

    String accessControlResponse = (String) request.getAttribute("accessControlResponse");

    if (accessControlResponse != null) {
        String convertPersonSearchResult = searchResultConverter
                .convertIdentityBasedAccessControlResult(accessControlResponse, params);
        model.put("accessControlResponse", convertPersonSearchResult);
    } else {
        model.put("accessControlResponse", getErrorMessage(user));
    }

    return "/error/403";

}

From source file:org.opendaylight.controller.usermanager.internal.UserManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (StringUtils.isBlank((String) authentication.getCredentials())
            || StringUtils.isBlank((String) authentication.getPrincipal())) {
        throw new BadCredentialsException("Username or credentials did not match");
    }//from  w  w  w.  ja v  a 2 s .c  o  m

    AuthResultEnum result = authenticate((String) authentication.getPrincipal(),
            (String) authentication.getCredentials());
    if (result.equals(AuthResultEnum.AUTHOR_PASS) || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC)
            || result.equals(AuthResultEnum.AUTH_ACCEPT)) {

        AuthenticatedUser user = activeUsers.get(authentication.getPrincipal().toString());

        if (user == null) {
            throw new AuthenticationServiceException("Authentication Failure");
        }

        authentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(),
                user.getGrantedAuthorities(getUserLevel(authentication.getName())));
        return authentication;

    } else {
        throw new BadCredentialsException("Username or credentials did not match");
    }

}

From source file:org.opentestsystem.shared.security.oauth.client.grant.samlbearer.SamlAssertionAccessTokenProvider.java

public String getSamlAssertion() {
    String encodedStr = "";
    try {//from  w  w w .j av a2 s.co  m
        final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        final SAMLCredential cred = (SAMLCredential) auth.getCredentials();
        final Assertion assertion = cred.getAuthenticationAssertion();

        final StringWriter output = new StringWriter();

        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(assertion.getDOM()), new StreamResult(output));

        String xml = output.toString();
        LOGGER.info("SAML ASSERTION:" + xml);
        byte[] bytesEncoded = Base64.encodeBase64(xml.getBytes());
        encodedStr = new String(bytesEncoded);

        LOGGER.info("SAML encoded:" + encodedStr);
    } catch (final TransformerException e) {
        LOGGER.error("There was an issue processing the SAML assertion", e);
    }
    return encodedStr;
}

From source file:org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java

License:asdf

@Test
public void authenticateSuccess() throws Exception {
    Authentication auth = provider.authenticate(token);
    assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
    assertThat(auth.getCredentials()).isEqualTo(token.getCredentials());
    assertThat(auth.isAuthenticated()).isEqualTo(true);
    assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false);
    verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class));
    verifyNoMoreInteractions(publisher);
}

From source file:org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("LdapAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }/*from  w w w .  j  a  v  a2  s .  co  m*/

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    if (!StringUtils.hasLength(password)) {
        throw new BadCredentialsException(
                messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    return createSuccessfulAuthentication(userToken, user);
}

From source file:org.springframework.security.ldap.authentication.BindAuthenticator.java

public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*from w w  w .  j  a  va 2s.  c o  m*/
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (!StringUtils.hasLength(password)) {
        logger.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

        if (user != null) {
            break;
        }
    }

    // Otherwise use the configured search object to find the user and authenticate
    // with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password,
                userFromSearch.getAttributes());
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.springframework.security.ldap.authentication.LdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }/*from   w  w w . j a  va2s. c  o m*/

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);

        Collection<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password);

        UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities);

        return createSuccessfulAuthentication(userToken, user);
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    } catch (NamingException ldapAccessFailure) {
        throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
}

From source file:org.springframework.security.ldap.authentication.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 ww.ja v a  2  s  . c o  m*/
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    for (String userDn : getUserDns(username)) {
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
        if (user != null) {
            break;
        }
    }

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

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

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

    if (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        return user;
    } else if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        return user;
    }
    throw new BadCredentialsException(
            messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}