Authentication/login-failed

I am using Blazor WASM and recently I have started receiving the message below whenever my application starts up and try to redirect to the Auth0 Login Page to authenticate the anonymous user.

https://localhost:7001/authentication/login-failed

Hi @curtis.egiftit.admin,

Welcome to the Community!

Have you looked at your logs? There should be a more descriptive error that will help us narrow this down.

Here is a copy of the corresponding log:

{
“date”: “2021-04-25T12:29:28.935Z”,
“type”: “fsa”,
“description”: “Login required”,
“client_id”: “Io39Efod2PASXIqoqcdKx6h7Y9iwKc82”,
“client_name”: “eGiftit Web”,
“ip”: “63.143.95.134”,
“user_agent”: “Chrome 90.0.4430 / Windows 10.0.0”,
“details”: {
“body”: {},
“qs”: {
“client_id”: “Io39Efod2PASXIqoqcdKx6h7Y9iwKc82”,
“redirect_uri”: “https://localhost:5001/authentication/login-callback”,
“response_type”: “code”,
“scope”: “openid profile email profile”,
“state”: “78da08f1cdc64ff7b5dc2cf2bfb82359”,
“code_challenge”: “QZNUy5XBxsSWSoXslAwbA_cOeAgqxSYev8eo_Xb-rlA”,
“code_challenge_method”: “S256”,
“prompt”: “none”,
“response_mode”: “query”
},
“connection”: null,
“error”: {
“message”: “Login required”,
“oauthError”: “login_required”,
“type”: “oauth-authorization”
},
“riskAssessment”: null
},
“hostname”: “dev-egiftit-online.us.auth0.com”,
“audience”: “https://dev.api.egiftit.online”,
“scope”: [
“openid”,
“profile”,
“email”,
“profile”
],
“log_id”: “90020210425122931959427584582602715632670955469946224642”,
“_id”: “90020210425122931959427584582602715632670955469946224642”,
“isMobile”: false
}

This is a failed silent auth. It means that your application is trying to silently log in the user, usually with a cookie session, and that is failing.

This should fall back to the login page, where the user should authenticate.

I am running my application in VS 2019 with google chrome in incognito mode, how do I clear / end the cookie / session responsible? Because of this issue I have been unable to do any testing of the code I have written for weeks now. :frowning:

Can you share the details (code) of your Auth0 implementation?

Yes I can how do I send it (the entire project) to you? Until then see below:

appsettings.development.json

{
  "Auth0": {
    "Authority": "https://dev-egiftit-online.us.auth0.com",
    "ClientId": "XifqvR6oMxfAf6yNgRsIywgoyyIzZXi5",
  },
  "ApiBaseUrl": "https://localhost:6001",
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  }
}

Program.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Blazored.Toast;
using eGiftit.Components;
using eGiftit.Components.Extensions;
using eGiftit.Components.Services;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace eGiftit.Merchant
{
    public partial class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.Configuration["ApiBaseUrl"]) });

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Auth0", options.ProviderOptions);
                options.ProviderOptions.ResponseType = "code";
                options.ProviderOptions.DefaultScopes.Add("email");
            });

            builder.Services.AddScoped<IApiService,ApiService>();
            builder.Services.AddScoped<RegistrationJsInterop>();
            builder.Services.AddScoped<AppUtilJsInterop>();
            builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            builder.Services.AddBlazoredToast();

            await builder.Build().RunAsync();
        }
    }
}

_Imports.razor

@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.WebUtilities
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using System.ComponentModel.DataAnnotations
@using Microsoft.JSInterop
@using Microsoft.Extensions.Logging
@using eGiftit.Components
@using eGiftit.Components.Models
@using eGiftit.Components.Services
@using eGiftit.Components.Bootstrap
@using eGiftit.Merchant
@using eGiftit.Merchant.Models
@using eGiftit.Merchant.Components
@using eGiftit.Merchant.Shared
@using AutoMapper
@using Blazored.Toast
@using Blazored.Toast.Services

App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <Authorizing>
                    <p>Determining session state, please wait...</p>
                </Authorizing>
                <NotAuthorized>
                    @if (!context.User.Identity.IsAuthenticated)
                    {
                        <RedirectToLogin />
                    }
                    else
                    {
                        <h1>Sorry</h1>
                        <p>You're not authorized to access this page. You need to log in first.</p>
                    }
                    
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>  

