Search in sources :

Example 1 with InvalidOAuthParametersException

use of org.springframework.security.oauth.provider.InvalidOAuthParametersException in project spring-security-oauth by spring-projects.

the class AccessTokenProcessingFilterTests method testOnNewTimestamp.

/**
	 * tests the logic on a new timestamp.
	 */
@Test
public void testOnNewTimestamp() throws Exception {
    try {
        new AccessTokenProcessingFilter().onNewTimestamp();
        fail();
    } catch (InvalidOAuthParametersException e) {
    // fall through
    }
}
Also used : InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) AccessTokenProcessingFilter(org.springframework.security.oauth.provider.filter.AccessTokenProcessingFilter) Test(org.junit.Test)

Example 2 with InvalidOAuthParametersException

use of org.springframework.security.oauth.provider.InvalidOAuthParametersException in project spring-security-oauth by spring-projects.

the class OAuthProcessingFilterTests method testValidateParams.

/**
	 * tests validation of the params.
	 */
@Test
public void testValidateParams() throws Exception {
    OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {

        protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        }
    };
    ConsumerDetails consumerDetails = mock(ConsumerDetails.class);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(OAuthConsumerParameter.oauth_version.toString(), "1.1");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials.");
    } catch (OAuthVersionUnsupportedException e) {
        params.remove(OAuthConsumerParameter.oauth_version.toString());
    }
    filter.getAuthenticationEntryPoint().setRealmName("anywho");
    params.put("realm", "hello");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials.");
    } catch (InvalidOAuthParametersException e) {
    }
    params.put("realm", "anywho");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials for missing signature method.");
    } catch (InvalidOAuthParametersException e) {
    }
    params.remove("realm");
    params.put(OAuthConsumerParameter.oauth_signature_method.toString(), "sigmethod");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials for missing signature.");
    } catch (InvalidOAuthParametersException e) {
    }
    params.remove("realm");
    params.put(OAuthConsumerParameter.oauth_signature_method.toString(), "sigmethod");
    params.put(OAuthConsumerParameter.oauth_signature.toString(), "value");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials for missing timestamp.");
    } catch (InvalidOAuthParametersException e) {
    }
    params.remove("realm");
    params.put(OAuthConsumerParameter.oauth_signature_method.toString(), "sigmethod");
    params.put(OAuthConsumerParameter.oauth_signature.toString(), "value");
    params.put(OAuthConsumerParameter.oauth_timestamp.toString(), "value");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials for missing nonce.");
    } catch (InvalidOAuthParametersException e) {
    }
    params.remove("realm");
    params.put(OAuthConsumerParameter.oauth_signature_method.toString(), "sigmethod");
    params.put(OAuthConsumerParameter.oauth_signature.toString(), "value");
    params.put(OAuthConsumerParameter.oauth_timestamp.toString(), "value");
    params.put(OAuthConsumerParameter.oauth_nonce.toString(), "value");
    try {
        filter.validateOAuthParams(consumerDetails, params);
        fail("should have thrown a bad credentials for bad timestamp.");
    } catch (InvalidOAuthParametersException e) {
    }
    OAuthNonceServices nonceServices = mock(OAuthNonceServices.class);
    filter.setNonceServices(nonceServices);
    params.remove("realm");
    params.put(OAuthConsumerParameter.oauth_signature_method.toString(), "sigmethod");
    params.put(OAuthConsumerParameter.oauth_signature.toString(), "value");
    params.put(OAuthConsumerParameter.oauth_timestamp.toString(), "1111111");
    params.put(OAuthConsumerParameter.oauth_nonce.toString(), "value");
    filter.validateOAuthParams(consumerDetails, params);
    verify(nonceServices).validateNonce(consumerDetails, 1111111L, "value");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthNonceServices(org.springframework.security.oauth.provider.nonce.OAuthNonceServices) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) OAuthVersionUnsupportedException(org.springframework.security.oauth.provider.OAuthVersionUnsupportedException) HashMap(java.util.HashMap) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails) Test(org.junit.Test)

