【问题标题】:Spring Security + REST controller Post method not displaying usernameSpring Security + REST 控制器 Post 方法不显示用户名
【发布时间】:2021-08-26 23:13:21
【问题描述】:

我正在使用带有 Spring Security 的 Spring Boot 作为我的 Web 应用程序的身份验证。 我有一个控制器,它将 authenticationRequest(POJO) 参数作为@RequestBody

通过以 JSON 格式传递用户名和密码,从邮递员调用端点 /authenticate 但是当我打印值(用户名和密码)时,我只能看到密码被打印出来。经过多次尝试找不到用户名未填充的原因。

@RequestMapping(value="/authenticate",method=RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception{


    System.out.println("authenticationRequest.getUserName()"+authenticationRequest.getUserName());
    System.out.println("authenticationRequest.getPassword()"+authenticationRequest.getPassword());

    authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUserName(), authenticationRequest.getPassword()));

        
}

POJO 类

public class AuthenticationRequest {
    
private String username;
private String password;

public AuthenticationRequest(){
    
}
public AuthenticationRequest(String username, String password) {
    super();
    this.username = username;
    this.password = password;
}
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;
}

}

JSON(原始) { “用户名”:“用户”, “密码”:“通过” }

控制台

authenticationRequest.getUserName()null
authenticationRequest.getPassword()pass

【问题讨论】:

    标签: java spring spring-boot authentication spring-security


    【解决方案1】:

    问题出在你的 getter 和 setter 上:

    public String getUserName() {
        return username;
    }
    public void setUserName(String username) {
        this.username = username;
    }
    

    字母 n 应该很小,因为您的 JSON 包含带有小 n 的 username。试试这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 2019-07-24
      • 2017-07-31
      • 2019-09-04
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      相关资源
      最近更新 更多