将 fetch 与 Identity Server 4 结合使用

Use fetch with Identity Server 4

在使用资源所有者密码流时,如何使用 IdentityServer4 获取 JWT 令牌? (大多数时候不推荐)。

即使我应该使用隐式流程,我也想使用这个流程,因为它在我的 spa 应用程序的情况下更方便。 首先,您会在这里找到有用的信息来实施您的解决方案:

但是如何使用 [fetch-api] 从 IdentityServer 4 获取令牌?

    const form = new FormData();
    form.append('grant_type', 'password');
    form.append('username', username);
    form.append('password', password);
    if (this._settings.scope) {
        form.append('scope', this._settings.scope);
    }
    form.append('client_id', this._settings.clientId);
    if (this._settings.clientSecret) {
        form.append('client_secret', this._settings.clientSecret);
    }

    var options = {
        method: 'POST',
        headers: {
           'Content-Type': 'multipart/form-data'
        },
        rejectUnauthorized: false, // when use local unverified certificate
        body: form
    };

我应该收到一个 JWT 令牌作为响应,但我收到了一个 http 500 错误。 "Internal Server Error"

如果我使用 fiddler 跟踪 HTTP headers,我得到以下结果:

POST http://127.0.0.1:8888/ HTTP/1.1
content-type: multipart/form-data
accept-encoding: gzip,deflate
user-agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
connection: close
accept: */*
content-length: 896
Host: 127.0.0.1:8888

正如我在之前的评论中提到的:如果您想使用 Fetch 以便 POST 具有表单数据的授权请求,则不得将 content-type 指定到header。因为 fetch 会自动用正确的值 ("multipart/form-data") 填充它并添加动态生成的 content-boundary。 另请注意,如果您更喜欢使用 application/x-www-form-urlencoded content-type 方法,则可以使用 URLSearchParams