0

I have a question using MSAL and Vue3, is about how to write functions to call a protected api, also I wanto to aquire the right access_token, taking in account if expired get a new one.

In the setup of a component a do something like that

EventList.vue

    import { useMsalAuthentication } from 'src/composition-api/useMsalAuthentication';

setup() {
    const events = ref<Event[]>();
    
    const { result, acquireToken } = useMsalAuthentication(
      InteractionType.Redirect,
      loginRequest
    );
    
    const callFn = ref<number>(0);
    
    const loadEvents = async() => {
      try {
        const apiResult = await callGetApi(
          result.value.accessToken,
          'api/Event/GetPaginatedList?Unit=' +
            unitTemp +
            '&SkipCount=0&Date=' +
            date.value
        );
        
        events.value = apiResult.data.result.items;
      } catch (err: any) {
        if(error401) {
          callFn.value = 0;
          acquireToken(); // will cause result change on watcher and this function will be called again
        }else {
          showAlert(
          `Falha ao carregar eventos: ${err.response?.data.errorMessage ?? err}`
          );
        }
      }
    }
    
    // show all files that belong to an event
    const showFiles = async (evtId: number) => {
      currEvtId.value = evtId;
      try {
        const apiResult = await callGetApi(
          result.value.accessToken,
          `/api/Archive/GetUploadedArchives?eventId=${evtId}`
        );
        // process response
        apiResult.data.forEach(
          // ... some code
        );
        showFileDialog.value = true;
      } catch (err: any) {
        if(error401) {
          callFn.value = 1;
          acquireToken(); // will cause result change on watcher and this function will be called again
        }else {
          showAlert(
          `Falha ao carregar arquivos: ${
            err.response?.data.errorMessage ?? err
          }`
         );
        }
        
      }
    };
    
    // Fetch new data from the API each time the result changes (i.e. a new access token was acquired)
    watch(result, async (currentValue, oldValue) => {
      console.log("---- from watch", result.value?.accessToken/*, currentValue, oldValue*/);
      if(callFn.value === 0)
        await loadEvents();
      else if(callFn.value === 1)
          await showFiles(currEvtId.value);
    });
    
}

My pattern for handle token code expiration is not good, I have many function in the component and the code gets dirty. Any one can show me a better approach?

I tried axios interceptor in the response however when I want to call acquireToken() I got an execption: throw "useMsal() cannot be called outside the setup() function of a component";

0 Answers0