|
| 1 | +package com.sap.cloud.sdk.cloudplatform.security; |
| 2 | + |
| 3 | +import static com.sap.cloud.sdk.cloudplatform.DwcHeaderUtils.DWC_JWT_HEADER; |
| 4 | +import static org.assertj.core.api.Assertions.assertThat; |
| 5 | + |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import org.junit.jupiter.api.Test; |
| 9 | + |
| 10 | +import com.auth0.jwt.JWT; |
| 11 | +import com.auth0.jwt.algorithms.Algorithm; |
| 12 | +import com.google.common.collect.ImmutableMap; |
| 13 | +import com.sap.cloud.sdk.cloudplatform.requestheader.RequestHeaderAccessor; |
| 14 | +import com.sap.cloud.sdk.cloudplatform.requestheader.RequestHeaderContainer; |
| 15 | +import com.sap.cloud.sdk.cloudplatform.security.exception.AuthTokenAccessException; |
| 16 | +import com.sap.cloud.sdk.cloudplatform.thread.ThreadContext; |
| 17 | +import com.sap.cloud.sdk.cloudplatform.thread.ThreadContextAccessor; |
| 18 | + |
| 19 | +import io.vavr.control.Try; |
| 20 | + |
| 21 | +class DwcAuthTokenFacadeTest |
| 22 | +{ |
| 23 | + @Test |
| 24 | + void testFacadeIsPickedUpAutomatically() |
| 25 | + { |
| 26 | + assertThat(AuthTokenAccessor.getAuthTokenFacade()).isInstanceOf(DwcAuthTokenFacade.class); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + void testSuccessfulAuthTokenRetrieval() |
| 31 | + { |
| 32 | + final String token = JWT.create().sign(Algorithm.none()); |
| 33 | + |
| 34 | + final AuthToken expectedToken = new AuthToken(JWT.decode(token)); |
| 35 | + final Map<String, String> headers = ImmutableMap.of(DWC_JWT_HEADER, token); |
| 36 | + |
| 37 | + RequestHeaderAccessor.executeWithHeaderContainer(headers, () -> { |
| 38 | + final ThreadContext currentContext = ThreadContextAccessor.getCurrentContext(); |
| 39 | + final AuthToken currentToken = AuthTokenAccessor.getCurrentToken(); |
| 40 | + final Try<AuthToken> maybeTokenFromContext = |
| 41 | + currentContext.getPropertyValue(AuthTokenThreadContextListener.PROPERTY_AUTH_TOKEN); |
| 42 | + |
| 43 | + assertThat(currentToken).isEqualTo(expectedToken); |
| 44 | + assertThat(maybeTokenFromContext).contains(expectedToken); |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + void testUnsuccessfulAuthTokenRetrieval() |
| 50 | + { |
| 51 | + RequestHeaderAccessor.executeWithHeaderContainer(RequestHeaderContainer.EMPTY, () -> { |
| 52 | + final ThreadContext currentContext = ThreadContextAccessor.getCurrentContext(); |
| 53 | + final Try<AuthToken> authTokenFailure = AuthTokenAccessor.tryGetCurrentToken(); |
| 54 | + final Try<AuthToken> shouldBeFailure = |
| 55 | + currentContext.getPropertyValue(AuthTokenThreadContextListener.PROPERTY_AUTH_TOKEN); |
| 56 | + |
| 57 | + assertThat(authTokenFailure.isFailure()).isTrue(); |
| 58 | + assertThat(authTokenFailure.getCause()).isInstanceOf(AuthTokenAccessException.class); |
| 59 | + assertThat(shouldBeFailure.isFailure()).isTrue(); |
| 60 | + assertThat(authTokenFailure).isSameAs(shouldBeFailure); |
| 61 | + }); |
| 62 | + } |
| 63 | +} |
0 commit comments