How can I get the user token from the context in a Sharepoint WebPart?

Brass Contributor

I have been working in a Sharepoint Webpart with TypeScript. I would like to obtain the user token to pass it as a parameter in the headers. How can I do this?.


So far, I have something like this:

public render(): void {
...
let request = this.getRequest(param1);
...
}

protected getRequest(param1: string): Promise<any> {

let loginURL = this.properties.url+"/admin/api/v2/list";

let body = '{"param":"'+param1+'"}';

let requestHeaders: Headers = new Headers(); requestHeaders.append("Accept-Tos", "true"); requestHeaders.append("Content-Type", "application/json"); requestHeaders.append("respondWithObject", "true");
**requestHeaders.append('Authorization', 'Bearer <TOKEN>'); ????**

let httpClientOptions: IHttpClientOptions = { body: body, headers: requestHeaders
};

return this.context.httpClient.post( loginURL,
HttpClient.configurations.v1, httpClientOptions)
.then((response: HttpClientResponse): any => {
return response.json();
});
}


Regards

 

1 Reply
Hi,
I suggest you try to use PnP JS for SharePoint communication. It will take care of all the authentication and authorization part so that we can focus on the functionality. Please refer the below link for more info.
https://pnp.github.io/pnpjs/getting-started/