Example usage for org.springframework.security.web.authentication.rememberme InvalidCookieException InvalidCookieException

List of usage examples for org.springframework.security.web.authentication.rememberme InvalidCookieException InvalidCookieException

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.rememberme InvalidCookieException InvalidCookieException.

Prototype

public InvalidCookieException(String message) 

Source Link

Usage

From source file:com.edgenius.wiki.security.acegi.TokenBasedRememberMeServices.java

public UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
        HttpServletResponse response) {/*from ww w .  j a  v a 2 s  . co m*/

    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Cookie token did not contain " + 2 + " tokens, but contained '"
                + Arrays.asList(cookieTokens) + "'");
    }

    long tokenExpiryTime;

    try {
        tokenExpiryTime = new Long(cookieTokens[1]).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException(
                "Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1] + "')");
    }

    if (isTokenExpired(tokenExpiryTime)) {
        throw new InvalidCookieException("Cookie token[1] has expired (expired on '" + new Date(tokenExpiryTime)
                + "'; current time is '" + new Date() + "')");
    }

    // Check the user exists.
    // Defer lookup until after expiry time checked, to possibly avoid
    // expensive database call.

    UserDetails userDetails = getUserDetailsService().loadUserByUsername(cookieTokens[0]);

    // Check signature of token matches remaining details.
    // Must do this after user lookup, as we need the DAO-derived password.
    // If efficiency was a major issue, just add in a UserCache
    // implementation,
    // but recall that this method is usually only called once per
    // HttpSession - if the token is valid,
    // it will cause SecurityContextHolder population, whilst if invalid,
    // will cause the cookie to be cancelled.
    String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(),
            userDetails.getPassword());

    if (!expectedTokenSignature.equals(cookieTokens[2])) {
        // NDPDNP - this is part of different with original code
        if (Global.webServiceEnabled || Global.restServiceEnabled) {
            // this is compare different key: it could come from
            // com.edgenius.wiki.integration.client.Authentication.login();
            expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(),
                    userDetails.getPassword(), REMEMBERME_COOKIE_KEY);
            if (expectedTokenSignature.equals(cookieTokens[2])) {
                // Remove this login cookie immediately, so that
                // Authentication.login() won't be a "rememberMe" style login - we just implement login by this cookie but not rememberMe.
                cancelCookie(request, response);
                return userDetails;
            }
        }
        throw new InvalidCookieException("Cookie token[2] contained signature '" + cookieTokens[2]
                + "' but expected '" + expectedTokenSignature + "'");
    }

    return userDetails;
}

From source file:com.sshdemo.common.security.web.authentication.rememberme.JPATokenBasedRememberMeService.java

@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
        HttpServletResponse response) {// w w w . ja  v a2s .  c om

    if (bindingIP) {
        String ip = getUserIPAddress(request);
        final String presentedSeries = cookieTokens[0];
        IPPersistentRememberMeToken token = (IPPersistentRememberMeToken) tokenRepository
                .getTokenForSeries(presentedSeries);
        if (token == null) {
            // No series match, so we can't authenticate using this cookie
            throw new RememberMeAuthenticationException(
                    "No persistent token found for series id: " + presentedSeries);
        }
        if (!ip.equals(token.getIpAddress())) {
            throw new InvalidCookieException(
                    "Cookie IP Address did not contain a matching IP (contained '" + ip + "')");
        }
    }

    return super.processAutoLoginCookie(cookieTokens, request, response);
}

From source file:org.jasypt.spring.security3.TokenBasedRememberMeServices.java

protected UserDetails processAutoLoginCookie(final String[] cookieTokens, final HttpServletRequest request,
        final HttpServletResponse response) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a "
                + "digester has not been set. A value must be specified for the \"digester\""
                + " property in service of class " + this.getClass().getName());
    }//from   w  w w.  j a v a 2  s.  c  om

    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Wrong number of tokens in cookie");
    }

    final String usernameToken = cookieTokens[0];
    final String expiryToken = cookieTokens[1];
    final String digestedSignature = cookieTokens[2];

    long expiryTimestamp = -1;
    try {
        expiryTimestamp = new Long(expiryToken).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException("Invalid cookie expiry token");
    }

    if (expiryTimestamp < System.currentTimeMillis()) {
        // Cookie has expired
        throw new InvalidCookieException("Cookie has expired (expired on '" + new Date(expiryTimestamp)
                + "'; current time is '" + new Date() + "')");
    }

    // Retrieve user details
    final UserDetails userDetails = getUserDetailsService().loadUserByUsername(usernameToken);
    final String username = userDetails.getUsername();
    final String password = userDetails.getPassword();

    // Check signature data
    if (!this.digester.matches(getSignatureData(expiryTimestamp, username, password), digestedSignature)) {
        throw new InvalidCookieException("Cookie signature is not valid");
    }

    return userDetails;

}