Example 3 with InvalidOAuthParametersException

use of org.springframework.security.oauth.provider.InvalidOAuthParametersException in project spring-security-oauth by spring-projects.

the class OAuthProcessingFilterTests method testDoFilter.

/**
	 * tests do filter.
	 */
@Test
public void testDoFilter() throws Exception {
    final boolean[] triggers = new boolean[2];
    Arrays.fill(triggers, false);
    OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {

        @Override
        protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
            return true;
        }

        protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(null, null);
        }

        @Override
        protected void validateOAuthParams(ConsumerDetails consumerDetails, Map<String, String> oauthParams) throws InvalidOAuthParametersException {
            triggers[0] = true;
        }

        @Override
        protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
            triggers[1] = true;
        }

        @Override
        protected void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failure) throws IOException, ServletException {
            throw failure;
        }

        @Override
        protected Object createDetails(HttpServletRequest request, ConsumerDetails consumerDetails) {
            return null;
        }

        @Override
        protected void resetPreviousAuthentication(Authentication previousAuthentication) {
        // no-op
        }

        @Override
        protected boolean skipProcessing(HttpServletRequest request) {
            return false;
        }
    };
    filter.setProviderSupport(providerSupport);
    filter.setConsumerDetailsService(consumerDetailsService);
    filter.setNonceServices(nonceServices);
    filter.setSignatureMethodFactory(signatureFactory);
    filter.setTokenServices(tokenServices);
    when(request.getMethod()).thenReturn("DELETE");
    filter.doFilter(request, response, filterChain);
    verify(response).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    assertFalse(triggers[0]);
    assertFalse(triggers[1]);
    Arrays.fill(triggers, false);
    when(request.getMethod()).thenReturn("GET");
    HashMap<String, String> requestParams = new HashMap<String, String>();
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    try {
        filter.doFilter(request, response, filterChain);
        fail("should have required a consumer key.");
    } catch (InvalidOAuthParametersException e) {
        assertFalse(triggers[0]);
        assertFalse(triggers[1]);
        Arrays.fill(triggers, false);
    }
    when(request.getMethod()).thenReturn("GET");
    requestParams = new HashMap<String, String>();
    requestParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(), "consumerKey");
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    ConsumerDetails consumerDetails = mock(ConsumerDetails.class);
    when(consumerDetails.getAuthorities()).thenReturn(new ArrayList<GrantedAuthority>());
    when(consumerDetailsService.loadConsumerByConsumerKey("consumerKey")).thenReturn(consumerDetails);
    requestParams.put(OAuthConsumerParameter.oauth_token.toString(), "tokenvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature_method.toString(), "methodvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature.toString(), "signaturevalue");
    when(providerSupport.getSignatureBaseString(request)).thenReturn("sigbasestring");
    filter.doFilter(request, response, filterChain);
    verify(filterChain).doFilter(null, null);
    verify(request).setAttribute(OAuthProviderProcessingFilter.OAUTH_PROCESSING_HANDLED, Boolean.TRUE);
    ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication();
    assertSame(consumerDetails, authentication.getConsumerDetails());
    assertEquals("tokenvalue", authentication.getConsumerCredentials().getToken());
    assertEquals("methodvalue", authentication.getConsumerCredentials().getSignatureMethod());
    assertEquals("signaturevalue", authentication.getConsumerCredentials().getSignature());
    assertEquals("sigbasestring", authentication.getConsumerCredentials().getSignatureBaseString());
    assertEquals("consumerKey", authentication.getConsumerCredentials().getConsumerKey());
    assertTrue(authentication.isSignatureValidated());
    SecurityContextHolder.getContext().setAuthentication(null);
    assertTrue(triggers[0]);
    assertTrue(triggers[1]);
    Arrays.fill(triggers, false);
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) HashMap(java.util.HashMap) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HashMap(java.util.HashMap) Map(java.util.Map) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails) Test(org.junit.Test)