RedirectToLogin.razor

@inject NavigationManager Navigation
@code {        
    
    protected override void OnParametersSet()
    {
      
        Navigation.NavigateTo("authentication/login");
    }
}

Authentication.razor

@page "/authentication/{action}"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Microsoft.Extensions.Configuration

@inject NavigationManager Navigation
@inject IConfiguration Configuration

<RemoteAuthenticatorView Action="@Action">
    <LogOut>
        @{
            var authority = Configuration["Auth0:Authority"];
            var clientId = Configuration["Auth0:ClientId"];

            Navigation.NavigateTo($"{authority}/v2/logout?client_id={clientId}");
        }
    </LogOut>
    <LogInFailed>
        <p>There was an error login you in: @_errorMessage</p>
    </LogInFailed>
</RemoteAuthenticatorView>

@code{
    [Parameter] public string Action { get; set; }
    string _errorMessage;

    protected override void OnParametersSet()
    {
        Uri uri = Navigation.ToAbsoluteUri(Navigation.Uri);
        if(QueryHelpers.ParseQuery(uri.Query).TryGetValue("message",out var message))
        {
            _errorMessage = message;
        }
    }
}

Thanks for providing that! It looks like you loosely. I am going to reach out to a teammate with more Blazor/C# experience and see if they will take a look.

Hi @curtis.egiftit.admin,
I’ve taken a quick look at your code and at first glance I didn’t find any particular issue. However, before going deeper with it, I’d like to highlight a few points:

  1. You are redirected to https://localhost:7001/authentication/login-failed but the base address of your redirect_uri parameter in the log is https://localhost:5001. So, it looks like your application listens to a different port than the one configured in Auth0. Usually this issue should give a different error message, but I’m pointing it out just to be sure your Auth0 configuration is correct.

  2. Have you tried to access your running app from a different browser? As @dan.woda mentioned, this issue usually depends on cookies. See this thread for more detailed info.

  3. Just in case the previous points don’t resolve the issue and I need to go deeper, which version of .NET are you using? Also, please, can you generate a HAR file for the HTTP messages exchanged by your application and Auth0 and share it with us?

Thank you :pray:

2 Likes

Hi @andrea.chiarelli ,

Thank you for your review of my code and the suggestions. I made the necessary clean up regarding the redirect Uri, and yes, I did try different browsers before coming to the community for help. Never-the-less, the problem persists.

However, I am happy to announced that I have discovered what the problem was. Here is how I solved it:

  1. Through a series of configuration changes on the Auth0 dashboard I concluded that problem was not with Auth0 and it was local with my implementation. I had it working before so what had change to cause this?

  2. Proceeded to google my error message :

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user.

  1. This lead me to some documentation on GitHub Getting Authorization failed error when upgrading Blazor to 5.0 with Azure ADB2C · Issue #20447 · dotnet/AspNetCore.Docs · GitHub the led me to realized that there were properties that I could play with on the Microsoft.AspNetCore.Authorization AddOidcAuthentication configuration.

  2. I proceeded to add two hard coded values and like magic everything started working again; the hard coded values were as as follows:

      builder.Services.AddOidcAuthentication(options =>
      {
           builder.Configuration.Bind("Auth0", options.ProviderOptions);
           options.ProviderOptions.ResponseType = "code";
           options.ProviderOptions.DefaultScopes.Add("email");
    
           **options.ProviderOptions.ClientId = "XifqvR6oMxfAf6yNgRsIywgoyyIzZXi5";**
           **options.ProviderOptions.Authority = "https://dev-egiftit-online.us.auth0.com";**
       });
    
  3. `Now I know what my problem was, for some reason the configuration values in appsettings.development.json was not being retrieved and applied properly. After reading about configuration settings and Blazor applications on docs.microsoft.com I realized that there was a environment (Production, Development, etc) and a naming convention baked into Blazor.

  4. A closer examination of my appsettings.development.json file made me realized that I had broken the naming convention by using a common d instead of a capital D in naming my file appsettings.Development.json. After making this change and removing the hard coded values I had previously added, the problem was resolved, and I was up and running once again.

Thank you @dan.woda and @andrea.chiarelli for being my rubber duck with this issue… :grin: :laughing:

2 Likes

Glad to hear this, @curtis.egiftit.admin and thanks for sharing! :pray:

Happy to have been your rubber duck! :duck: :joy:

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.