refactor(simple-jwt): Changed the implementation of extracting data in the token payload.

This commit is contained in:
Zihlu Wang
2023-10-17 21:12:33 +08:00
parent fd281ff99e
commit 5b4b6e7997
2 changed files with 35 additions and 30 deletions
@@ -413,42 +413,32 @@ public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
*/ */
@Override @Override
public <T extends TokenPayload> T extract(String token, Class<T> targetType) { public <T extends TokenPayload> T extract(String token, Class<T> targetType) {
// Get claims from token.
var claims = resolve(token).getClaims();
try { try {
// Get claims from token.
var payloads = objectMapper.readValue(Base64Util.decode(resolve(token).getPayload()), new MapTypeReference());
// Get the no-argument constructor to create an instance. // Get the no-argument constructor to create an instance.
T bean = targetType.getConstructor().newInstance(); var bean = targetType.getConstructor().newInstance();
var fields = targetType.getDeclaredFields(); for (var entry : payloads.entrySet()) {
for (var field : fields) { // Jump all JWT pre-defined properties and the fields that are annotated to be excluded.
// Ignore the field annotated with @ExcludeFromPayload. if (PredefinedKeys.KEYS.contains(entry.getKey()) || targetType.getDeclaredField(entry.getKey()).isAnnotationPresent(ExcludeFromPayload.class))
if (field.isAnnotationPresent(ExcludeFromPayload.class))
continue; continue;
// Get the name of this field. var setter = targetType.getDeclaredMethod("set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1), entry.getValue().getClass());
var fieldName = field.getName(); if (setter.canAccess(bean)) {
setter.invoke(bean, entry.getValue());
// Prevent this class is annotated @Slf4j or added logger. } else {
if ("log".equalsIgnoreCase(fieldName) || "logger".equalsIgnoreCase(fieldName)) log.error("Setter for field {} can't be accessed.", entry.getKey());
continue;
// Get the value of this field.
var fieldValue = Optional.ofNullable(claims.get(fieldName))
.map(claim -> claim.as(field.getType()))
.orElse(null);
if (fieldValue != null) {
// Set the field value by invoking the setter method.
var setter = targetType.getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), fieldValue.getClass());
setter.invoke(bean, fieldValue);
} }
} }
return bean; return bean;
} catch (NoSuchMethodException e) { } catch (JsonProcessingException e) {
log.error("Unable to find a no-argument constructor declaration for class {}.", targetType.getCanonicalName()); log.error("Unable to read payload as a Map<String, Object>.", e);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { } catch (InvocationTargetException | InstantiationException | IllegalAccessException |
log.error("Unable to create a new instance of class {}.", targetType.getCanonicalName()); NoSuchMethodException e) {
log.error("Unable to load the constructor or setter.", e);
} catch (NoSuchFieldException e) {
log.error("Unable to load the field.", e);
} }
return null; return null;
} }
@@ -291,7 +291,20 @@ public class JjwtTokenResolver implements TokenResolver<Jws<Claims>> {
var claims = resolvedToken.getBody(); var claims = resolvedToken.getBody();
try { try {
return MapUtil.mapToObject(claims, targetType); var bean = targetType.getConstructor().newInstance();
for (var entry : claims.entrySet()) {
// Jump all JWT pre-defined properties and the fields that are annotated to be excluded.
if (PredefinedKeys.KEYS.contains(entry.getKey()) || targetType.getDeclaredField(entry.getKey()).isAnnotationPresent(ExcludeFromPayload.class))
continue;
var setter = targetType.getDeclaredMethod("set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1), entry.getValue().getClass());
if (setter.canAccess(bean)) {
setter.invoke(bean, entry.getValue());
} else {
log.error("Setter for field {} can't be accessed.", entry.getKey());
}
}
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
log.error("An error occurs while invoking the constructor of type {}.", targetType.getCanonicalName()); log.error("An error occurs while invoking the constructor of type {}.", targetType.getCanonicalName());
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
@@ -299,7 +312,9 @@ public class JjwtTokenResolver implements TokenResolver<Jws<Claims>> {
} catch (InstantiationException e) { } catch (InstantiationException e) {
log.error("The required type {} is abstract or an interface.", targetType.getCanonicalName()); log.error("The required type {} is abstract or an interface.", targetType.getCanonicalName());
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
log.error("An error occurs while accessing the fields of the object."); log.error("An error occurs while accessing the fields of the object.", e);
} catch (NoSuchFieldException e) {
log.error("Cannot load field according to given field name.", e);
} }
return null; return null;