【问题标题】:How to pass jwt token into header using Spring boot? [duplicate]如何使用 Spring Boot 将 jwt 令牌传递到标头中? [复制]
【发布时间】:2021-09-27 10:26:00
【问题描述】:

我用 spring boot 和 react 创建了一个简单的应用程序。我登录时从后端获得了 jwt 令牌。自动传递标头后,我需要使用该令牌访问数据。 (如下postmon ss)

这是我的反应代码

useEffect(()=>{
    const config ={
        headers:{
            Authorization: 'Bearer '+ localStorage.getItem('token')
        }
    }
    axios.get('http://localhost:8090/dashboard',config).then(res=>{
        console.log(res);
    })
})

这是我的弹簧控制器类

@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class AuthController {

@Autowired
private UserRepository userRepository;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserService userService;

@Autowired
private JwtUtils jwtUtils;

@GetMapping("/dashboard")
public String testingToken(){
    return "Welcome to dashboard.";
}


@PostMapping("/register")
private ResponseEntity<?> subscribeClient(@RequestBody AuthenticationRequest authenticationRequest){
    String userName = authenticationRequest.getUserName();
    String password = authenticationRequest.getPassword();
    String userType = authenticationRequest.getUserType();

    Users userModel = new Users();
    userModel.setUserName(userName);
    userModel.setPassword(password);
    userModel.setUserType(userType);

    try{
        userRepository.save(userModel);
    }catch (Exception e){
        return ResponseEntity.ok(new AuthenticationResponse("Error while subscription."+ userName));
    }

    return ResponseEntity.ok(new AuthenticationResponse("Successfully authenticated."+ userName));
}

@PostMapping("/login")
private ResponseEntity<?> authenticateClient(@RequestBody AuthenticationRequest authenticationRequest){
    String userName = authenticationRequest.getUserName();
    String password = authenticationRequest.getPassword();

    try {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName,password));
    }catch (Exception e){
        return ResponseEntity.ok(new AuthenticationResponse("Error during client authentication."+ userName));
    }

    UserDetails userDetails = userService.loadUserByUsername(userName);
    String generatedToken = jwtUtils.generateToken(userDetails);

    return ResponseEntity.ok(new AuthenticationResponse(generatedToken));
}

}

当我运行它时,控制台结果是

Access to XMLHttpRequest at 'http://localhost:8090/dashboard' from origin 
'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

如何解决这个问题?

【问题讨论】:

  • cors 是春季回答最多的问题。请在此处询问之前使用谷歌。投票结束

标签: reactjs spring spring-boot spring-security


【解决方案1】:

如果您还没有尝试过,请尝试创建一个扩展 BasicAuthenticationFilter 并覆盖 doFilterInternal() 方法的类,使用请求参数,使用 getHeader() 读取标头并记录。查看您支持的获取令牌的格式是否正确。

在 React 代码中,使用日志并交叉检查 localStorage.getItem('token') 是否返回有效令牌(Bearer YOUR SECRET KEY)

【讨论】:

  • 感谢您的回复。是的,它回来了。我需要将该令牌传递给标题以访问其他内容。
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多