Как отключить анонимного пользователя в Spring Security 6.1+JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как отключить анонимного пользователя в Spring Security 6.1+

Сообщение Anonymous »

"
Я не могу отключить анонимных пользователей (я должен использовать JWT, и этот токен генерируется из единого входа с использованием Spring Security 4.x).
Пожалуйста, помогите мне, спасибо всем.
Я использую следующие библиотеки Java 17, Spring Security 6+:

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

org.springframework.security
spring-security-oauth2-resource-server


org.springframework.boot
spring-boot-starter-security


org.springframework.security
spring-security-oauth2-jose

Мой код, класс конфигурации безопасности, при отладке при запуске программы он уже вводится сюда:

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

@Configuration
public class SecurityConfigBase {
@Autowired
private UserService userService;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)  // Tắt CSRF
.anonymous(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v0.1/security/test").authenticated()  // Endpoint /test yêu cầu xác thực
.anyRequest().authenticated()  // Tất cả các endpoint khác đều yêu cầu xác thực
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))  // Xử lý JWT
)
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))  // Trả về 401 nếu không có auth
);
return http.build();
}
@Bean
public JwtDecoder jwtDecoder() {
String secretKey = "key";  // Đảm bảo key chính xác
return NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256")).build();
}

private JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(new CustomJwtGrantedAuthoritiesConverter(userService));
return converter;
}
}
а это клиентский класс Jwt Granted:

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

import com.aiassistant.common.service.UserService;
import com.grooo.jpa.model.exception.CustomException;
import exception.CustomExceptionEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jwt.Jwt;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.stream.Collectors;

public class CustomJwtGrantedAuthoritiesConverter implements Converter {

private final UserService userService;

public CustomJwtGrantedAuthoritiesConverter(UserService userService) {
this.userService = userService;
}

@Override
public Collection convert(Jwt jwt) {
// Lấy thông tin người dùng qua API
try {
UserDetails userDetails = userService.loadUserByUsername();
// Trích xuất quyền từ UserDetails
return userDetails.getAuthorities().stream()
.map(authority ->  new SimpleGrantedAuthority(authority.getAuthority()))
.collect(Collectors.toList());
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
throw new CustomException(CustomExceptionEnum.SERVER_ERROR);
}
}
}

и это ошибка консоли:

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

2024-12-06 17:11:27,333 DEBUG [http-nio-8085-exec-5] o.s.s.w.FilterChainProxy: doFilterInternal Securing GET /api/v0.1/security/test
2024-12-06 17:11:27,333 DEBUG [http-nio-8085-exec-5] o.s.s.w.FilterChainProxy: lambda$doFilterInternal$3 Secured GET /api/v0.1/security/test
2024-12-06 17:11:27,335 DEBUG [http-nio-8085-exec-5] o.s.s.w.a.AnonymousAuthenticationFilter: defaultWithAnonymous Set SecurityContextHolder to anonymous SecurityContext
Я пробую использовать:

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

.anonymous(AbstractHttpConfigurer::disable)
но не работает

Подробнее здесь: https://stackoverflow.com/questions/792 ... curity-6-1
Ответить

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

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

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

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

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