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.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource.java

/**
 * @see org.springframework.ldap.core.AuthenticationSource#getCredentials()
 *//*from  w  w  w  .j ava 2 s.  c om*/
public String getCredentials() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials");
        return "";
    }

    return (String) authentication.getCredentials();
}

From source file:org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor.java

/**
 * Called every time a HTTP invocation is made.
 * <p>/*from w  w w.  j a v a 2s.  co  m*/
 * Simply allows the parent to setup the connection, and then adds an
 * <code>Authorization</code> HTTP header property that will be used for BASIC
 * authentication.
 * </p>
 * <p>
 * The <code>SecurityContextHolder</code> is used to obtain the relevant principal and
 * credentials.
 * </p>
 *
 * @param con the HTTP connection to prepare
 * @param contentLength the length of the content to send
 *
 * @throws IOException if thrown by HttpURLConnection methods
 */
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {
    super.prepareConnection(con, contentLength);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)
            && !trustResolver.isAnonymous(auth)) {
        String base64 = auth.getName() + ":" + auth.getCredentials().toString();
        con.setRequestProperty("Authorization",
                "Basic " + new String(Base64.getEncoder().encode(base64.getBytes())));

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: "
                            + auth.toString());
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
                    + "valid Authentication: " + auth);
        }
    }

    doPrepareConnection(con, contentLength);
}

From source file:org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocation.java

/**
 * Constructs the object, storing the principal and credentials extracted from the
 * client-side security context./*from w  ww  .j a va  2  s .  co  m*/
 *
 * @param methodInvocation the method to invoke
 */
public ContextPropagatingRemoteInvocation(MethodInvocation methodInvocation) {
    super(methodInvocation);
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();

    if (currentUser != null) {
        principal = currentUser.getName();
        Object userCredentials = currentUser.getCredentials();
        credentials = userCredentials == null ? null : userCredentials.toString();
    } else {
        principal = credentials = null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("RemoteInvocation now has principal: " + principal);
        if (credentials == null) {
            logger.debug("RemoteInvocation now has null credentials.");
        }
    }
}

From source file:org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.java

/**
 * Authenticate the given PreAuthenticatedAuthenticationToken.
 * <p>//from ww w. jav a 2  s  .c o m
 * If the principal contained in the authentication object is null, the request will
 * be ignored to allow other providers to authenticate it.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("PreAuthenticated authentication request: " + authentication);
    }

    if (authentication.getPrincipal() == null) {
        logger.debug("No pre-authenticated principal found in request.");

        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated principal found in request.");
        }
        return null;
    }

    if (authentication.getCredentials() == null) {
        logger.debug("No pre-authenticated credentials found in request.");

        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated credentials found in request.");
        }
        return null;
    }

    UserDetails ud = preAuthenticatedUserDetailsService
            .loadUserDetails((PreAuthenticatedAuthenticationToken) authentication);

    userDetailsChecker.check(ud);

    PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(ud,
            authentication.getCredentials(), ud.getAuthorities());
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.springframework.ws.soap.security.x509.X509AuthenticationProvider.java

/**
 * If the supplied authentication token contains a certificate then this will be passed to the configured
 * {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
 * certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
 * which client authentication hasn't been configured in the container) then a BadCredentialsException will be
 * raised.</p>//from ww  w. j a  va 2  s  . c o  m
 *
 * @param authentication the authentication request.
 *
 * @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
 *
 * @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
 * @throws BadCredentialsException if no certificate was presented in the authentication request.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("X509 authentication request: " + authentication);
    }

    X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();

    if (clientCertificate == null) {
        throw new BadCredentialsException(
                messages.getMessage("X509AuthenticationProvider.certificateNull", "Certificate is null"));
    }

    UserDetails user = userCache.getUserFromCache(clientCertificate);

    if (user == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authenticating with certificate " + clientCertificate);
        }
        user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
        userCache.putUserInCache(clientCertificate, user);
    }

    X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate,
            user.getAuthorities());

    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.valkyriercp.security.remoting.BasicAuthHttpInvokerRequestExecutor.java

/**
 * Called every time a HTTP invocation is made.
 * <p>/*from  w  w w .j a va  2 s  . co  m*/
 * Simply allows the parent to setup the connection, and then adds an
 * <code>Authorization</code> HTTP header property that will be used for
 * BASIC authentication. Following that a call to
 * {@link #doPrepareConnection} is made to allow subclasses to apply any
 * additional configuration desired to the connection prior to invoking the
 * request.
 * <p>
 * The previously saved authentication token is used to obtain the principal
 * and credentials. If the saved token is null, then the "Authorization"
 * header will not be added to the request.
 * 
 * @param con
 *            the HTTP connection to prepare
 * @param contentLength
 *            the length of the content to send
 * 
 * @throws IOException
 *             if thrown by HttpURLConnection methods
 */
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {

    super.prepareConnection(con, contentLength);

    Authentication auth = getAuthenticationToken();

    if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
        String base64 = auth.getName() + ":" + auth.getCredentials().toString();
        con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        if (logger.isDebugEnabled()) {
            logger.debug("HttpInvocation now presenting via BASIC authentication with token:: " + auth);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Unable to set BASIC authentication header as Authentication token is invalid: " + auth);
        }
    }

    doPrepareConnection(con, contentLength);
}

