代码之家  ›  专栏  ›  技术社区  ›  pise

org.springframework.security.core.userdetails.user不能转换为myuserdetails(junit 5)

  •  0
  • pise  · 技术社区  · 6 年前

    我正在使用JUnit5测试Web应用程序,除了

    SecurityContextHolder.getContext().getAuthentication().getPrincipal())

    在的行返回对象的代码上方运行测试用例时,控制器类中的行

    org.springframework.security.core.userdetails.user而不是myuserdetails(在Spring引导返回对象中运行应用程序时,myuserdetails和代码运行良好)

    我的测试用例类

    @ExtendWith(SpringExtension.class)
    @WebMvcTest(VendorController.class)
    @AutoConfigureMockMvc
    class VendorControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @Test
        void test() throws Exception {
        mvc.perform(MockMvcRequestBuilders.post("/vendor/user/getVendorList").with(csrf().asHeader())
                .param("iDisplayStart","0")
                .param("iDisplayLength", "10")
                .param("iSortCol_0", "0")
                .param("sSortDir_0", "asc")
                .param("sSearch","")
                .with(user("username").password("password").roles("2"))).andExpect(status().isOk());
         }
    }
    

    在使用JUnit 5运行测试用例时,我缺少什么代码使它返回org.springframework.security.core.userdetails.user对象,但如果我通过Spring引导运行项目,它将正常工作。

    添加UserDetailsService实现代码

    @Service("userDetailsService")
    
    public class MyUserDetailsService implements UserDetailsService {
    
    @Autowired
    
    private UserSvc userSvc;
    
    @Transactional(readOnly=true)
    
    @Override
    
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    
        com.esociety.entity.UserEntity userEntity = userSvc.findByUserName(username);
    
        List<GrantedAuthority> authorities = buildUserAuthority(userEntity.getUserType());
    
        return buildUserForAuthentication(userEntity, authorities);
    
    }
    
    private User buildUserForAuthentication(com.esociety.entity.UserEntity userEntity, List<GrantedAuthority> authorities) {
    
         MyUserDetails myUserDetails = new MyUserDetails (userEntity.getUsername(), userEntity.getPassword(), userEntity.isEnabled(), userEntity.isAccountNonExpired(), userEntity.isCredentialsNonExpired(),userEntity.isAccountNonLocked(),authorities,userEntity.getUserId(),userEntity.getSocietyId(),userEntity.getUserType(),userEntity.getFirstName(),userEntity.getMiddleName(),userEntity.getLastName());
    
         return myUserDetails;
    
    }
    
    private List<GrantedAuthority> buildUserAuthority(String userType) {
    
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
    
        // Build user's authorities
    
        setAuths.add(new SimpleGrantedAuthority(userType));
    
        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
    
        return Result;
    
    }
    
    }
    

    MyUserDetails类

    public class MyUserDetails extends User {
     public MyUserDetails(String username, String password, boolean enabled,
            boolean accountNonExpired, boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities, Long userId,
            Long societyId, String userType, String firstName,
            String middleName, String lastName) {
        super(username, password, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);
        this.userId = userId;
        this.societyId = societyId;
        this.userType = userType;
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
     }
    // getter setter goes here
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   shazin    6 年前

    SecurityMockMvcRequestPostProcessors.user(String username) RequestPostProcessor org.springframework.security.core.userdetails.User UserDetails MyUserDetails

    相反,你可以使用 SecurityMockMvcRequestPostProcessors.user(UserDetails user) 它允许提交您自己的 用户详细信息 ,在这种情况下 我的用户详细信息 你想要的。

    将测试更改为:

    @Test
    void test() throws Exception {
    mvc.perform(MockMvcRequestBuilders.post("/vendor/user/getVendorList").with(csrf().asHeader())
            .param("iDisplayStart","0")
            .param("iDisplayLength", "10")
            .param("iSortCol_0", "0")
            .param("sSortDir_0", "asc")
            .param("sSearch","")
            .with(user(new MyUserDetails ("username", "password", true, true, true,true, Arrays.asList(new SimpleGrantedAuthority("2")),1,1,USER_TYPE,"FirstName","MiddleName","LastName")))).andExpect(status().isOk());
     }
    

    参考弹簧安全性 Source code