Example 4 with InvalidOAuthParametersException

use of org.springframework.security.oauth.provider.InvalidOAuthParametersException in project spring-security-oauth by spring-projects.

the class OAuthProviderProcessingFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (!skipProcessing(request)) {
        if (requiresAuthentication(request, response, chain)) {
            if (!allowMethod(request.getMethod().toUpperCase())) {
                if (log.isDebugEnabled()) {
                    log.debug("Method " + request.getMethod() + " not supported.");
                }
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return;
            }
            try {
                Map<String, String> oauthParams = getProviderSupport().parseParameters(request);
                if (parametersAreAdequate(oauthParams)) {
                    if (log.isDebugEnabled()) {
                        StringBuilder builder = new StringBuilder("OAuth parameters parsed: ");
                        for (String param : oauthParams.keySet()) {
                            builder.append(param).append('=').append(oauthParams.get(param)).append(' ');
                        }
                        log.debug(builder.toString());
                    }
                    String consumerKey = oauthParams.get(OAuthConsumerParameter.oauth_consumer_key.toString());
                    if (consumerKey == null) {
                        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingConsumerKey", "Missing consumer key."));
                    }
                    //load the consumer details.
                    ConsumerDetails consumerDetails = getConsumerDetailsService().loadConsumerByConsumerKey(consumerKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Consumer details loaded for " + consumerKey + ": " + consumerDetails);
                    }
                    //validate the parameters for the consumer.
                    validateOAuthParams(consumerDetails, oauthParams);
                    if (log.isDebugEnabled()) {
                        log.debug("Parameters validated.");
                    }
                    //extract the credentials.
                    String token = oauthParams.get(OAuthConsumerParameter.oauth_token.toString());
                    String signatureMethod = oauthParams.get(OAuthConsumerParameter.oauth_signature_method.toString());
                    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
                    String signatureBaseString = getProviderSupport().getSignatureBaseString(request);
                    ConsumerCredentials credentials = new ConsumerCredentials(consumerKey, signature, signatureMethod, signatureBaseString, token);
                    //create an authentication request.
                    ConsumerAuthentication authentication = new ConsumerAuthentication(consumerDetails, credentials, oauthParams);
                    authentication.setDetails(createDetails(request, consumerDetails));
                    Authentication previousAuthentication = SecurityContextHolder.getContext().getAuthentication();
                    try {
                        //set the authentication request (unauthenticated) into the context.
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        //validate the signature.
                        validateSignature(authentication);
                        //mark the authentication request as validated.
                        authentication.setSignatureValidated(true);
                        //mark that processing has been handled.
                        request.setAttribute(OAUTH_PROCESSING_HANDLED, Boolean.TRUE);
                        if (log.isDebugEnabled()) {
                            log.debug("Signature validated.");
                        }
                        //go.
                        onValidSignature(request, response, chain);
                    } finally {
                        //clear out the consumer authentication to make sure it doesn't get cached.
                        resetPreviousAuthentication(previousAuthentication);
                    }
                } else if (!isIgnoreInadequateCredentials()) {
                    throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingCredentials", "Inadequate OAuth consumer credentials."));
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Supplied OAuth parameters are inadequate. Ignoring.");
                    }
                    chain.doFilter(request, response);
                }
            } catch (AuthenticationException ae) {
                fail(request, response, ae);
            } catch (ServletException e) {
                if (e.getRootCause() instanceof AuthenticationException) {
                    fail(request, response, (AuthenticationException) e.getRootCause());
                } else {
                    throw e;
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Request does not require authentication.  OAuth processing skipped.");
            }
            chain.doFilter(servletRequest, servletResponse);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Processing explicitly skipped.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) ConsumerCredentials(org.springframework.security.oauth.provider.ConsumerCredentials) AuthenticationException(org.springframework.security.core.AuthenticationException) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails)

