首页 > 解决方案 > Axios 身份验证请求无法将标头发送到 Spring Boot

问题描述

我正在尝试在 RN 部分使用 Axios 实现授权并将令牌发送到 Spring Boot 后端。我之前尝试过使用简单的发送电子邮件和密码作为 GET 请求的参数来做到这一点,并且效果很好,但是现在当我尝试将带有 btoa 的基本标头发送到后端部分时,它一直在接收空值。我的 React Native 部分:

  login(user) {   
  const headers = {
  authorization: 'Basic ' + btoa(user.email + ':' + user.password)
  };

return axios.get(API_URL + 'login', {headers: headers})
.then(response => {
console.log('function called')

还有我在 Spring Boot 上的控制器:

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
public ResponseEntity<?> login(Principal principal) {
    if(principal == null){
        //logout will also use here so we should return ok http status.
        return (ResponseEntity<?>) ResponseEntity.badRequest();
    }
    UsernamePasswordAuthenticationToken authenticationToken =
            (UsernamePasswordAuthenticationToken) principal;

调试控制器时,看到我的方法参数原理是接收null。我猜这个问题可能在标头或控制器参数中的某个地方,但有真正的想法。

标签: spring-bootreact-nativeauthenticationspring-securityaxios

解决方案


标题应该是:

{
  headers: {
     "Authorization": "Basic "...
  }
}

或者,

{
  auth: {
     username: "",
     password: ""
  }
}

这将为您添加基本的身份验证标头

https://github.com/axios/axios#request-config供参考


推荐阅读