gpt4 book ai didi

java - 对于 Spring boot 中的 GET 请求,如何在单个 JSON 响应中发送 Header 中的一些特定信息和 Body 中的一些信息?

转载 作者:行者123 更新时间:2023-11-30 05:17:43 25 4
gpt4 key购买 nike

在我的 Spring boot 项目中,我创建了 AuthController 类,在其中编写了用于发出登录 POST 请求的代码,并在响应中显示 jwt token 由此成功的登录请求生成。

这是我的AuthController 类的代码-

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsernameOrEmail(),
loginRequest.getPassword()
)
);

SecurityContextHolder.getContext().setAuthentication(authentication);

String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}

这是登录请求成功时我收到的响应 -

{
"accessToken": "abcd",
"tokenType": "Bearer"
}

----现在的问题是---

我需要做一些不同的事情。我希望此 accessToken 在响应 HEADER 中发送,而不是在响应正文中发送。 在响应正文中,我想在 JSON 响应中发送 UserId电子邮件。我不知道该怎么做。因此,如果有人帮助我使用示例代码或对我给出的代码进行一些更改,那就太好了。

最佳答案

尝试使用 HttpServletResponse 添加响应 header 。

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest,
HttpServletResponse response) {

Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsernameOrEmail(),
loginRequest.getPassword()
)
);

SecurityContextHolder.getContext().setAuthentication(authentication);

String jwt = tokenProvider.generateToken(authentication);

// set headers here
response.addHeader("accessToken", jwt);
response.addHeader("tokenType", "Bearer");

JwtAuthenticationResponse response = new JwtAuthenticationResponse();
response.setUserId(/*userId here*/);
response.setEmail(/*email here*/);

return ResponseEntity.ok(response);
}

并在您的 JwtAuthenticationResponse 中添加 userIdemail 字段,或者仅使用另一个类。

public class JwtAuthenticationResponse {

private Long userId;
private String email;

//getters setters
}

关于java - 对于 Spring boot 中的 GET 请求,如何在单个 JSON 响应中发送 Header 中的一些特定信息和 Body 中的一些信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60114770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com