在我们用 VueJS 构建的单页应用程序中,我试图显示来自 Mendeley API 的出版物。
我安装了 Mendeley JavaScript SDK yarn
:
yarn add @mendeley/api
VueJS 组件如下所示:
import sdk from '@mendeley/api';
export default {
name: 'Publications',
mounted() {
const api = sdk({
authFlow: sdk.Auth.implicitGrantFlow({
clientId: 012345,
redirectUrl: 'http://localhost:8000/#/publications',
}),
});
api.documents.list().then((docs) => {
console.log('Success!');
console.log(docs);
}).catch((response) => {
console.log('Failed!');
console.log('Response:', response);
});
},
};
组件在 VueRouter 中注册:
{
path: '/publications',
name: 'publications',
component: Publications,
},
现在当我打电话时:
http://localhost:8000/#/publications
我在 Web 控制台中得到以下信息:
Failed!
Response: Error: No token
<... other messages from traceback ...>
并且浏览器被重定向到 Mendeley 的登录表单:
https://id.elsevier.com/as/authorization.oauth2?...
但这不是我想要的!
如果我使用我的凭据登录,浏览器将被简单地重定向到:
http://localhost:8000/#/
浏览器重定向前生成的 URL 为:
https://api.mendeley.com/oauth/authorize?client_id=012345&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F%23%2Fpublications&scope=all&response_type=token
我遵循了包文档中的解释:
https://www.npmjs.com/package/@mendeley/api#implicit-grant-flow
以及这个问题:
Mendeley API - 如何使用 JavaScript SDK - 隐式流认证
看来我太愚蠢了,无法理解 OAuth 2 的工作原理。
在官方文档中有这部分:
显示授权用户界面
使用在上一步中构建的 URL 请求用户授权使用他们的 Mendeley 凭据。您的应用程序可以使用普通的 GET 请求将授权页面加载到现有浏览器窗口中,因为该页面将在流程的最后阶段重定向回您的应用程序。或者,您的应用程序可以打开一个新的弹出窗口或面板来显示授权过程,但在 Web 浏览器窗口之间提取和传输访问令牌需要更多工作。
如有必要,系统将提示用户使用其 Elsevier 凭据登录 Mendeley。如果他们没有 Elsevier 帐户,那么他们可以注册一个作为此流程的一部分。
我需要在没有任何提示的情况下将我们的 SPA 授权给 Mendeley API。SPA 的最终用户应该只获取从浏览器中显示的 API 检索到的内容。