Search code examples
spartacus-storefront

How to call custom endpoints with token on SAP Spartacus storefront?


I'm new on SAP Spartacus storefront, and I'm trying to make a custom API call to check if CNPJ is valid on customer database. My backend is ready and needs to receive a Token on request header.

But I don't find on Spartacus documentation how to use a default token service or interceptor to make this call.

Anyone can help me? Thanks for your time, have a good day.


Solution

  • You can take a look at the Spartacus Session Management documentation.

    • If you need to send the user token, by default it is included in the header of every request made to "occ". This means that if you want to have this same behavior for an endpoint not in OCC you will need to extend and overwrite AuthHttpHeaderService more specifically the isOccUrl method so that it returns "true" for occ endpoints and your external endpoints. It will look like this:
    [...]
    @Injectable({
      providedIn: 'root',
    })
    export class CustomAuthHttpHeaderService extends AuthHttpHeaderService {
      constructor(
        protected authService: AuthService,
        protected authStorageService: AuthStorageService,
        protected oAuthLibWrapperService: OAuthLibWrapperService,
        protected routingService: RoutingService,
        protected occEndpoints: OccEndpointsService,
        protected globalMessageService: GlobalMessageService
      ) {
       super(...);
       }
    
       protected isOccUrl(url: string): boolean {
        return url.includes(this.occEndpoints.getBaseUrl()) || url === 'my-custom-url';
      }
    }
    

    And for the injection:

    {
     provide: AuthHttpHeaderService,
     useClass: CustomAuthHttpHeaderService
    }
    
    • If you need the client token you simply need to place the following string 'cx-use-client-token' in your request's header. If it's there and the user is anonymous, the ClientTokenInterceptor will add the client token. It should be used as follow:
    [...]
    
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
    });
    headers = InterceptorUtil.createHeader(USE_CLIENT_TOKEN, true, headers);
    
    // Your request
    return this.http.post('/your-request-endpoints', { headers });