From source file:piecework.security.CustomAuthenticationSource.java

public String getPrincipal() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        log.warn("No Authentication object set in SecurityContext - returning empty String as Principal");
        return "";
    }/*from   www  .j av  a2 s .  c  o  m*/

    Object principal = authentication.getPrincipal();

    if (principal instanceof LdapUserDetails) {
        LdapUserDetails details = (LdapUserDetails) principal;
        return details.getDn();
    } else if (authentication.getCredentials() != null
            && authentication.getCredentials() instanceof X509Certificate) {
        if (log.isDebugEnabled()) {
            log.debug("Authenticated by certificate, returning certificate subject name as Principal");
        }
        return principal.toString();
    } else if (authentication instanceof AnonymousAuthenticationToken) {
        if (log.isDebugEnabled()) {
            log.debug("Anonymous Authentication, returning empty String as Principal");
        }
        return "";
    } else {
        throw new IllegalArgumentException(
                "The principal property of the authentication object" + "needs to be an LdapUserDetails.");
    }
}

From source file:piecework.security.CustomAuthenticationSource.java

public String getCredentials() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials");
        return "";
    } else if (authentication.getCredentials() != null
            && authentication.getCredentials() instanceof X509Certificate) {
        if (log.isDebugEnabled()) {
            log.debug("Authenticated by certificate, returning empty string as credentials");
        }//from   w  ww. jav  a2 s  .c  o m
        return "";
    }

    return (String) authentication.getCredentials();
}

From source file:shionn.blog.security.AuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    User user = session.getMapper(AuthenticationDao.class).readUser((String) authentication.getPrincipal());
    if (user == null) {
        throw new BadCredentialsException("TODO msg");
    } else if (checkPassword((UsernamePasswordAuthenticationToken) authentication, user)) {
        authentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
    } else {/*  w w  w. ja  v  a2 s. co m*/
        throw new BadCredentialsException("TODO msg");
    }
    return authentication;
}

From source file:software.coolstuff.springframework.owncloud.service.impl.AbstractOwncloudServiceTest.java

private ResponseActions prepareRestRequest(RestRequest request) throws MalformedURLException {
    MockRestServiceServer server = this.server;
    if (request.getServer() != null) {
        server = request.getServer();/*from   w w w  .  j a  va 2  s .c om*/
    }
    ResponseActions responseActions = server.expect(requestToWithPrefix(request.getUrl()))
            .andExpect(method(request.getMethod()));
    if (StringUtils.isNotBlank(request.getBasicAuthentication())) {
        responseActions.andExpect(header(HttpHeaders.AUTHORIZATION, request.getBasicAuthentication()));
    } else {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        responseActions
                .andExpect(header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(
                        (authentication.getName() + ":" + authentication.getCredentials()).getBytes())));
    }
    return responseActions;
}