Предполагая, что пружина и JWT-ваш выбор, это то, как вы сделаете это.
Код: Выделить всё
// @RestController class
@PutMapping("/{id}")
@PreAuthorize("@userPermissionService.isCurrentUserIdEqualTo(#id)")
public ResponseEntity updateUser(@PathVariable long id,
@RequestBody UpdateUserRequestDto userRequestDto) {
// some business logic
}
< /code>
@Service
public class UserPermissionService {
public boolean isCurrentUserIdEqualTo(String userId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) return false;
Jwt jwt = (Jwt) authentication.getPrincipal();
Long currentUserId = jwt.getClaim("userid");
return currentUserId != null && currentUserId.toString().equals(userId);
}
}
< /code>
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
// your security config
}
< /code>
org.springframework.boot
spring-boot-starter-oauth2-resource-server
< /code>
Это работает, но есть несколько бухте. Если userpermissionservice
Код: Выделить всё
@Service("userPermissionService") // first, I want to use this implementation...
public class UserPermissionServiceImpl implements UserPermissionService {
< /code>
@Service("userPermissionService") // ...but then I decide to use this one – move the bean name to another class!
public class UserPermissionServiceImpl2 implements UserPermissionService {
// ...
private final UserPermissionService permissionService; // then somehow reference it
< /code>
Однако я не уверен, как это будет работать. Я почти наверняка не могу ссылаться на поля по имени в выражении Spel.>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ter-values