java - jackson 不匹配输入异常 : No content to map due to end-of-input

标签 java spring-boot spring-security jwt jackson-databind

我正在尝试在我的项目中实现 JWTAuthentication。我已经像这样设置了我的实体:

@Entity
public class ApplicationUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String username,password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

然后我像这样设置了 AuthenticationFilter:

    public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
        private AuthenticationManager authenticationManager;

        public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
            this.authenticationManager = authenticationManager;
        }

        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            try {
                System.out.println("request "+request.getPathInfo());
                ApplicationUser user = new ObjectMapper().readValue(request.getInputStream(),ApplicationUser.class);
//this is where the exception is    
                return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),new ArrayList<>()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
            String token = Jwts.builder()
                    .setSubject(((ApplicationUser) authResult.getPrincipal()).getUsername())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
                    .compact();
            response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
        }
    }

这是我的安全配置:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserDetailsService userDetailsService;

    public SecurityConfig(AppUserDetailService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder){
        this.bCryptPasswordEncoder=bCryptPasswordEncoder;
        this.userDetailsService=userDetailsService;
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
//                .antMatchers(HttpMethod.POST,LOGIN_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

注册工作正常,但是当我尝试使用相同的凭据登录时,出现以下异常:

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0] at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.9.6.jar:2.9.6] at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4145) ~[jackson-databind-2.9.6.jar:2.9.6] at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4000) ~[jackson-databind-2.9.6.jar:2.9.6] at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3070) ~[jackson-databind-2.9.6.jar:2.9.6] at com.project.pq.security.JWTAuthenticationFilter.attemptAuthentication(JWTAuthenticationFilter.java:35) ~[classes/:na] ... 53 common frames omitted

我正在使用 Postman 来访问 API,并将 application/json 设置为内容类型,并将用户名和密码作为 post 参数发送。我正在关注this教程。我究竟做错了什么?任何帮助,将不胜感激。

谢谢

最佳答案

我遇到了同样的错误,必须删除 ApplicationUser 用户 = 新 ObjectMapper().readValue(request.getInputStream(),ApplicationUser.class);

并直接使用request.getParameter:

                new UsernamePasswordAuthenticationToken(
                    request.getParameter("username"),
                    request.getParameter("password"),
                    Collections.emptyList()
            )

关于java - jackson 不匹配输入异常 : No content to map due to end-of-input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51345439/

相关文章:

java - Spring Boot 多部分文件始终为空

java - 测试 Spring bean 时模拟配置属性

java - 如何通过基于 TLS 的 LDAP 对 Active Directory 进行身份验证?

java - 找不到类型 : java. lang.Integer 的 validator

java - 两个构造函数和静态字符串变量

内存提升后 java.lang.ref.Finalizer OutOfMemory

java - equals 和 hashCode 的通用反射辅助方法

java - 使用 testng 检测 @afterMethod 中跳过的测试

带有Apache Tiles的Spring Boot

java - CAS + Spring 安全