Использование PreAuthorize для безопасности ресурсов с помощью JWTJAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Использование PreAuthorize для безопасности ресурсов с помощью JWT

Сообщение Гость »


I have successfully implemented JWT-authentication for my Rest-API in Java Spring Boot. Only with a valid JWT-token users can make requests to my secured endpoints. But I need to find a way so that users can only access the resources they own.

If user "foobar" with ID 1 is authenticated, he should only be able to access GET /users/1 and /users?name=foobar. /users/2 should return an error 403.

Currently I have a solution by using

Код: Выделить всё

@PreAuthorize
.

I have made a class UserResourceValidator.java:

Код: Выделить всё

package com.example.demo.auth; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import com.example.demo.model.User; import com.example.demo.repositories.UserRepository; @Component public class UserResourceValidator {          @Autowired     private UserRepository userRepository;          public boolean isResourceOwner(Authentication authentication, Integer resourceId) {         User user = userRepository.findByName(authentication.getName()).orElse(null);                  if (user == null) {             return false;         }                  return user.getId() == resourceId;     } } 
In my UserService.java I use the following

Код: Выделить всё

@PreAuthorize
annotation:

Код: Выделить всё

package com.example.demo.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import com.example.demo.auth.UserResourceValidator; import com.example.demo.model.User; import com.example.demo.repositories.UserRepository; import java.util.Optional; @Service public class UserService {     @Autowired     private UserRepository userRepository;          @Autowired     private UserResourceValidator userResourceValidator;          public boolean userExists(String name) {         Optional user = userRepository.findByName(name);         return user.isPresent();     }          public User createUser(User user) {         if (userExists(user.getName())) {             return null;         }                  return userRepository.save(user);     }          @PreAuthorize("@userResourceValidator.isResourceOwner(authentication, #id)")     public User getUserById(Integer id) {         return userRepository.findById(id).orElse(null);     }          @PreAuthorize("#name == authentication.principal.toString()")     public User getUserByName(String name) {         return userRepository.findByName(name).orElse(null);     } } 
This works fine. But I was wondering if there is a better solution?

Also,

Код: Выделить всё

isResourceOwner
currently only checks if the ID of the authenticated user matches with the ID of the resource. This will work if the requested resource is an User-object, but what if I want to check if a Book with id 123 belongs to user 1?


Источник: https://stackoverflow.com/questions/781 ... y-with-jwt
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»