@WithUserDetails does not seem to work

被刻印的时光 ゝ 提交于 2019-12-05 21:29:22

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

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();
    }
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!