Search code examples
c#asp.netauthenticationasp.net-coreaspnet-contrib

Retrieving claims in asp.net core using open id connect server


I'm about to implement bearer based authentication in my asp.net core app. Coming from .NET Framework, the core stuff is still quite new to me. Getting a token from server does already work great. But how can I in following request determine if a user is authenticated? In .NET Framework projects, I used to use

(ClaimsIdentity)Thread.CurrentPrincipal.Identity.IsAuthenticated;

However, this returns an identity with empty or default claims. This is my setup so far:

I've started with the OpenIdConnect.Server framework and the sample code in their Get Started section. This works great, and my client recieves a Bearer Token. I've build it in my Startup.cs in the following way:

public class Startup
{
    [...]

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddMvc();
        services.AddAuthentication();
        [...]
    }

    public void Configure([...])
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc();
        app.UseOpenIdConnectServer(options =>
        {
            [code of example]
        }
    }

On client side, I use the retrieved token for further requests

The Bearer Token is transmitted in the header.

Now, how do I now access the current logged in users claims or how do I know if he/she is authenticated?

I have tried

// within api controller:
var isAuth = this.User.Identity.IsAuthenticated

// using DI
public class MyClass(IHttpContextAccessor httpContextAccessor) {
    public void MyMethod() {
        var isAuth = httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
    }
}

But this always returns false and the claims are some default values. Am I missing something? Do I need to install some additional service or middleware?


Solution

  • One thing to note with the OpenID Connect server middleware is that it doesn't validate incoming access tokens for you (it only issues them). Since you're using the default token format (encrypted), you can use the AspNet.Security.OAuth.Validation package for that:

    public class Startup
    {
        [...]
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc();
            services.AddAuthentication();
            [...]
        }
    
        public void Configure([...])
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseOpenIdConnectServer(options =>
            {
                [code of example]
            });
            app.UseOAuthValidation();
            app.UseMvc();
        }
    }