Created
February 1, 2017 15:59
-
-
Save george-hawkins/3b030c04a55d03b85a99bc69228648b5 to your computer and use it in GitHub Desktop.
ServletRequestMethodArgumentResolver issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.lang.reflect.Method; | |
import java.security.Principal; | |
import org.junit.Assert; | |
import org.junit.Test; | |
import org.springframework.core.MethodParameter; | |
import org.springframework.security.core.Authentication; | |
public class ResolveArgumentTest { | |
// The Principal.class.isAssignableFrom(...) check in ServletRequestMethodArgumentResolver.resolveArgument(...) can result in | |
// it returning a value that clearly cannot be assigned to the parameter in question. | |
// This test boils things down to the minimum - we have: | |
// * a method that wants an Authentication instance | |
// * a request whose getUserPrincipal() something that isn't an instance of Authentication. | |
// * a cut down version of resolveArgument(...) | |
// The test fails because the resolveArgument(...) logic thinks we can satisfy our need for an Authentication instance with | |
// the result of calling getUserPrincipal(). | |
@Test | |
public void testResolveArgument() throws NoSuchMethodException, SecurityException { | |
DummyRequest request = new DummyRequest(); | |
Method method = getClass().getMethod("myRequest", Authentication.class); | |
MethodParameter parameter = new MethodParameter(method, 0); | |
Object arg = resolveArgument(parameter, request); | |
try { | |
method.invoke(this, arg); | |
} catch (Exception e) { | |
Assert.fail(e.getMessage()); | |
} | |
} | |
private Object resolveArgument(MethodParameter parameter, DummyRequest request) { | |
Class<?> paramType = parameter.getParameterType(); | |
if (Principal.class.isAssignableFrom(paramType)) { | |
return request.getUserPrincipal(); | |
} else { | |
throw new AssertionError("paramType of unexpected type"); | |
} | |
} | |
public void myRequest(Authentication authentication) { | |
System.out.println("success"); | |
} | |
private static class DummyRequest { | |
private final Principal userPrincipal = new AccountPrincipal(); | |
public Principal getUserPrincipal() { | |
return userPrincipal; | |
} | |
} | |
private static class AccountPrincipal implements Principal { | |
@Override | |
public String getName() { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment