Необработанный отказ (ошибка): не удалось загрузить настройки для «WebPortal» - ASP. NET Core React - PullRequest
3 голосов
/ 07 февраля 2020

Я создаю ASP. NET Core 3 React проект и получаю эту ошибку.

Необработанный отказ (ошибка): не удалось загрузить настройки для 'WebPortal'

GET https://localhost: 44367 / _configuration / WebPortal 401

Uncaught (в обещании) Ошибка: не удалось загрузить настройки для 'WebPortal'

в AuthorizeService.ensureUserManagerInitialized (AuthorizeService. js: 184)
в asyn c AuthorizeService.getUser (AuthorizeService. js: 24)
в asyn c AuthorizeService.isAuthenticated. js: 15)
в asyn c Promise.all (индекс 0)
в asyn c LoginMenu.populateState (LoginMenu. js: 26)

Здесь выскочила ошибка (AuthorizeService.js):

    async ensureUserManagerInitialized() {
        if (this.userManager !== undefined) {
            return;
        }

        let response = await fetch(ApplicationPaths.ApiAuthorizationClientConfigurationUrl);

        if (!response.ok) {
            throw new Error('Could not load settings for '${ApplicationName}');
        }

        let settings = await response.json();
        settings.automaticSilentRenew = true;
        settings.includeIdTokenInSilentRenew = true;
        settings.userStore = new WebStorageStateStore({
            prefix: ApplicationName
        });

        this.userManager = new UserManager(settings);
        this.userManager.events.addUserSignedOut(async () => {
            await this.userManager.removeUser();
            this.updateState(undefined);
        });
    }

Мой ApiAuthorizationConstants.js файл:

    export const ApplicationName = 'WebPortal';
    export const QueryParameterNames = {
      ReturnUrl: 'returnUrl',
      Message: 'message'
    };
    export const LogoutActions = {
      LogoutCallback: 'logout-callback',
      Logout: 'logout',
      LoggedOut: 'logged-out'
    };
    export const LoginActions = {
      Login: 'login',
      LoginCallback: 'login-callback',
      LoginFailed: 'login-failed',
      Profile: 'profile',
      Register: 'register'
    };
    const prefix = '/authentication';
    export const ApplicationPaths = {
       DefaultLoginRedirectPath: '/',
       ApiAuthorizationClientConfigurationUrl: '/_configuration/${ApplicationName}',
       ApiAuthorizationPrefix: prefix,
       Login: '${prefix}/${LoginActions.Login}',
       LoginFailed: '${prefix}/${LoginActions.LoginFailed}',
       LoginCallback: '${prefix}/${LoginActions.LoginCallback}',
       Register: '${prefix}/${LoginActions.Register}',
       Profile: '${prefix}/${LoginActions.Profile}',
       LogOut: '${prefix}/${LogoutActions.Logout}',
       LoggedOut: '${prefix}/${LogoutActions.LoggedOut}',
       LogOutCallback: '${prefix}/${LogoutActions.LogoutCallback}',
       IdentityRegisterPath: '/Identity/Account/Register',
       IdentityManagePath: '/Identity/Account/Manage'
     };

В консоли я вижу:

Error console

Кто-нибудь может мне помочь?

1 Ответ

1 голос
/ 07 февраля 2020

Согласно комментариям @Woodz и @Jack, я исследую проблему и выясняю ее. Проблема: Домашняя страница требуется авторизация. Я опубликую свое решение здесь, и оно может кому-то помочь.

Причина проблемы

В моем Startup.cs классе я включил авторизацию для всех контроллеров. См. Ниже код,

services.AddMvc(options => {

                //**************Add General Policy *********************
                //User need to be a Authorized system user to access pages except allowAnonymous annotation
                var generalPolicy = new AuthorizationPolicyBuilder()
                                           .RequireAuthenticatedUser()
                                           .Build();
                options.Filters.Add(new AuthorizeFilter(generalPolicy));
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());


            })

Решение

  • Изменить разрешение в OidcConfigurationController.cs (Добавить Разрешить анонимный аннотация ).

    [AllowAnonymous]
    public class OidcConfigurationController : Controller
    {
        private readonly ILogger<OidcConfigurationController> _logger;
    
        public OidcConfigurationController(IClientRequestParametersProvider 
          clientRequestParametersProvider, ILogger<OidcConfigurationController> 
         logger)
        {
            ClientRequestParametersProvider = clientRequestParametersProvider;
            _logger = logger;
         }
    
        public IClientRequestParametersProvider ClientRequestParametersProvider 
          { get; }
    
        [HttpGet("_configuration/{clientId}")]
        public IActionResult GetClientRequestParameters([FromRoute]string clientId)
        {
            var parameters = 
                     ClientRequestParametersProvider.GetClientParameters(HttpContext, 
                     clientId);
            return Ok(parameters);
        }
    }
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...