Search code examples
authenticationasp.net-core-mvcopenid-connectasp.net-core-5.0

How to get mvc pipeline to authenticate oidc in .net core 5


i'm trying to figure out a way to get mvc to authenticate AzureAD oidc token. My application is backend only, no sign in or sign out. so I want to get user claims from OnAuthorizationAsync(**AuthorizationFilterContext** context), but it always return empty in httpcontext. I would think it might be some sort of configuration issue in AddOpenIdConnect. The following is my settings in ConfigureServices. What need to be done for more to get the user claims?

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme
        //    options =>
        //{
        //    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        //    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //AuthorizationConstants.AuthenticationSchemes.Oidc
        //} //behave the same with or without this setting
        )
        .AddOpenIdConnect("oidc", options =>
        {
            options.ClientId = azureAdConfig.ClientId;
            options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(azureAdConfig.EntryUrl, new OpenIdConnectConfigurationRetriever());
        });



 Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // routing and other things
        app.UseAuthentication();
        app.UseAuthorization();
    }

Solution

  • What you have does not work at all. OpenIDConnect only handles the authentication part, but the received tokens are just lost in your setup. The second problem you have is that you don't mix JwtBearer with AddOpenIdConnect. JwtBearer is for the API that receives access tokens from the client.

    A proper skeleton for what you need to configure is:

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    }).AddCookie(opt =>
    {
    }).AddOpenIdConnect(options =>
    {
    });
    

    You should combine the OpenIDConnectHandler with the Cookie handler. Then it will work.

    See this article for more details: How do I implement Blazor authentication with OpenID Connect?

    To complement this answer, I wrote a blog post that goes into more detail about this topic: Debugging OpenID Connect claim problems in ASP.NET Core