Search code examples
javaspringvue.jsrequestuserprincipal

HttpServletRequest userprincipal is null at first load


im using javax.servlet.http.HttpServletRequest; to get the request in java controller, i just want to create controller that returns actual user name, im using method getUserPrincipal() in order to get the user in the actual session, it doesn't work at the first page load (returns null) but when i reload the page it works perfectly.

Im using

  • spring framework 5.3.9
  • javaee-api 8.0
  • weblogic 14.1.1
  • vuejs 3.2.37

Here is my java controller

@GetMapping("/username")
    public ResponseEntity<?> getname(HttpServletRequest request) {
        Map<String, String> response = new HashMap<String, String>();

        String username = "";
        try {

            Principal p = request.getUserPrincipal();
            if (p == null || p.getName() == null || p.getName().equals("")) {

                username = "undefined";

            } else {
                username = p.getName();
            }
            response.put("username", username);

            return new ResponseEntity<Object>(
                    response, HttpStatus.OK);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            response.put("username", "");
            return new ResponseEntity<Object>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

I have tried something a little tricky, reload the page in my Vue file when username is undefined, it works but i need this to work at first load.

Can you help me with this issue?

Thanks


Solution

  • Is it possible the first request is sent without user authentication? That's what browsers would typically do, and only when the server responds with HTTP status 403 they would try again with credentials.

    To not deal with such fuss in your application you could simply set a security constraint that only allows authenticated users to access. The container will then automatically send the 403 response and your application would only see valid traffic.