From f532e67886f63d2bf564ed13b2afa1240d07999a Mon Sep 17 00:00:00 2001 From: Francois Prunayre Date: Tue, 10 Nov 2020 13:13:39 +0100 Subject: [PATCH] Auth / Avoid NPE. --- .../common/GnUserAuthentificationConverter.java | 14 +++++++++----- .../controller/SecurityTesterController.java | 10 +++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/modules/library/common-security/src/main/java/org/fao/geonet/common/GnUserAuthentificationConverter.java b/modules/library/common-security/src/main/java/org/fao/geonet/common/GnUserAuthentificationConverter.java index dd585b93..1dd9c21c 100644 --- a/modules/library/common-security/src/main/java/org/fao/geonet/common/GnUserAuthentificationConverter.java +++ b/modules/library/common-security/src/main/java/org/fao/geonet/common/GnUserAuthentificationConverter.java @@ -45,10 +45,14 @@ public Authentication extractAuthentication(Map map) { } private Collection getAuthorities(Map map) { - return ((Map) map.get("authorities")).values().stream() - .map(attributes -> (Map) attributes) - .map(attributes -> - new OAuth2UserAuthority((String) attributes.get("groupName"), attributes)) - .collect(Collectors.toList()); + if (map.containsKey("authorities")) { + return ((Map) map.get("authorities")).values().stream() + .map(attributes -> (Map) attributes) + .map(attributes -> + new OAuth2UserAuthority((String) attributes.get("groupName"), attributes)) + .collect(Collectors.toList()); + } else { + return null; + } } } diff --git a/modules/services/searching/src/main/java/org/fao/geonet/searching/controller/SecurityTesterController.java b/modules/services/searching/src/main/java/org/fao/geonet/searching/controller/SecurityTesterController.java index 075f874f..4d8612f8 100644 --- a/modules/services/searching/src/main/java/org/fao/geonet/searching/controller/SecurityTesterController.java +++ b/modules/services/searching/src/main/java/org/fao/geonet/searching/controller/SecurityTesterController.java @@ -6,7 +6,9 @@ package org.fao.geonet.searching.controller; import java.security.Principal; +import java.util.Optional; import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.web.bind.annotation.RequestMapping; @@ -25,10 +27,12 @@ public String search( Authentication authentication, OAuth2Authentication oauth2Authentication, Principal principal) { + Optional authority = + oauth2Authentication.getAuthorities() + .stream().findFirst(); return String.format( - "Search service called. You are authenticated as %s", + "Search service called. You are authenticated as %s. Authorities: %s", name, - oauth2Authentication.getAuthorities() - .stream().findFirst().get().getAuthority()); + authority.isPresent() ? authority.get().getAuthority() : ""); } }