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
Код: Выделить всё
@PreAuthorizeI 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; } } Код: Выделить всё
@PreAuthorizeКод: Выделить всё
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); } } Also,
Код: Выделить всё
isResourceOwnerИсточник: https://stackoverflow.com/questions/781 ... y-with-jwt
Мобильная версия