Add generic getClaim() method in ClaimAccessor

Fixes gh-6947
This commit is contained in:
Thomas Vitale 2019-06-15 17:40:54 +02:00 committed by Joe Grandja
parent 59dcc36dd1
commit 417ad40d10
2 changed files with 58 additions and 1 deletions

View File

@ -39,6 +39,20 @@ public interface ClaimAccessor {
*/
Map<String, Object> getClaims();
/**
* Returns the claim value as a {@code T} type.
* The claim value is expected to be of type {@code T}.
*
* @since 5.2
* @param claim the name of the claim
* @param <T> the type of the claim value
* @return the claim value
*/
@SuppressWarnings("unchecked")
default <T> T getClaim(String claim) {
return !containsClaim(claim) ? null : (T) getClaims().get(claim);
}
/**
* Returns {@code true} if the claim exists in {@link #getClaims()}, otherwise {@code false}.
*

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,11 +19,14 @@ import org.junit.Before;
import org.junit.Test;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* Tests for {@link ClaimAccessor}.
@ -101,4 +104,44 @@ public class ClaimAccessorTests {
assertThat(this.claimAccessor.getClaimAsString(claimName)).isNull();
}
@Test
public void getClaimWhenNotExistingThenReturnNull() {
String claimName = "list";
List<String> actualClaimValue = this.claimAccessor.getClaim(claimName);
assertThat(actualClaimValue).isNull();
}
@Test
public void getClaimWhenValueIsConvertedThenReturnList() {
List<String> expectedClaimValue = Arrays.asList("item1", "item2");
String claimName = "list";
this.claims.put(claimName, expectedClaimValue);
List<String> actualClaimValue = this.claimAccessor.getClaim(claimName);
assertThat(actualClaimValue).containsOnlyElementsOf(expectedClaimValue);
}
@Test
public void getClaimWhenValueIsConvertedThenReturnBoolean() {
boolean expectedClaimValue = true;
String claimName = "boolean";
this.claims.put(claimName, expectedClaimValue);
boolean actualClaimValue = this.claimAccessor.getClaim(claimName);
assertThat(actualClaimValue).isEqualTo(expectedClaimValue);
}
@Test
public void getClaimWhenValueIsNotConvertedThenThrowClassCastException() {
String expectedClaimValue = "true";
String claimName = "boolean";
this.claims.put(claimName, expectedClaimValue);
Throwable thrown = catchThrowable(() -> { boolean actualClaimValue = this.claimAccessor.getClaim(claimName); });
assertThat(thrown).isInstanceOf(ClassCastException.class);
}
}