From source file:com.acc.storefront.security.AcceleratorRememberMeServices.java

@Override
protected String[] decodeCookie(final String cookieValue) throws InvalidCookieException {
    try {/*w  w  w.  j ava2  s  . co m*/
        return super.decodeCookie(getSecureTokenService().decryptData(cookieValue).getData());
    } catch (final SystemException | IllegalArgumentException e) {
        throw new InvalidCookieException("Cookie token was not encrypted; value was '" + cookieValue + "'");
    }
}

From source file:com.thinkbiganalytics.auth.jwt.JwtRememberMeServices.java

/**
 * Decodes the specified JWT cookie into tokens.
 *
 * <p>The first element of the return value with be the JWT subject. The remaining elements are the elements in the {@code groups} list.</p>
 *
 * @param cookie the JWT cookie/*from  ww  w.ja  v a  2s.  c  o m*/
 * @return an array with the username and group names
 * @throws IllegalStateException  if the secret key is invalid
 * @throws InvalidCookieException if the cookie cannot be decoded
 */
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
    // Build the JWT parser
    final JwtConsumer consumer = new JwtConsumerBuilder()
            .setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis()))
            .setVerificationKey(getSecretKey()).build();

    // Parse the cookie
    final String user;
    final List<String> groups;

    try {
        final JwtClaims claims = consumer.processToClaims(cookie);
        user = claims.getSubject();
        groups = claims.getStringListClaimValue(GROUPS);
    } catch (final InvalidJwtException e) {
        throw new InvalidCookieException("JWT cookie is invalid: " + e);
    } catch (final MalformedClaimException e) {
        throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
    }

    if (StringUtils.isBlank(user)) {
        throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
    }

    // Build the token array
    final Stream<String> userStream = Stream.of(user);
    final Stream<String> groupStream = groups.stream();
    return Stream.concat(userStream, groupStream).toArray(String[]::new);
}

From source file:org.bibsonomy.webapp.util.spring.security.rememberMeServices.LDAPRememberMeServices.java

