@WithUserDetails 似乎不起作用 [英] @WithUserDetails does not seem to work

查看:66
本文介绍了@WithUserDetails 似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我在其中使用 Spring Social Security 进行身份验证和授权.不幸的是,我在模拟 Spring Security 时遇到了一些问题.好像根本行不通.

I have an application in which I use Spring Social Security for authentication and authorization. Unfortunately I am having some problems with mocking Spring Security. It seems that it does not work at all.

我有一个 REST 控制器,如果它应该返回的实体标识符不可用,它会返回 404 Not Found.如果用户未登录,则任何页面都会重定向到我的应用的社交登录页面.

I have a REST controller that returns 404 Not Found if the identifier of the entity it should return is not available. If the user is not logged in then any page redirects to the social login page of my app.

我已经阅读了这里 @WithUserDetails 注释最适合我.

I have read here that the @WithUserDetails annotation would suit me the best.

所以我的测试方法是这样的

So my test method looks like this

@Test
@SqlGroup({
    @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, statements = "INSERT INTO UserAccount(id, creationtime, modificationtime, version, email, firstname, lastname, role, signinprovider) VALUES (1, '2008-08-08 20:08:08', '2008-08-08 20:08:08', 1, 'user', 'John', 'Doe', 'ROLE_USER', 'FACEBOOK')"), })
@Rollback
@WithUserDetails
public void ifNoTeamsInTheDatabaseThenTheRestControllerShouldReturnNotFoundHttpStatus() {
    ResponseEntity<String> response = restTemplate.getForEntity("/getTeamHistory/{team}", String.class, "Team");
    Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}

但这似乎根本不起作用.看起来测试方法是匿名用户执行的,因为我得到的状态是200 OK.

But this does not seem to work at all. It looks like the test method is executed with anonymous user, because the status I get is 200 OK.

我的测试类是这样注释的

My test class is annotated like this

@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Transactional
public class TeamRestControllerTest {
    //...
}

有没有人在模拟 Spring Social 提供的 Spring Security 时遇到过这样的问题?

Has anyone ever experienced such an issue with mocking Spring Security that is delivered by Spring Social?

推荐答案

我目前无法对其进行测试,但这里有一个可能的解决方案.

I'm unable to test it at the moment, but here's a possible solution.

查看@WithUserDetails 实现:

Looking at @WithUserDetails implementation:

@WithSecurityContext(factory = WithUserDetailsSecurityContextFactory.class)
public @interface WithUserDetails {
    ...
}

final class WithUserDetailsSecurityContextFactory implements
        WithSecurityContextFactory<WithUserDetails> {

    private BeanFactory beans;

    @Autowired
    public WithUserDetailsSecurityContextFactory(BeanFactory beans) {
        this.beans = beans;
    }

    public SecurityContext createSecurityContext(WithUserDetails withUser) {
        String beanName = withUser.userDetailsServiceBeanName();
        UserDetailsService userDetailsService = StringUtils.hasLength(beanName)
                ? this.beans.getBean(beanName, UserDetailsService.class)
                : this.beans.getBean(UserDetailsService.class);
        String username = withUser.value();
        Assert.hasLength(username, "value() must be non empty String");
        UserDetails principal = userDetailsService.loadUserByUsername(username);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                principal, principal.getPassword(), principal.getAuthorities());
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        return context;
    }
}

您可以按照相同的模式创建您选择的安全上下文:

You could create the Security Context of your choice following the same pattern:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithoutUserFactory.class)
public @interface WithoutUser {
}

public class WithoutUserFactory implements WithSecurityContextFactory<WithoutUser> {
    public SecurityContext createSecurityContext(WithoutUser withoutUser) {
        return SecurityContextHolder.createEmptyContext();
    }
}

其他可用的注解:WithAnonymousUserWithMockUserWithSecurityContext(和WithUserDetails)

The other available annotations: WithAnonymousUser, WithMockUser, WithSecurityContext (and WithUserDetails)

这篇关于@WithUserDetails 似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