Я пытаюсь создать приложение с использованием Java, которое ограничивает доступ на чтение и запись для каталога. Вот случай:
Есть серверный компьютер, к которому сотрудники доступны через IP-адрес, используя порт. Они хранят свои файлы в определенном каталоге, однако могут видеть и получать доступ к каждой папке и файлу в этом каталоге. Я хочу создать и развернуть приложение Spring Boot на этом компьютере, чтобы оно блокировало этот каталог и было доступно только через аутентификацию с помощью настольного приложения. Настольное приложение отправит запрос приложению Spring Boot, а затем разблокирует необходимые каталоги в зависимости от роли пользователя.
Я пробовал это, но доступ к каталогу все равно возможен для разрешения на чтение и запись:
package FileFlame.FileFlame.controller;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileController {
private final Path rootDirectory = Paths.get("/Users/admin/Desktop/test_directory");
// Called when Spring Boot app starts. Block access to the directory initially
@GetMapping("/initialize")
public void initialize() {
blockDirectoryAccess();
}
// Block access to the directory
private void blockDirectoryAccess() {
File dir = rootDirectory.toFile();
if (dir.exists()) {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// For Windows: Deny access using icacls (deny full control to everyone)
try {
Process process = new ProcessBuilder("icacls", rootDirectory.toString(), "/deny", "everyone:(F)", "/T").start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} else {
// For Unix-based systems (e.g., macOS): Change permissions to block access
try {
// Change permissions to 000 recursively (no permissions)
Process process = new ProcessBuilder("chmod", "-R", "000", rootDirectory.toString()).start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Called after successful login: Unblock access to the directory
@GetMapping("/files")
public String listFiles(Model model) throws Exception {
// Ensure the user is authenticated and has the role
if (SecurityContextHolder.getContext().getAuthentication() != null) {
unblockDirectoryAccess();
var files = rootDirectory.toFile().list();
if (files != null) {
model.addAttribute("files", files);
}
return "files";
}
return "redirect:/login"; // Redirect to login if not authenticated
}
// Unblock access to the directory
private void unblockDirectoryAccess() {
File dir = rootDirectory.toFile();
if (dir.exists()) {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// For Windows: Grant full control to everyone again (unblock access)
try {
Process process = new ProcessBuilder("icacls", rootDirectory.toString(), "/grant", "everyone:(F)", "/T").start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} else {
// For Unix-based systems (e.g., macOS): Change permissions to allow access (755)
try {
// Change permissions to 755 recursively (owner can read/write/execute, others can read/execute)
Process process = new ProcessBuilder("chmod", "-R", "755", rootDirectory.toString()).start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Endpoint to download the file (after authentication)
@GetMapping("/files/{filename}")
public Resource downloadFile(@PathVariable String filename) throws Exception {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
Path filePath = rootDirectory.resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new RuntimeException("File not found: " + filename);
}
} else {
throw new RuntimeException("Unauthorized access.");
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... using-java
Ограничение каталога с помощью Java ⇐ JAVA
Программисты JAVA общаются здесь
1731930056
Anonymous
Я пытаюсь создать приложение с использованием Java, которое ограничивает доступ на чтение и запись для каталога. Вот случай:
Есть серверный компьютер, к которому сотрудники доступны через IP-адрес, используя порт. Они хранят свои файлы в определенном каталоге, однако могут видеть и получать доступ к каждой папке и файлу в этом каталоге. Я хочу создать и развернуть приложение Spring Boot на этом компьютере, чтобы оно блокировало этот каталог и было доступно только через аутентификацию с помощью настольного приложения. Настольное приложение отправит запрос приложению Spring Boot, а затем разблокирует необходимые каталоги в зависимости от роли пользователя.
Я пробовал это, но доступ к каталогу все равно возможен для разрешения на чтение и запись:
package FileFlame.FileFlame.controller;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileController {
private final Path rootDirectory = Paths.get("/Users/admin/Desktop/test_directory");
// Called when Spring Boot app starts. Block access to the directory initially
@GetMapping("/initialize")
public void initialize() {
blockDirectoryAccess();
}
// Block access to the directory
private void blockDirectoryAccess() {
File dir = rootDirectory.toFile();
if (dir.exists()) {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// For Windows: Deny access using icacls (deny full control to everyone)
try {
Process process = new ProcessBuilder("icacls", rootDirectory.toString(), "/deny", "everyone:(F)", "/T").start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} else {
// For Unix-based systems (e.g., macOS): Change permissions to block access
try {
// Change permissions to 000 recursively (no permissions)
Process process = new ProcessBuilder("chmod", "-R", "000", rootDirectory.toString()).start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Called after successful login: Unblock access to the directory
@GetMapping("/files")
public String listFiles(Model model) throws Exception {
// Ensure the user is authenticated and has the role
if (SecurityContextHolder.getContext().getAuthentication() != null) {
unblockDirectoryAccess();
var files = rootDirectory.toFile().list();
if (files != null) {
model.addAttribute("files", files);
}
return "files";
}
return "redirect:/login"; // Redirect to login if not authenticated
}
// Unblock access to the directory
private void unblockDirectoryAccess() {
File dir = rootDirectory.toFile();
if (dir.exists()) {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// For Windows: Grant full control to everyone again (unblock access)
try {
Process process = new ProcessBuilder("icacls", rootDirectory.toString(), "/grant", "everyone:(F)", "/T").start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} else {
// For Unix-based systems (e.g., macOS): Change permissions to allow access (755)
try {
// Change permissions to 755 recursively (owner can read/write/execute, others can read/execute)
Process process = new ProcessBuilder("chmod", "-R", "755", rootDirectory.toString()).start();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Endpoint to download the file (after authentication)
@GetMapping("/files/{filename}")
public Resource downloadFile(@PathVariable String filename) throws Exception {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
Path filePath = rootDirectory.resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new RuntimeException("File not found: " + filename);
}
} else {
throw new RuntimeException("Unauthorized access.");
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79199789/restricting-a-directory-using-java[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия