1. 问题
今天写响应时为保安全把token写进了headers的Authorization里
String token = StpUtil.getTokenValue();
System.out.println("成功");
// 使用HTTP头部传递Token,避免直接在响应体中暴露敏感信息
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
return ResponseEntity.ok().headers(headers).body("登录成功");
但是前端的响应里怎么也找不到Authorization这个字段
headers:{
"content-length": "12",
"content-type": "application/json"
}
2. 解决方法
在后端设置跨域这里CorsRegistry registry,加上exposedHeaders("Authorization")
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:5173") // 允许
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的HTTP方法
.allowedHeaders("*") // 允许任何头
.exposedHeaders("Authorization") // 加上这个
.allowCredentials(true) // 允许发送Cookie
.maxAge(3600); // 预检请求的缓存时间(秒)
}
}
现在前端请求时,发现authorization字段出现了
headers:{
"authorization": "Bearer 8f80431c-b0aa-4b0c-865e-49fac64f7423",
"content-length": "12",
"content-type": "application/json"
}