简体   繁体   中英

How to send some specific info in Header and some info in Body in a single JSON response, for a GET request in Spring boot?

In my Spring boot project, I have made AuthController class, where I have written the code for making Sign-in POST request and in response, I show the jwt token generated by this successful Sign-in request.

Here's the code of my AuthController class -

@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));
}

And here's the response I get, when the sign-in request is successful-

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

----Now the Problem is---

I need to do something different. I want this accessToken to send in response HEADER rather than the response Body . In response Body , I want to send the UserId and email in a JSON response. I am not having any idea how to do that. So, It would be nice if someone help me to do that with an example code or making some changes in the code I have given.

Try using HttpServletResponse to add response headers.

@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);
}

And in your JwtAuthenticationResponse add userId and email fields, or just use another class.

public class JwtAuthenticationResponse {

    private Long userId;
    private String email;

    //getters setters
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM