当尝试使用@ PreAuthorize对授权进行单元测试时,我得到" No UserProvider找不到UsernamePasswordAuthenticationToken"

时间:2013-05-01 12:43:13

标签: unit-testing junit spring-security authorization mockito

首先:我的问题似乎是No AuthenticationProvider found for UsernamePasswordAuthenticationToken,但实施解决方案并没有对我有所帮助。

我的app-context看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">

<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider ref="userService" />
</security:authentication-manager>

<bean id="userService" class="<util-classpath>.UserServiceMock" >
    <property name="userDetailsService" ref="crowdUserDetailsService" />
    <property name="requestHelper" ref="mockRequestHelper" />
</bean>

<bean id="mockRequestHelper" class="<util-classpath>.RequestHelperMock" />

<bean id="crowdUserDetailsService" class="<util-classpath>.UserDetailsServiceMock" />

<bean id="RemoteCrowdAuthenticationProvider" class="<util-classpath>.RemoteCrowdAuthenticationProviderMock">
    <constructor-arg ref="crowdAuthenticationManager" />
    <constructor-arg ref="httpAuthenticator" />
    <constructor-arg ref="crowdUserDetailsService" />
</bean>

<bean id="crowdAuthenticationManager" class="<util-classpath>.CrowdAuthenticationManagerMock" >
    <constructor-arg ref="securityServerClient" />
</bean>

<bean id="securityServerClient" class="<util-classpath>.SecurityServerClientMock" >
    <constructor-arg ref="clientProperties" />
</bean>

<bean id="clientProperties" class="<util-classpath>.ClientPropertiesMock" >
    <constructor-arg ref="properties" />
</bean>

<bean id="properties" class="<util-classpath>.PropertiesMock" />

<bean id="httpAuthenticator" class="<util-classpath>.HttpAuthenticatorMock" >
    <constructor-arg ref="clientProperties" />
</bean>

<security:global-method-security pre-post-annotations="enabled" />

我的测试控制器:

@ContextConfiguration("classpath:app-context.xml")
public abstract class AbstractControllerTest extends AbstractController {

@Autowired
private AuthenticationManager am;
@Mock
private RemoteCrowdAuthenticationProvider authProvider;
@Mock
private AuthenticationProvider customAuthenticationProvider;

@After
public void clear() {
    SecurityContextHolder.clearContext();
}

protected User getJohnDoe() {
    // role for ordinary user (medewerker)
    User user = new User("JohnDoe", "John", null, null, "Doe");
    Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
    userAuthorities.add(new SimpleGrantedAuthority("EVERYONE_General"));
    userAuthorities.add(new SimpleGrantedAuthority("EVERYONE_Profile"));
    Authentication auth = new UsernamePasswordAuthenticationToken(user.getLoginID(), null, userAuthorities);
    SecurityContextHolder.getContext().setAuthentication(am.authenticate(auth));
    return user;
}

我的特定测试类我在eclipse中使用JUNit运行:

@RunWith(SpringJUnit4ClassRunner.class)
public class AdministrationControllerTest extends AbstractControllerTest {
@Mock
private UserService userService;
@Mock
private RequestHelper requestHelper;
@InjectMocks
private AdministrationController controller = new AdministrationController();

private List<User> users;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);

    users = new ArrayList<User>();
    User employee = new User("smithb", "Bob", "", "", "Smith", User.SeniorityLevel.MEDIOR, "Medior developer", initProfile());
    employee.setId(new Long(123));
    users.add(employee);

    when(userService.findAllUsersIncludingInactive(new Sort(new Sort.Order("firstName")))).thenReturn(users);
}


@Test
public void testShowCompleteEmployeeOverviewNoAccess() {
    User johnDoe = getJohnDoe();
    ModelAndView modelAndView = controller.showCompleteEmployeeOverview(johnDoe, new ModelAndView());

    assertEquals(Constants.LOGOUT_URL, modelAndView.getViewName());

    verify(userService, never()).findAllUsersIncludingInactive(any(Sort.class));
}

模拟的UserService:

public final class UserServiceMock implements UserService, AuthenticationProvider {

private UserDetailsServiceMock userDetailsService;

private RequestHelperMock requestHelper;

@Override
public List<User> findAllUsers() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<User> findAllUsers(Sort sort) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<User> findAllUsersIncludingInactive(Sort sort) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public User findUserById(Long id) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public User findUserByLoginID(String loginId) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public User createUser() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public User saveUser(User user) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void removeUser(User user) {
    // TODO Auto-generated method stub

}

@Override
public Team findTeamById(Long id) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<Team> findAllTeams() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<Team> findAllTeams(Sort sort) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Team saveTeam(Team team) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<User> searchUsers(String name) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean supports(Class<?> authentication) {
    return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

public UserDetailsServiceMock getUserDetailsService() {
    return userDetailsService;
}

public void setUserDetailsService(UserDetailsServiceMock userDetailsService) {
    this.userDetailsService = userDetailsService;
}

public RequestHelperMock getRequestHelper() {
    return requestHelper;
}

public void setRequestHelper(RequestHelperMock requestHelper) {
    this.requestHelper = requestHelper;
}
}

不幸的是我一直在

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

我不明白为什么因为我告诉他在配置中预测使用UserServiceMock作为AuthenticationProvider

1 个答案:

答案 0 :(得分:1)

实际上我所要做的就是在UserServiceMock中实现以下方法:

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    return authentication;
}

而不是返回null;