You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+Angular实现JWT登录后端接收凭证为null如何解决

问题原因

  1. 权限规则配置错误:你的安全配置中/api/auth/**路径被设置为需要ADMIN或USER角色,而登录接口/api/auth/login也属于该路径范围,未登录的请求没有对应角色权限,会直接被Spring Security拦截,根本无法进入你自定义的AuthController登录方法,因此请求参数无法被正常解析,出现null的情况。
  2. 冗余的认证配置:前后端分离的JWT认证场景下,不需要配置formLogin和httpBasic,这两类配置是为传统服务端渲染的认证场景设计,和你自定义的登录接口逻辑冲突,会导致请求被Spring Security自带的认证逻辑提前拦截处理。
  3. 表单参数读取逻辑不匹配:你配置的formLogin失败处理器中用request.getParameter读取参数,该方法仅能读取URL参数或者x-www-form-urlencoded格式的表单参数,无法读取JSON格式的请求体内容,也会导致日志打印的参数为null。

修复方案

第一步:修改Spring Security权限规则

调整SecurityConfiguration类的configure方法,将登录接口加入放行列表,同时移除冗余的formLogin和httpBasic配置,注意放行规则要放在/api/auth/**的权限规则之前,Spring Security的antMatchers按定义顺序匹配,优先级从高到低:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable()
        .authorizeRequests()
            // 放行登录接口等不需要认证的路径
            .antMatchers("/api/posts", "/api/forums", "/api/auth/login").permitAll()
            .antMatchers("/api/auth/admin/**").hasRole("ADMIN")
            .antMatchers("/api/auth/**").hasAnyRole("ADMIN", "USER")
            .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

第二步:检查LoginRequest类定义

确保LoginRequest类的username和password字段有对应的getter、setter方法,或者添加了Lombok的@Data注解,否则Spring MVC无法将JSON请求体正确映射到对象,也会出现字段为null的问题。

第三步:Postman测试配置验证

测试时发送JSON请求需要确保请求头添加了Content-Type: application/json,请求体格式符合要求:

{
  "username": "测试用户名",
  "password": "测试密码"
}

内容的提问来源于stack exchange,提问作者Akhil Bandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 03:15:04