【问题标题】:Use fetch with Identity Server 4将 fetch 与 Identity Server 4 一起使用
【发布时间】:2018-05-15 16:14:26
【问题描述】:

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

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

但是如何使用 [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 错误。 “内部服务器错误”

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

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

【问题讨论】:

  • 身份服务器日志说什么?
  • dbug: IdentityServer4.Validation.PostBodySecretParser[0] Start parsing for secret in post body crit: IdentityServer4.Hosting.IdentityServerMiddleware[0] Unhandled exception: System.IO.InvalidDataException: **Missing content-type boundary.** at Microsoft.AspNetCore.Http.Features.FormFeature.GetBoundary(MediaTypeHeaderValue contentType, Int32 lengthLimit) at Microsoft.AspNetCore.Http.Features.FormFeature. <InnerReadFormAsync>d__18.MoveNext() --- End of stack trace from previous location where exception was thrown ---
  • 当我从标题中删除“内容类型”时,它就可以工作了!我稍后会给出答案,但还要注意此代码来自与 request js 模块一起使用的复制/粘贴。 (请求覆盖传递的内容类型)

标签: javascript node.js identityserver4 fetch-api isomorphic-fetch-api


【解决方案1】:

正如我在之前的评论中提到的:如果您想使用Fetch 来发布带有表单数据的授权请求,则不得在标头中指定内容类型。由于fetch 将自动使用正确的值(“multipart/form-data”)填充它并添加动态生成的内容边界。 另请注意,您可以使用 URLSearchParams,如果您更喜欢使用 application/x-www-form-urlencoded 内容类型方法。

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2020-05-13
    • 2011-10-01
    • 2019-03-14
    相关资源
    最近更新 更多