@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
        HttpServletResponse response) throws RememberMeAuthenticationException, UsernameNotFoundException {
    if (cookieTokens.length != 5) {
        throw new InvalidCookieException(
                "Cookie token did not contain 5 tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }//from ww w  .  j  a v a  2 s .  c  om

    final String username = cookieTokens[0];

    long tokenExpiryTime = this.getExpiryTime(cookieTokens[3]);

    final UserDetails loadUserByUsername = this.getUserDetailsService().loadUserByUsername(username);
    if (loadUserByUsername instanceof UserAdapter) {
        final UserAdapter adapter = (UserAdapter) loadUserByUsername;
        final User user = adapter.getUser();
        final String ldapID = user.getLdapId();
        final String clearPassword = cookieTokens[2];

        final String expectedTokenSignature = this.makeTokenSignature(
                new String[] { Long.toString(tokenExpiryTime), username, ldapID, clearPassword });
        final String signature = cookieTokens[4];

        if (!expectedTokenSignature.equals(signature)) {
            throw new InvalidCookieException("Cookie token[4] contained signature '" + signature
                    + "' but expected '" + expectedTokenSignature + "'");
        }

        user.setPassword(clearPassword);
        return loadUserByUsername;
    }

    throw new UsernameNotFoundException(""); // TODO
}

From source file:org.bibsonomy.webapp.util.spring.security.rememberMeServices.OpenIDRememberMeServices.java

@Override
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, final HttpServletRequest request,
        final HttpServletResponse response)
        throws RememberMeAuthenticationException, UsernameNotFoundException {
    if (cookieTokens.length != 4) {
        throw new InvalidCookieException(
                "Cookie token did not contain 4 tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }/*from w w w . j  a  v  a2s  .c  o m*/

    final long tokenExpiryTime = this.getExpiryTime(cookieTokens[2]);

    /*  
     * if user is not logged in, redirect user to his open id provider
     * extract open id and user name
     */
    final String username = cookieTokens[1];
    final String claimedIdentity = cookieTokens[0];

    /*
     * note: AbstractRememberMeServices#autoLogin checks if the user was deleted
     */
    final UserDetails userDetails = this.getUserDetailsService().loadUserByUsername(username);

    /*
     * extract open ID from the database user
     */
    if (!present(userDetails) || !(userDetails instanceof UserAdapter)) {
        throw new AuthenticationServiceException("User or ID could not be found in database.");
    }

    final String databaseIdentity = ((UserAdapter) userDetails).getUser().getOpenID();

    /*
     * check token signature
     */
    final String expectedTokenSignature = this
            .makeTokenSignature(new String[] { Long.toString(tokenExpiryTime), username, databaseIdentity });
    final String signature = cookieTokens[3];
    if (!expectedTokenSignature.equals(signature)) {
        throw new InvalidCookieException("Cookie token[3] contained signature '" + signature
                + "' but expected '" + expectedTokenSignature + "'");
    }

    /*
     * build the url for the open id
     */
    final String returnToUrl = this.buildReturnToUrl(request);
    final String realm = this.lookupRealm(returnToUrl);
    String openIdUrl = null;
    try {
        openIdUrl = this.consumer.beginConsumption(request, claimedIdentity, returnToUrl, realm);
        if (log.isDebugEnabled()) {
            log.debug("return_to is '" + returnToUrl + "', realm is '" + realm + "'");
            log.debug("Redirecting to " + openIdUrl);
        }

        /*
         * save request in cache
         */
        this.requestCache.saveRequest(request, response);

        response.sendRedirect(openIdUrl);
    } catch (final IOException ex) {
        log.warn("could not set redirect url " + openIdUrl, ex);
    } catch (final OpenIDConsumerException e) {
        log.debug("Failed to consume claimedIdentity: " + claimedIdentity, e);
        throw new AuthenticationServiceException(
                "Unable to process claimed identity '" + claimedIdentity + "'");
    }

    // throw an exception to redirect the user
    throw new RememberMeAuthenticationException("redirect was sent");
}

From source file:org.flowable.app.filter.FlowableCookieFilter.java

protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
    for (int j = 0; j < cookieValue.length() % 4; j++) {
        cookieValue = cookieValue + "=";
    }// w  w w. j a va2 s. c  om

    if (!Base64.isBase64(cookieValue.getBytes())) {
        throw new InvalidCookieException(
                "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
    }

    String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes()));

    String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER);

    if ((tokens[0].equalsIgnoreCase("http") || tokens[0].equalsIgnoreCase("https"))
            && tokens[1].startsWith("//")) {
        // Assume we've accidentally split a URL (OpenID identifier)
        String[] newTokens = new String[tokens.length - 1];
        newTokens[0] = tokens[0] + ":" + tokens[1];
        System.arraycopy(tokens, 2, newTokens, 1, newTokens.length - 1);
        tokens = newTokens;
    }

    return tokens;
}

From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Decodes the cookie and splits it into a set of token strings using the ":"
 * delimiter.//ww w  .j  a  va 2 s. c o  m
 *
 * @param cookieValue the value obtained from the submitted cookie
 * @return the array of tokens.
 * @throws InvalidCookieException if the cookie was not base64 encoded.
 */
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
    for (int j = 0; j < cookieValue.length() % 4; j++) {
        cookieValue = cookieValue + "=";
    }

    try {
        Base64.getDecoder().decode(cookieValue.getBytes());
    } catch (IllegalArgumentException e) {
        throw new InvalidCookieException(
                "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
    }

    String cookieAsPlainText = new String(Base64.getDecoder().decode(cookieValue.getBytes()));

    String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER);

    for (int i = 0; i < tokens.length; i++) {
        try {
            tokens[i] = URLDecoder.decode(tokens[i], StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
    }

    return tokens;
}