如何在Java spring boot中使用cookie存储访问令牌?

问题描述 投票:0回答:1

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

前端逻辑

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

我正在尝试这种方法将令牌存储在 cookie 中,并希望访问我的整个应用程序的令牌,以便我可以将其用作中间件来授权我的私有路由

此方法不会在浏览器本地存储中存储cookie。

我什至不知道这是否正确,我是否应该将访问令牌存储在cookie中,因为cookie容易受到XSS攻击。

java spring-boot next.js middleware access-token
1个回答
0
投票

通常,移动应用程序不使用 cookie 来存储任何数据。您可以考虑使用 SQLite 来存储令牌并随时访问它们。

protected final void saveToken(final CustomDatabaseHelper helper, final String token) {
    SQLiteDatabase database = helper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("token", token);
    database.insertOrThrow("table_name", null, values);
    database.close();
}
© www.soinside.com 2019 - 2024. All rights reserved.