Call to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an object

Viewed 4902

I am intending to get a bearer token via IdentityServer4 via my web project, and I am getting this exception. The exception is in the IdentityServer4 open source class library. The field url is null, and this causes the NullReference exception in the AddQueryString method, see https://github.com/IdentityServer/IdentityServer4/blob/master/src/Extensions/StringsExtensions.cs

The log files show;

IdentityServer4.Endpoints.AuthorizeEndpoint:Information: ValidatedAuthorizeRequest { "ClientId": "SIR", "ClientName": "SIR", "RedirectUri": "http://localhost:53200/signin-oidc", "AllowedRedirectUris": [ "https://localhost:44314", "http://localhost:53200/signin-oidc" ], "SubjectId": "anonymous", "ResponseType": "code id_token", "ResponseMode": "form_post", "GrantType": "hybrid", "RequestedScopes": "openid profile", "State": "OpenIdConnect.AuthenticationProperties=WBfqf-a6W0K-0x6giakJP1GCkjUyG0wzOgAr9AuitPNyUb6wsIlzJN-Yvv-ARRdTd5huJIIl3N0mpI95EbLzGKIVmAhXr4JiIWKo2dOCTFI7PH218T9V1vVkKP3kFmQgtRRYRagG9YEA2PvyMtxzQXMf4v3pPequ8Am7H_8TIfgMqspxAnTsXQ4K-cD_TBTVFc45AiDiylpWup1_Ovrpqu700JCGimHZJRuXP25MHMs", "Nonce": "636809130138863279.M2IyNTYyZTgtZTk0Ni00OWU5LWI4MmMtNGU2MWY4M2FkMzQzNzExYjRjYjYtOWY4MC00NjQwLWEyZGYtYzgzYjljZTY4ZDFj", "Raw": { "client_id": "SIR", "redirect_uri": "http://localhost:53200/signin-oidc", "response_mode": "form_post", "response_type": "id_token code", "scope": "openid profile", "state": "OpenIdConnect.AuthenticationProperties=WBfqf-a6W0K-0x6giakJP1GCkjUyG0wzOgAr9AuitPNyUb6wsIlzJN-Yvv-ARRdTd5huJIIl3N0mpI95EbLzGKIVmAhXr4JiIWKo2dOCTFI7PH218T9V1vVkKP3kFmQgtRRYRagG9YEA2PvyMtxzQXMf4v3pPequ8Am7H_8TIfgMqspxAnTsXQ4K-cD_TBTVFc45AiDiylpWup1_Ovrpqu700JCGimHZJRuXP25MHMs", "nonce": "636809130138863279.M2IyNTYyZTgtZTk0Ni00OWU5LWI4MmMtNGU2MWY4M2FkMzQzNzExYjRjYjYtOWY4MC00NjQwLWEyZGYtYzgzYjljZTY4ZDFj", "x-client-SKU": "ID_NET461", "x-client-ver": "5.3.0.0" } } IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator:Information: Showing login: User is not authenticated IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator:Information: Showing login: User is not authenticated IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator:Information: Showing login: User is not authenticated IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator:Information: Showing login: User is not authenticated Exception thrown: 'System.NullReferenceException' in IdentityServer4.dll Exception thrown: 'System.NullReferenceException' in IdentityServer4.dll 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.6\System.Diagnostics.StackTrace.dll'. Symbols loaded. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.6\System.Reflection.Metadata.dll'. Symbols loaded. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.6\System.IO.MemoryMappedFiles.dll'. Symbols loaded. IdentityServer4.Hosting.IdentityServerMiddleware:Critical: Unhandled exception: Object reference not set to an instance of an object.

System.NullReferenceException: Object reference not set to an instance of an object. at IdentityServer4.Extensions.StringExtensions.AddQueryString(String url, String query) in C:\local\identity\server4\IdentityServer4\src\Extensions\StringsExtensions.cs:line 197 at IdentityServer4.Endpoints.Results.LoginPageResult.ExecuteAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\Endpoints\Results\LoginPageResult.cs:line 61 at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 59 IdentityServer4.Hosting.IdentityServerMiddleware:Critical: Unhandled exception: Object reference not set to an instance of an object.

So in the AddQueryString method, the url is null. In my web client my startup method is;

public void Configuration(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = Settings.SignInAsAuthenticationType    // "Cookies";
    });

    app.UseOpenIdConnectAuthentication(openIdConnectOptions: new OpenIdConnectAuthenticationOptions
    {
        AuthenticationType = "oidc",
        Authority = Settings.AuthorityUrl,      //ID Server,  "https://localhost:44314/"; https://localhost:44307/
        ClientId = Settings.ClientId,           // "SIR"
        Scope = Settings.Scope,                 // "openid profile";
        ResponseType = Settings.ResponseType,   // "id_token code";
        SignInAsAuthenticationType = Settings.SignInAsAuthenticationType,
        //--------------------------------------// "Cookies";
        RedirectUri = Settings.RedirectUri,     // URL of website, http://localhost:53200/signin-oidc;
        RequireHttpsMetadata = Settings.RequireHttpsMetadata,
        //--------------------------------------// true
        ClientSecret = "secret"
    });

    app.Use(async (ctx, next) =>
    {
        var message = ctx.Authentication.User.Identity.IsAuthenticated
            ? $"User: {ctx.Authentication.User.Identity.Name}"
            : "User Not Authenticated";
        await next();
    });
}

Notice that I am using Microsoft.Owin

The client in my IdentityServer4 is;

public static IEnumerable<Client> Clients()
{
    return new[]
    {
        new Client
        {
            ClientId = "SIR",
            ClientName = "SIR",
            AllowedGrantTypes = GrantTypes.Hybrid,
            AllowedScopes = new[]
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile
            },
            RedirectUris = {
                "https://localhost:44314",
                "http://localhost:53200/signin-oidc"
            },
            ClientSecrets = { new Secret("secret".Sha256())}
        }
    };
}

Why is this and how do I fix this?

2 Answers

Add UserInteraction to AddIdentityServer. It will fix your problem.

 services.AddIdentityServer(options =>
    {
        options.UserInteraction = new UserInteractionOptions()
        {
            LogoutUrl = "/Identity/account/logout",
            LoginUrl = "/Identity/account/login",
            LoginReturnUrlParameter = "returnUrl"
        };
    })

As per the Identity Server 4 documentation, the default login URL is /account/login. I believe this error is given if that is not the correct URL for your login. In that case, you can specify the appropriate URL in the UserInteractionOptions which can be provided within AddIdentityServer.

services.AddIdentityServer(options =>
{
    options.UserInteraction = new UserInteractionOptions()
    {
        LogoutUrl = "Your/Route/To/Logout",
        LoginUrl = "Your/Route/To/Login",
        LoginReturnUrlParameter = "returnUrl"
    };
})

These routes should accept a string parameter containing the return URL, the name of which should match the LoginReturnUrlParameter property in the UserInteractionOptions.

Related