signIn(@RequestBody LoginDto loginDto, HttpServletResponse response) { Stri" /> signIn(@RequestBody LoginDto loginDto, HttpServletResponse response) { Stri" /> signIn(@RequestBody LoginDto loginDto, HttpServletResponse response) { Stri"/>

how to store access token using cookie in Java spring boot?

41 Views Asked by At

AuthController.java

    @PostMapping("/sign-in")
    public ResponseEntity<String> signIn(@RequestBody LoginDto loginDto, HttpServletResponse response) {
        String email = loginDto.getEmail();
        String password = loginDto.getPassword();
        String token = authService.signIn(email, password);

        if (token != null) {
            Cookie cookie = new Cookie("access_token", token);
            cookie.setMaxAge(24 * 60 * 60);
            cookie.setHttpOnly(true);
            cookie.setPath("/");

            response.addCookie(cookie);

            return new ResponseEntity<>("Login Successful", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
        }
    }

Fronted Side Logic

const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log("the button was clicked");
    try {
      const res = await fetch(
        process.env.NEXT_PUBLIC_BASE_URL + "/api/auth/sign-in",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ email, password }),
        }
      );
      if (res.ok) {
        const data = await res.text();
        console.log(data);
      } else {
        console.log("Login failed");
      }
    } catch (err) {
      console.log(err);
    }

i am trying this approach to store token in cookie and want to access the token for my whole application so that i can use it as a middleware for authorising my private routes

this method does not store cookie in browser local storage.

I even don't know that this is right way or not, should i store access token in cookies or not as cookies are vuleranable to XSS attacks.

0

There are 0 best solutions below