Spring Boot Jwt Auth не сработает с «еще одним ожидаемым алгоритмом, или не найдено подходящих ключей», несмотря на сопоJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Spring Boot Jwt Auth не сработает с «еще одним ожидаемым алгоритмом, или не найдено подходящих ключей», несмотря на сопо

Сообщение Anonymous »

Я создаю приложение для Spring Boot Microservices, где аут-сервис генерирует JWT, а пользовательский сервис проверяет их. I'm consistently getting a 401 Unauthorized error in the user-service when I make a request with a valid token generated by the auth-service.The specific error from the user-service logs is: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) foundThis is very confusing because I have meticulously configured both services to use the Алгоритм HS512 и тот же секретный ключ. < /P>
my setup1. Auth -Service - Token Generation (jwtservice.java) Эта услуга создает токен с использованием библиотеки io.jsonwebtoken (jjwt) и подписывает его с Signaturalgorithm.hs512. < /p>
package com.grambasket.authservice.security;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class JwtService {

@Value("${spring.security.oauth2.resourceserver.jwt.secret-key}")
private String jwtSecret;

private Key signInKey;

@PostConstruct
public void init() {
this.signInKey = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
log.info("JWT signing key initialized for use with HS512 algorithm.");
}

private String buildToken(Map extraClaims, UserDetails userDetails, long expiration) {
// ...
return Jwts.builder()
// ... other claims (subject, issuer, etc.)
.signWith(signInKey, SignatureAlgorithm.HS512) // Explicitly using HS512
.compact();
}
// ... rest of the class
}
< /code>

Пользовательская служба - проверка токена (SecurityConfig.java) Эта служба является сервером ресурсов OAuth2. Он использует nimbusjwtdecoder для проверки токена, также указав Hmacsha512. < /Li>
< /ol>
package com.grambasket.userservice.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig {

@Value("${spring.security.oauth2.resourceserver.jwt.secret-key}")
private String jwtSecret;

// ... other beans and configs

@Bean
public JwtDecoder jwtDecoder() {
// Expecting HmacSHA512
SecretKeySpec secretKey = new SecretKeySpec(jwtSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
log.info("Configuring JwtDecoder with HmacSHA512 algorithm.");
return NimbusJwtDecoder.withSecretKey(secretKey).build();
}
}
< /code>

Общая конфигурация (Application.yml) Обе службы используют одинаковый секретный ключ. Я попробовал как простой ключ, так и длинный, кодированный Base64-ключ, чтобы убедиться, что он соответствует требованиям длины для HS512. Ошибка одинакова в обоих случаях. security:
oauth2:
resourceserver:
jwt:
secret-key: "mysupersecretkeymysupersecretkey12"
````

user-service/application.yml:

< /code>
spring:
security:
oauth2:
resourceserver:
jwt:
secret-key: "mysupersecretkeymysupersecretkey12"
< /code>


What I Have Tried
1.Algorithm Alignment:
I have triple-checked that both the signing (SignatureAlgorithm.HS512) and decoding ("HmacSHA512") configurations match.
2.Secret Key Verification: The secret key is identical in both services. I've copy-pasted it to be sure.
3.Key Length: I replaced an initial shorter key with a longer one (> 64 bytes) to satisfy the length requirement for HS512, but the error persists.
4.Clean Build: I have run mvn clean install -U and manually deleted my .m2 repository folders to rule out caching issues.
5.Public Endpoint Test: I created a public /ping endpoint in the user-service which works perfectly. The 401 error only occurs when the Authorization: Bearer header is present, which isolates the problem to JWT validation.

Given that the algorithms and secret keys appear to be perfectly matched, what could be the underlying cause for the JwtAuthenticationProvider to fail with Another algorithm expected, or no matching key(s) found?Could there be a subtle conflict between the io.jsonwebtoken library used for signing and the com.nimbusds library used by Spring for decoding? Or could the non-GA dependency versions in my pom.xml be causing this unpredictable behavior?Any insight would be greatly appreciated.


Подробнее здесь: https://stackoverflow.com/questions/796 ... tching-key
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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