Example 5 with InvalidOAuthParametersException

use of org.springframework.security.oauth.provider.InvalidOAuthParametersException in project spring-security-oauth by spring-projects.

the class OAuthProviderProcessingFilter method validateOAuthParams.

/**
   * Validates the OAuth parameters for the given consumer. Base implementation validates only those parameters
   * that are required for all OAuth requests. This includes the nonce and timestamp, but not the signature.
   *
   * @param consumerDetails The consumer details.
   * @param oauthParams     The OAuth parameters to validate.
   * @throws InvalidOAuthParametersException If the OAuth parameters are invalid.
   */
protected void validateOAuthParams(ConsumerDetails consumerDetails, Map<String, String> oauthParams) throws InvalidOAuthParametersException {
    String version = oauthParams.get(OAuthConsumerParameter.oauth_version.toString());
    if ((version != null) && (!"1.0".equals(version))) {
        throw new OAuthVersionUnsupportedException("Unsupported OAuth version: " + version);
    }
    String realm = oauthParams.get("realm");
    realm = realm == null || "".equals(realm) ? null : realm;
    if ((realm != null) && (!realm.equals(this.authenticationEntryPoint.getRealmName()))) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.incorrectRealm", new Object[] { realm, this.getAuthenticationEntryPoint().getRealmName() }, "Response realm name '{0}' does not match system realm name of '{1}'"));
    }
    String signatureMethod = oauthParams.get(OAuthConsumerParameter.oauth_signature_method.toString());
    if (signatureMethod == null) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingSignatureMethod", "Missing signature method."));
    }
    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
    if (signature == null) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingSignature", "Missing signature."));
    }
    String timestamp = oauthParams.get(OAuthConsumerParameter.oauth_timestamp.toString());
    if (timestamp == null) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingTimestamp", "Missing timestamp."));
    }
    String nonce = oauthParams.get(OAuthConsumerParameter.oauth_nonce.toString());
    if (nonce == null) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingNonce", "Missing nonce."));
    }
    try {
        getNonceServices().validateNonce(consumerDetails, Long.parseLong(timestamp), nonce);
    } catch (NumberFormatException e) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.invalidTimestamp", new Object[] { timestamp }, "Timestamp must be a positive integer. Invalid value: {0}"));
    }
    validateAdditionalParameters(consumerDetails, oauthParams);
}
Also used : InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) OAuthVersionUnsupportedException(org.springframework.security.oauth.provider.OAuthVersionUnsupportedException)

Aggregations

InvalidOAuthParametersException (org.springframework.security.oauth.provider.InvalidOAuthParametersException)8 Authentication (org.springframework.security.core.Authentication)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Test (org.junit.Test)3 ConsumerAuthentication (org.springframework.security.oauth.provider.ConsumerAuthentication)3 ConsumerDetails (org.springframework.security.oauth.provider.ConsumerDetails)3 OAuthProviderToken (org.springframework.security.oauth.provider.token.OAuthProviderToken)3 HashMap (java.util.HashMap)2 FilterChain (javax.servlet.FilterChain)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 OAuthVersionUnsupportedException (org.springframework.security.oauth.provider.OAuthVersionUnsupportedException)2 Map (java.util.Map)1 AccessDeniedException (org.springframework.security.access.AccessDeniedException)1 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)1 GrantedAuthority (org.springframework.security.core.GrantedAuthority)1 ConsumerCredentials (org.springframework.security.oauth.provider.ConsumerCredentials)1 ExtraTrustConsumerDetails (org.springframework.security.oauth.provider.ExtraTrustConsumerDetails)1 AccessTokenProcessingFilter (org.springframework.security.oauth.provider.filter.AccessTokenProcessingFilter)1 OAuthNonceServices (org.springframework.security.oauth.provider.nonce.OAuthNonceServices)1