首页 > 解决方案 > 如何在 Spring Security 中使用 Model Mapper?

问题描述

我尝试替换BeanUtils.copyPropertiesModelMapper.map(). 尝试使用 Spring Security 登录时出现错误:


1) Converter org.modelmapper.internal.converter.MergingCollectionConverter@2a5749f5 failed to convert org.hibernate.collection.internal.PersistentBag to java.util.List.

1 error
    at org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:380) ~[modelmapper-2.3.7.jar:na]
    at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:81) ~[modelmapper-2.3.7.jar:na]
    at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:573) ~[modelmapper-2.3.7.jar:na]
    at org.modelmapper.ModelMapper.map(ModelMapper.java:406) ~[modelmapper-2.3.7.jar:na]
    at com.thao.wsapplication.service.impl.UserServiceImpl.getUser(UserServiceImpl.java:81) ~[main/:na]
    at com.thao.wsapplication.security.AuthenticationFilter.successfulAuthentication(AuthenticationFilter.java:71) ~[main/:na]

功能getUser()

@Override
    public UserDto getUser(String email) {
        UserDto returnValue = new UserDto();
        UserEntity userEntity = userRepository.findByEmail(email);
        if (userEntity == null) throw new UsernameNotFoundException(email);
        returnValue = new ModelMapper().map(userEntity, UserDto.class);
//      BeanUtils.copyProperties(userEntity, returnValue);
        return returnValue;
    }

功能successfulAuthentication()

@Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        String userName = ((User) auth.getPrincipal()).getUsername();  

        String token = Jwts.builder()
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.getTokenSecret())
                .compact();

        UserService userService = (UserService)SpringApplicationContext.getBean("userServiceImpl");
        UserDto userDto = userService.getUser(userName);

        res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
        res.addHeader("UserID", userDto.getUserId());
    }

更新我的源代码:源代码

标签: spring-bootmodelmapperspring-security-rest

解决方案


推荐阅读