question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Since v1 my login page is unreachable when user is not logged

See original GitHub issue

API Platform version(s) affected: 1.0.1

Description
Open a private tab and go to the page /admin You should be redirected to /login page (if you follow the documentation) since parseHydraDocumentation manage the HTTP 401 with a react redirect component But, you just land on /admin#/ page with the message Not Found Either you typed a wrong URL, or you followed a bad link..

How to reproduce
Just follow the official documentation. Here is my sample that is almost the same as the official

import React from "react";
import {HydraAdmin} from "@api-platform/admin";
import parseHydraDocumentation from '@api-platform/api-doc-parser/lib/hydra/parseHydraDocumentation';
import {dataProvider as baseDataProvider, fetchHydra as baseFetchHydra} from "@api-platform/admin";
import authProvider from './lib/authProvider';
import { Redirect } from 'react-router-dom';

const entrypoint = document.getElementById('api-entrypoint').innerText;
// Fetch api route with Http Basic auth instead of JWT Bearer system
const fetchHeaders = {"Authorization": `Basic ${btoa(`${localStorage.getItem('username')}:${localStorage.getItem('token')}`)}`};
const fetchHydra = (url, options = {}) => baseFetchHydra(url, {
    ...options,
    headers: new Headers(fetchHeaders),
});
const apiDocumentationParser = entrypoint => parseHydraDocumentation(entrypoint, { headers: new Headers(fetchHeaders) })
    .then(
        ({ api }) => ({api}),
        (result) => {
            switch (result.status) {
                case 401:
                    debugger
                    return Promise.resolve({
                        api: result.api,
                        customRoutes: [{
                            props: {
                                path: '/',
                                render: () => <Redirect to={`/login`}/>,
                            },
                        }],
                    });

                default:
                    return Promise.reject(result);
            }
        },
    );
const dataProvider = baseDataProvider(entrypoint, fetchHydra, apiDocumentationParser);

export default () => (
    <HydraAdmin
        apiDocumentationParser={ apiDocumentationParser }
        dataProvider={ dataProvider }
        authProvider={ authProvider }
        entrypoint={entrypoint}
        loginPage={MyLoginPage}
    />
);

Possible Solution
No solution for instance i don’t know why the route /login is not used. Maybe the redirect component is not understood by the app

Additional Context
I don’t know how to debug redirect component, that would have helped me to find a solution and fix it

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
gtgtcommented, Dec 5, 2019

Hi!

I do have. After a day of debugging, still not found the proper way to pass that route in customRoutes with the Promise to get executed. There are many contradictory info around: First, the documentation on api-platform.com is not in sync with documentation in api-platform source I believe, the first one is the right one, since hydraClient is not exists any more. This type of issue reports also adds to the confusion. Seems this changing quite fast. I decided that I try to find different way to handle this. So I took the advice: “Refer to the chapter dedicated to authentication in the React Admin documentation for more information.” At first look, I notice the differences in authProvider there, especially the “type” variable. Then found the “loginPage” (component) property on <Admin> (from ‘react-admin’). But when I looked into the api-platform/admin sources, I realised that it’s not implemented there. Then I found in one version of the authProvider.js the following: “Promise.reject({ redirectTo: ‘/no-access’ }),”. Nice, I try that. No working, since the “AUTH_ERROR” not even called. Then I found why: because we are returning Promise.resolve() when our parseHydraDocumentation wrapper finds 401 error. So I removed that “if” clause to return reject() instead. Vioala, AUTH_ERROR runs, and the react-admin catches the “redirectTo” property in Promise.reject() argument.

So the apiDocumentationParser wrapper in Admin component looks like this:

const apiDocumentationParser = entrypoint => parseHydraDocumentation(entrypoint, { headers: new Headers(fetchHeaders) })
    // you can even remove the whole (".then()")
    .then(
        ({ api }) => ({ api }),
        result => {
            // console.warn(result);
            return Promise.reject(result);
        },
    );

and the AUTH_ERROR and AUTH_CHECK (yes, we can redirect earlier, so not need to perform unnecessary request without Authorization header) in authProvider.js looks like this:

    case AUTH_ERROR:
        if (401 === params.status || 403 === params.status) {
            localStorage.removeItem('token');
            return Promise.reject({ redirectTo: '/login' });
        }
        console.error(params);
        break;

    case AUTH_CHECK:
        return localStorage.getItem('token') ? Promise.resolve() : Promise.reject({ redirectTo: '/login' });

If I will have some time, I’ll make a PR maybe to update documentation, since I think this way is cleaner, easier.

1reaction
luispaboncommented, Nov 25, 2020

Thank you @Rebolon 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

Web Admin Login Error (There was an error, please try again)
The error prevents users from logging in to the Web Portal. The Admin Console may also be unavailable or it may be working...
Read more >
Failed to login Prism Central with username "admin" due to ...
The Prism Central login page shows error "Server is not reachable" after submitting credentials. A reboot of Prism Central VM does not recover ......
Read more >
Why can't I login to the web management utility of range ...
Why can't I login to the web management utility of range extender? · Step 1 · Step 2: Reset to the factory defaults...
Read more >
Application response codes, login events, and errors
Description: The end user is not allowed to access the application. ... not exist. Possible solution: Check if request URL is available in...
Read more >
403 Forbidden Error: What It Is and How to Fix It - Airbrake Blog
If the application you're using has some form of user authentication, the last client-side step to try is to log out and then...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found