Аннотация Spring Security @PreAuthorize("permitAll()") не работает в Spring GraphQLJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Аннотация Spring Security @PreAuthorize("permitAll()") не работает в Spring GraphQL

Сообщение Anonymous »

Я хочу создать систему аутентификации с помощью токена-носителя. Есть некоторые методы, к которым я хочу быть доступными без аутентификации, но когда я заявлял, что сборка не может работать, он всегда возвращает 401 Unauthorized и json. Я использую Spring Boot 3.3.0 с Java 21 и Spring GraphQL.
JSON, который я получаю:

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

{
"timestamp": "2024-07-28T14:12:45.187+00:00",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/api"
}
SecurityConfig.java

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

package com.espacogeek.geek.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
return http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> {
auth.anyRequest().authenticated();
})
.sessionManagement(
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(withDefaults())
.build();
}
}

Я уже пробовал изменить auth.anyRequest().authenticated() на auth.anyRequest().anonymous() и auth.anyRequest().permitAll (), но результат тот же.
Обновление: 28.07.2024 - 11:37 -> Я пробовал использовать jsr250Enabled = true с @PermitAll () аннотирует в MediaController.getSerie(), но результат тот же.
MediaController.java

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

package com.espacogeek.geek.controllers;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.stereotype.Controller;

import com.espacogeek.geek.data.MediaDataController;
import com.espacogeek.geek.models.MediaModel;
import com.espacogeek.geek.services.MediaService;

import jakarta.annotation.security.PermitAll;

@Controller
public class MediaController {
@Autowired
private MediaService mediaService;

@Autowired
private MediaDataController serieController;

@QueryMapping(name = "tvserie")
@PreAuthorize("permitAll()")
public List getSerie(@Argument Integer id, @Argument String name) {

System.out.println("aa");

name = name == null ? null : name.trim();

if (name == null & id == null || name == "" & id == null) {
return new ArrayList();
}

var medias = this.mediaService.findSerieByIdOrName(id, name);
var newMedias = new ArrayList();

for (MediaModel media: medias) {

LocalDate mediaUpdateAt = media.getUpdateAt() == null ? null : LocalDate.ofInstant(media.getUpdateAt().toInstant(), ZoneId.systemDefault());

if (mediaUpdateAt == null) {
media = serieController.updateAllInformation(media, null);
} else if (ChronoUnit.DAYS.between(mediaUpdateAt, LocalDate.now()) < 14 && ChronoUnit.DAYS.between(mediaUpdateAt, LocalDate.now()) >  1) {
// TODO a method to get only the fields updated
// ! by now we'll use updateAllInformation
media = serieController.updateAllInformation(media, null);
} else if (ChronoUnit.DAYS.between(mediaUpdateAt, LocalDate.now()) > 14) {
media = serieController.updateAllInformation(media, null);
}
newMedias.add(media);
}
return newMedias;
}
}

Я уже пробовал изменить @PreAuthorize("permitAll()") на @PermitAll() и @PostAuthorize("permitAll()"), но результат тот же.
Весь мой код можно найти в репозитории GitHub.

Подробнее здесь: https://stackoverflow.com/questions/788 ... n-spring-g
Ответить

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

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

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

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

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