use of org.springframework.security.oauth.provider.ConsumerAuthentication in project spring-security-oauth by spring-projects.
the class OAuthProcessingFilterTests method testValidateSignature.
/**
* test validating the signature.
*/
@Test
public void testValidateSignature() throws Exception {
OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {
@Override
protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
}
};
ConsumerDetails details = mock(ConsumerDetails.class);
SignatureSecret secret = mock(SignatureSecret.class);
OAuthProviderToken token = mock(OAuthProviderToken.class);
OAuthSignatureMethod sigMethod = mock(OAuthSignatureMethod.class);
ConsumerCredentials credentials = new ConsumerCredentials("id", "sig", "method", "base", "token");
when(details.getAuthorities()).thenReturn(new ArrayList<GrantedAuthority>());
when(details.getSignatureSecret()).thenReturn(secret);
filter.setTokenServices(tokenServices);
when(tokenServices.getToken("token")).thenReturn(token);
filter.setSignatureMethodFactory(signatureFactory);
when(token.getSecret()).thenReturn("shhh!!!");
when(signatureFactory.getSignatureMethod("method", secret, "shhh!!!")).thenReturn(sigMethod);
ConsumerAuthentication authentication = new ConsumerAuthentication(details, credentials);
filter.validateSignature(authentication);
verify(sigMethod).verify("base", "sig");
}
use of org.springframework.security.oauth.provider.ConsumerAuthentication 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);
}
use of org.springframework.security.oauth.provider.ConsumerAuthentication in project spring-security-oauth by spring-projects.
the class ProtectedResourceProcessingFilterTests method testOnValidSignature.
/**
* test onValidSignature
*/
@Test
public void testOnValidSignature() throws Exception {
ProtectedResourceProcessingFilter filter = new ProtectedResourceProcessingFilter();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
ConsumerCredentials creds = new ConsumerCredentials("key", "sig", "meth", "base", "tok");
ConsumerAuthentication authentication = new ConsumerAuthentication(mock(ConsumerDetails.class), creds);
authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
OAuthProviderTokenServices tokenServices = mock(OAuthProviderTokenServices.class);
OAuthAccessProviderToken token = mock(OAuthAccessProviderToken.class);
filter.setTokenServices(tokenServices);
when(tokenServices.getToken("tok")).thenReturn(token);
when(token.isAccessToken()).thenReturn(true);
Authentication userAuthentication = mock(Authentication.class);
when(token.getUserAuthentication()).thenReturn(userAuthentication);
filter.onValidSignature(request, response, chain);
verify(chain).doFilter(request, response);
assertSame(userAuthentication, SecurityContextHolder.getContext().getAuthentication());
SecurityContextHolder.getContext().setAuthentication(null);
}
use of org.springframework.security.oauth.provider.ConsumerAuthentication in project spring-security-oauth by spring-projects.
the class AccessTokenProcessingFilter method onValidSignature.
protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException {
//signature is verified; create the token, send the response.
ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication();
OAuthProviderToken authToken = createOAuthToken(authentication);
if (!authToken.getConsumerKey().equals(authentication.getConsumerDetails().getConsumerKey())) {
throw new IllegalStateException("The consumer key associated with the created auth token is not valid for the authenticated consumer.");
}
String tokenValue = authToken.getValue();
StringBuilder responseValue = new StringBuilder(OAuthProviderParameter.oauth_token.toString()).append('=').append(OAuthCodec.oauthEncode(tokenValue)).append('&').append(OAuthProviderParameter.oauth_token_secret.toString()).append('=').append(OAuthCodec.oauthEncode(authToken.getSecret()));
response.setContentType(getResponseContentType());
response.getWriter().print(responseValue.toString());
response.flushBuffer();
}
use of org.springframework.security.oauth.provider.ConsumerAuthentication 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);
}
}
Aggregations