Search code examples
multi-tenants4sdk

TenantAccessor.getCurrentTenant() throws TenantNotAvailableException: Failed to get current tenant: no request available


So I followed https://blogs.sap.com/2017/12/20/deep-dive-6-with-sap-s4hana-cloud-sdk-extend-your-cloud-foundry-application-with-tenant-aware-persistency/

I have a Spring Boot 2.0.1.RELEASE application running in SCP with xs2 library OAuth 2.0 security. If I create an access token in Postman and call my @RestController directly (reaching the DB), I get this error from TenantAccessor.getCurrentTenant():

com.sap.cloud.sdk.cloudplatform.tenant.exception.TenantNotAvailableException: Failed to get current tenant: no request available. This error may occur when trying to obtain the current tenant within tasks that are not triggered by a request, for example, while using a RequestContextExecutor. Note that, on SCP CF, a request is required to obtain tenant information from the JWT bearer in the "Authorization" header.

I don't understand why I get no "request available" when I am obviously sending a request with Authorization header containing Bearer token directly to my @RestController.

I had an idea to solve this by annotating TenantIdentifierResolver class (which contains the TenantAccessor) with @RequestScope, but this fails because then the request context is not found when initializing the app (entityManagerFactory).


Solution

  • This message indicates a missing RequestContext. Such a RequestContext is initialized using either a RequestContextServletFilter or a RequestContextExecutor.

    Your Spring application may be missing the Web Servlet filter. Could you try to add the following @ServletComponentScan annotation to your application?

    @ServletComponentScan({"com.sap.cloud.sdk"})
      ...
    @SpringBootApplication
    public class Application extends SpringBootServletInitializer
    { 
        ...
    }
    

    Within background tasks, you may have to use a RequestContextExecutor. For more details, please also have a look at a related question here.