Example usage for org.springframework.security.web.authentication.www NonceExpiredException NonceExpiredException

List of usage examples for org.springframework.security.web.authentication.www NonceExpiredException NonceExpiredException

Introduction

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

Prototype

public NonceExpiredException(String msg) 

Source Link

Document

Constructs a NonceExpiredException with the specified message.

Usage

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationEntryPointTests.java

@Test
public void testOperationIfDueToStaleNonce() throws Exception {
    DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
    ep.setRealmName("hello");
    ep.setKey("key");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/some_path");

    MockHttpServletResponse response = new MockHttpServletResponse();

    ep.afterPropertiesSet();//from w  w  w .  j  a v a2  s  .  c  o  m

    ep.commence(request, response, new NonceExpiredException("expired nonce"));

    // Check response is properly formed
    assertThat(response.getStatus()).isEqualTo(401);
    assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest ");

    // Break up response header
    String header = response.getHeader("WWW-Authenticate").toString().substring(7);
    String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
    Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");

    assertThat(headerMap.get("realm")).isEqualTo("hello");
    assertThat(headerMap.get("qop")).isEqualTo("auth");
    assertThat(headerMap.get("stale")).isEqualTo("true");

    checkNonceValid(headerMap.get("nonce"));
}

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);

        return;//from  ww w  . j a  va2s .  c  o m
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }

    DigestData digestAuth = new DigestData(header);

    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(),
                this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);

        return;
    }

    // Lookup password for presented username
    // NB: DAO-provided password MUST be clear text - not encoded/salted
    // (unless this instance's passwordAlreadyEncoded property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;

    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());

            if (user == null) {
                throw new AuthenticationServiceException(
                        "AuthenticationDao returned null, which is an interface contract violation");
            }

            this.userCache.putUserInCache(user);
        }

        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());

        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }

            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }

    } catch (UsernameNotFoundException notFound) {
        fail(request, response,
                new BadCredentialsException(
                        this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                                new Object[] { digestAuth.getUsername() }, "Username {0} not found")));

        return;
    }

    // If digest is still incorrect, definitely reject authentication attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '"
                    + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
        }

        fail(request, response, new BadCredentialsException(this.messages
                .getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
        return;
    }

    // To get this far, the digest must have been valid
    // Check the nonce has not expired
    // We do this last so we can direct the user agent its nonce is stale
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(this.messages
                .getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '"
                + digestAuth.getResponse() + "'");
    }

    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);

    chain.doFilter(request, response);
}

From source file:pl.bcichecki.rms.customizations.org.springframework.security.web.authentication.www.EventPublisherAwareDigestAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);

        return;//from www.j  ava 2s.  co  m
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }

    DigestData digestAuth = new DigestData(header);

    try {
        digestAuth.validateAndDecode(authenticationEntryPoint.getKey(),
                authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);

        return;
    }

    // Lookup password for presented username
    // NB: DAO-provided password MUST be clear text - not encoded/salted
    // (unless this instance's passwordAlreadyEncoded property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;

    try {
        if (user == null) {
            cacheWasUsed = false;
            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());

            if (user == null) {
                throw new AuthenticationServiceException(
                        "AuthenticationDao returned null, which is an interface contract violation");
            }

            userCache.putUserInCache(user);
        }

        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());

        // If digest is incorrect, try refreshing from backend and
        // recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }

            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());
            userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }

    } catch (UsernameNotFoundException notFound) {
        // MODIFICATION

        boolean userWasNull = false;
        if (user == null) {
            userWasNull = true;
            user = new User(digestAuth.getUsername(), "fakePassSoSpringShutUp", false, false, false, false,
                    new ArrayList<GrantedAuthority>());
        }

        authenticationEventPublisher.publishAuthenticationFailure(notFound,
                createUnsuccessfulAuthentication(request, user));

        if (userWasNull) {
            user = null;
        }

        // END OF MODIFICATION

        fail(request, response,
                new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                        new Object[] { digestAuth.getUsername() }, "Username {0} not found")));

        return;
    }

    // If digest is still incorrect, definitely reject authentication
    // attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '"
                    + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
        }

        // MODIFICATION

        authenticationEventPublisher.publishAuthenticationFailure(
                new BadCredentialsException("Bad credentials"),
                createUnsuccessfulAuthentication(request, user));

        // END OF MODIFICATION

        fail(request, response, new BadCredentialsException(
                messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
        return;
    }

    // To get this far, the digest must have been valid
    // Check the nonce has not expired
    // We do this last so we can direct the user agent its nonce is stale
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(
                messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '"
                + digestAuth.getResponse() + "'");
    }

    SecurityContextHolder.getContext().setAuthentication(createSuccessfulAuthentication(request, user));

    chain.doFilter(request, response);
}