Commit b732d910 authored by Szabolcs Gyurko's avatar Szabolcs Gyurko
Browse files

Reworked function to cater for possible null values.

parent d6f044b7
Pipeline #321 failed with stage
in 3 minutes and 35 seconds
......@@ -25,6 +25,7 @@ package com.jeff_cms.jeff.web.util;
*/
import com.jeff_cms.jeff.web.config.JeffConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
......@@ -32,10 +33,13 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.Optional;
/**
* URL utils.
*/
@Component
@Slf4j
public class UrlUtils {
private final JeffConfiguration jeffConfiguration;
......@@ -69,9 +73,10 @@ public class UrlUtils {
return String.format("%s%s", jeffConfiguration.getPagesNodePath(), pagePath);
}
private String getClientAccessToken() {
return RequestContextHolder.getRequestAttributes()
.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, RequestAttributes.SCOPE_REQUEST).toString();
private Optional<String> getClientAccessToken() {
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.map(attrs -> attrs.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, RequestAttributes.SCOPE_REQUEST))
.map(Object::toString);
}
/**
......@@ -83,16 +88,16 @@ public class UrlUtils {
}
/**
* Creates an HTTP entity and adds a bearer token from the current request context.
* Creates an HTTP entity and adds a bearer token from the current request context if there's any.
* @param body Body object
* @param <T> Type of the body
* @return A new HTTP Entity object
*/
public <T> HttpEntity<T> authenticatedEntity(T body) {
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Authorization", "Bearer " + getClientAccessToken());
getClientAccessToken().ifPresent(t -> httpHeaders.add("Authorization", "Bearer " + t));
return new HttpEntity<T>(body, httpHeaders);
return new HttpEntity<>(body, httpHeaders);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment