(The post image has nothing to do with bearer tokens, but the Lego 1967 Mustang GT I finished building is just freakishly cool!)
I’m working on a solution which has a small UI created using the SharePoint Framework. This UI will make an authenticated call to a back-end service, which again has to read some data from a SharePoint list for validation.
The easy approach would be to read the validation data in the UI, but this would lead to a potential security hole, disclosing the verification mechanism. I could also have read the SharePoint data using app-only permissions in the back-end service, but this adds one more moving piece.
Thus, I ended up with fetching a valid Bearer token for the logged in user, and passing that along to the back-end service, which in turn can use it for SharePoint authorization.
The code itself is fairly simple from within the SPFx web part.
const provider = await this.context.aadTokenProviderFactory.getTokenProvider();
const token = await provider.getToken('https://<tenant>.sharepoint.com');
Took me a few tries, but pass in the root URL for your tenant and you get a token you can use for future calls against any SharePoint resource (as long as it’s valid).