javascriptnode.jsidentityserver4fetch-apiisomorphic-fetch-api

Use fetch with Identity Server 4


How to use fetch with IdentityServer4 to get a JWT token, when using the resource owner password flow ? (which is not recommended most of the time).

Even if I should use the implicit flow, I want to use this flow because it's more convenienent in my situation for my spa application. First, you'll find usefull information here to implement your solution :

But how to use [fetch-api] to get a token from 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
    };

I should receive a JWT token in response but I receive an http 500 Error. "Internal Server Error"

If I trace HTTP headers with fiddler, I got the following result :

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

Solution

  • As I mentioned in my previous comment: If you want to use Fetch in order to POST an authorized request with form data, you must not specify the content-type into the header. Since fetch will automatically populate it with the correct value ("multipart/form-data") and add the dynamically generated content-boundary. Also note that you can use URLSearchParams, if you prefer use the application/x-www-form-urlencoded content-type method.