JwtTypValidator.java
package com.project.auth.config.auth.security;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
import java.util.Objects;
public class JwtTypValidator implements OAuth2TokenValidator<Jwt> {
private static final String TYP_CLAIM = "typ";
private static final String ERROR_CODE = "invalid_token";
private final String expectedTyp;
public JwtTypValidator(String expectedTyp) {
this.expectedTyp = Objects.requireNonNull(expectedTyp, "expectedTyp must not be null");
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
String actual = jwt.getClaimAsString(TYP_CLAIM);
if (expectedTyp.equals(actual)) {
return OAuth2TokenValidatorResult.success();
}
OAuth2Error error = new OAuth2Error(
ERROR_CODE,
"Expected JWT typ=" + expectedTyp + " but got " + actual,
null
);
return OAuth2TokenValidatorResult.failure(error);
}
}