diff --git a/models/asymkey/ssh_key_authorized_keys.go b/models/asymkey/ssh_key_authorized_keys.go
index f0a3a77eaf..4c9cc1deab 100644
--- a/models/asymkey/ssh_key_authorized_keys.go
+++ b/models/asymkey/ssh_key_authorized_keys.go
@@ -169,7 +169,12 @@ func RewriteAllPublicKeys(ctx context.Context) error {
 		return err
 	}
 
-	t.Close()
+	if err := t.Sync(); err != nil {
+		return err
+	}
+	if err := t.Close(); err != nil {
+		return err
+	}
 	return util.Rename(tmpPath, fPath)
 }
 
diff --git a/models/asymkey/ssh_key_authorized_principals.go b/models/asymkey/ssh_key_authorized_principals.go
index 592196c255..79915df7b5 100644
--- a/models/asymkey/ssh_key_authorized_principals.go
+++ b/models/asymkey/ssh_key_authorized_principals.go
@@ -92,7 +92,12 @@ func RewriteAllPrincipalKeys(ctx context.Context) error {
 		return err
 	}
 
-	t.Close()
+	if err := t.Sync(); err != nil {
+		return err
+	}
+	if err := t.Close(); err != nil {
+		return err
+	}
 	return util.Rename(tmpPath, fPath)
 }