简体   繁体   中英

Send custom object as response along with status code 200 on successful login without internal redirection

I want to return user detail object (custom object) as a response to the client once the user is authenticated. I have configured a customSuccessHandler for this but I am not sure how do I send object in response without redirecting it from the handle() method.

Initially I redirected it to another method annotated with @RequestMapping("/user") , but this sent the response status as 302 (redirection) which is not acceptable to the client side (Angular UI).Other option I have is to ask Ui to make another request to ( "/user" ) and get the required details, but this would cause and unnecessary over burden on client to make and extra rest call. Is there a better way of achieving this?

my handle() method in CustomSuccessHandler

@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    HttpSession session = request.getSession(true);     
    Users user = getUserDetails(); //this gets the user details
    session.setAttribute("user",user); 
    response.getWriter().append("OK");
    response.setStatus(200);
}

The functionality I am trying to achieve is on successful user login, my back-end code should reply with status code 200 and also the user details without any extra REST call.

Not really sure if this is the best practice but as you can do this in your handle(..)

response.getWriter().append("OK");

you can do also this:

User user = getUserDetails();
ObjectMapper om = new ObjectMapper();
response.getWriter().append(om.writeValueAsString(user));

remembering that you should of course use some DTO for user details written to response that does not expose password or any other sensitive data.

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