如何以静态方法获取会话ID
我正在研究包括LWC和Tooling API的事情。我写了以下方法,该方法发出了标注。但是,当我当时从LWC调用此方法此方法时,我无法获得会话ID,但是如果我从开发人员控制台调用相同的方法,则可以正常工作。
Apex Code:
@AuraEnabled
public static string getList(String fieldName){
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
System.debug('res------>'+UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint('callout:Tooling_Query/query/?q=Select+id,Namespaceprefix,developername,TableEnumOrId+FROM+customfield+Where+developername+LIKE\'' +fieldName+ '\'');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
System.debug('res------>'+res.getBody());
return res.getBody();
}
当我从LWC调用它时,它将返回此
[{“消息”:“此会话不适合与REST API”,“ errorCode”:“ Invalid_Session_Id”}],
因此,我如何从LWC中获得会话-ID,我已经设置了一个连接的应用程序,并以tooling_query的名称命名凭据 并将URL添加到远程站点。
请在这里帮助我。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能。您在Lightning Web组件上下文中调用的Apex代码无法获取API启用的会话ID。这是
唯一受支持的方法是使用被认证为特定用户。
周围有一个hack浮动,它利用了一个Visualforce页面,从此类顶点上下文中获取会话ID。我不建议这样做,特别是如果您需要访问特权工具API。使用正确的解决方案并构建一个命名的凭据。
You can't. Your Apex code called in a Lightning Web Components context cannot get an API-enabled Session Id. This is documented in the Lightning Web Components Dev Guide:
The only supported approach is to use a Named Credential authenticated as a specific user.
There is a hack floating around that exploits a Visualforce page to obtain a Session Id from such an Apex context. I do not recommend doing this, especially if you need to access the privileged Tooling API. Use the correct solution and build a Named Credential.