title: Authentication with oidc-client.js and Identityserver4 in a React frontend
body: <p>Lately I'm trying to set-up authentication using IdentityServer4 with a React client. I followed the <code>Adding a JavaScript client</code> tutorial (partly) of the IdentityServer documentation: <a href="https://media.readthedocs.org/pdf/identityserver4/release/identityserver4.pdf" rel="noreferrer">https://media.readthedocs.org/pdf/identityserver4/release/identityserver4.pdf</a> also using the <code>Quickstart7_JavaScriptClient</code> file.</p>
  
  <p>The downside is that I'm using React as my front-end and my knowledge of React is not good enough to implement the same functionality used in the tutorial using React. </p>
  
  <p>Nevertheless, I start reading up and tried to get started with it anyway. My IdentityServer project and API are set-up and seem to be working correctly (also tested with other clients). </p>
  
  <p>I started by adding the oidc-client.js to my Visual Code project. Next I created a page which get's rendered at the start (named it Authentication.js) and this is the place where the Login, Call API and Logout buttons are included. This page (Authentication.js) looks as follows:</p>
  
  <pre><code>import React, { Component } from 'react';
  import {login, logout, api, log} from '../../testoidc'
  import {Route, Link} from 'react-router';
  
  export default class Authentication extends Component {
      constructor(props) {
        super(props);
      }
  
      render() {
        return (
          &lt;div&gt;
              &lt;div&gt;  
                  &lt;button id="login" onClick={() =&gt; {login()}}&gt;Login&lt;/button&gt;
                  &lt;button id="api" onClick={() =&gt; {api()}}&gt;Call API&lt;/button&gt;
                  &lt;button id="logout" onClick={() =&gt; {logout()}}&gt;Logout&lt;/button&gt;
  
                  &lt;pre id="results"&gt;&lt;/pre&gt;
  
              &lt;/div&gt;  
  
              &lt;div&gt;
                  &lt;Route exact path="/callback" render={() =&gt; {window.location.href="callback.html"}} /&gt;
  
                  {/* {&lt;Route path='/callback' component={callback}&gt;callback&lt;/Route&gt;} */}
              &lt;/div&gt;
          &lt;/div&gt;
        );
      }
    }
  </code></pre>
  
  <p>In the testoidc.js file (which get's imported above) I added all the oidc functions which are used (app.js in the example projects). The route part should make the callback.html available, I have left that file as is (which is probably wrong). </p>
  
  <p>The testoidc.js file contains the functions as follow:</p>
  
  <pre><code>import Oidc from 'oidc-client'
  
  
  export function log() {
    document.getElementById('results').innerText = '';
  
    Array.prototype.forEach.call(arguments, function (msg) {
        if (msg instanceof Error) {
            msg = "Error: " + msg.message;
        }
        else if (typeof msg !== 'string') {
            msg = JSON.stringify(msg, null, 2);
        }
        document.getElementById('results').innerHTML += msg + '\r\n';
    });
  }
  
  var config = {
    authority: "http://localhost:5000",
    client_id: "js",
    redirect_uri: "http://localhost:3000/callback.html",
    response_type: "id_token token",
    scope:"openid profile api1",
    post_logout_redirect_uri : "http://localhost:3000/index.html",
  };
  var mgr = new Oidc.UserManager(config);
  
  mgr.getUser().then(function (user) {
    if (user) {
        log("User logged in", user.profile);
    }
    else {
        log("User not logged in");
    }
  });
  
  export function login() {
    mgr.signinRedirect();
  }
  
  export function api() {
    mgr.getUser().then(function (user) {
        var url = "http://localhost:5001/identity";
  
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.onload = function () {
            log(xhr.status, JSON.parse(xhr.responseText));
        }
        xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
        xhr.send();
    });
  }
  
  export function logout() {
    mgr.signoutRedirect();
  } 
  </code></pre>
  
  <p>There are multiple things going wrong. When I click the login button, I get redirected to the login page of the identityServer (which is good). When I log in with valid credentials I'm getting redirected to my React app: <a href="http://localhost:3000/callback.html#id_token=Token" rel="noreferrer">http://localhost:3000/callback.html#id_token=Token</a></p>
  
  <p>This client in the Identity project is defined as follows:</p>
  
  <pre><code>new Client
                  {
                      ClientId = "js",
                      ClientName = "JavaScript Client",
                      AllowedGrantTypes = GrantTypes.Implicit,
                      AllowAccessTokensViaBrowser = true,
  
                      // where to redirect to after login
                      RedirectUris = { "http://localhost:3000/callback.html" },
  
                      // where to redirect to after logout
                      PostLogoutRedirectUris = { "http://localhost:3000/index.html" },
  
                      AllowedCorsOrigins = { "http://localhost:3000" },
                      AllowedScopes =
                      {
                          IdentityServerConstants.StandardScopes.OpenId,
                          IdentityServerConstants.StandardScopes.Profile,
                          "api1"
                      }
  
                  }
  </code></pre>
  
  <p>Though, it seems the callback function is never called, it just stays on the callback url with a very long token behind it..</p>
  
  <p>Also the getUser function keeps displaying 'User not logged in' after logging in and the Call API button keeps saying that there is no token. So obviously things are not working correctly. I just don't know on which points it goes wrong. 
  When inspecting I can see there is a token generated in the local storage: </p>
  
  <p><a href="https://i.stack.imgur.com/8qmHe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8qmHe.png" alt="enter image description here"></a></p>
  
  <p>Also when I click the logout button, I get redirected to the logout page of the Identity Host, but when I click logout there I don't get redirected to my client.</p>
  
  <p><strong>My questions are:</strong></p>
  
  <ul>
  <li>Am I on the right track implementing the oidc-client in combination with IdentityServer4? </li>
  <li>Am I using the correct libraries or does react require different libraries than the oidc-client.js one.</li>
  <li>Is there any tutorial where a react front-end is used in combination with IdentityServer4 and the oidc-client (without redux), I couldn't find any. </li>
  <li>How / where to add the callback.html, should it be rewritten? </li>
  </ul>
  
  <p>Could someone point me in the right direction, there are most likely more things going wrong here but at the moment I am just stuck in where to even begin. </p>