So I am getting my JWT token with SecurityContext like so:
JwtAuthenticationToken authToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (authToken != null) {
log.warn("Principal authorities:");
authToken.getAuthorities().forEach(auth -> log.warn("authorities: [{}]", auth.getAuthority()));
Map<String, Object> attributes = Collections.emptyMap();
attributes = authToken.getTokenAttributes();
with my token looking something like:
{
"exp": 1705347941,
"iat": 1705347641,
"jti": "011200ff-9c3d-44e4-8f49-be29fc0f7792",
...
"user": [
"backend",
"backend-time"
],
...
How would grab all the values in user
and assign them to a array of type String?
I am consoling my values like, but having trouble creating an string array with all user
values.
attributes
.entrySet()
.forEach(attr -> log.warn("attributes: [{}:{}", attr.getKey(), attr.getValue()));
2
Answers
You could do something like this:
The
.get()
lets you get whatever dataattributes
contains. The code expects for that to be Object, therefore you have to add(List<String>)
before getting the data, so the code knows that it is a list of string you will receive.Then all the strings within user is stored in said list. You could print the data any of these two ways:
You can extract claims like below using the JWT token.
You will get a list like below.
You can use the below dependency.