Skip to content

Commit

Permalink
fix null pointers in CustomAuthenticationConverter (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
m-gora authored Dec 1, 2023
1 parent a00386c commit 0d6aee6
Showing 1 changed file with 18 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@

package org.eclipse.tractusx.managedidentitywallets.config.security;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
Expand All @@ -29,17 +35,13 @@
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
* The type Custom authentication converter.
*/
public class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {

private static final String ROLE_PREFIX = "ROLE_";

private final JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter;
private final String resourceId;

Expand All @@ -63,17 +65,15 @@ public AbstractAuthenticationToken convert(Jwt source) {
}

private Collection<? extends GrantedAuthority> extractResourceRoles(Jwt jwt, String resourceId) {
Map<String, Object> resourceAccess = jwt.getClaim("resource_access");
Map<String, Object> resource = (Map<String, Object>) resourceAccess.get(resourceId);
if (Objects.isNull(resource)) {
return Set.of();
}
Collection<String> resourceRoles = (Collection<String>) resource.get("roles");
if (Objects.isNull(resourceRoles)) {
return Set.of();
}
return resourceRoles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toSet());
return Optional.ofNullable(jwt.getClaim("resource_access"))
.filter(resourceAccess -> resourceAccess instanceof Map)
.map(resourceAccess -> ((Map<String, Object>) resourceAccess).get(resourceId))
.filter(resource -> resource instanceof Map)
.map(resource -> ((Map<String, Object>) resource).get("roles"))
.filter(resourceRoles -> resourceRoles instanceof Collection)
.map(resourceRoles -> ((Collection<String>) resourceRoles).stream()
.map(role -> new SimpleGrantedAuthority(ROLE_PREFIX + role))
.collect(Collectors.toSet()))
.orElse(Set.of());
}
}

0 comments on commit 0d6aee6

Please sign in to comment.