Vlado Pandžić
Vlado Pandžić

Reputation: 5048

How to authenticate web api in WPF app using Azure AD

I use this code inside my WPF app:

 var app = PublicClientApplicationBuilder.Create(_clientId)                                                
   .WithRedirectUri("http://localhost/")                                                  
   .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId).Build();

 try
        {
            result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

        }
        catch (MsalUiRequiredException)
        {
            return Result<UserMetadata>.NotAuthorized("There was on error");
        }

and it works great. Now I can call my WEB API and send "Bearer token" header to all endpoints. (Where token is access_token property I get from result)

In web api I just do:

 _ = services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

and it works.

However, I don't want all endpoints to be protected by this method (I have other auth mechanism) My idea is to get "code" variable somehow on client (the on that was set on browser window, but unfortunatelly not returned in my C# code as result), sent it on server and inside specific controller try to "login" user (get access_token from that code)

Reason is that I already have my own auth mechanism that is based on users table in my database.

Upvotes: 1

Views: 423

Answers (1)

Harshita Singh
Harshita Singh

Reputation: 4870

If I understand it correctly, you want to protect only selected API endpoints by using AD. You can certainly do this by setting up you Startup.cs like below:

services.AddAuthentication(options =>
              {
                  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
              })
                .AddJwtBearer("AAD", jwtOptions =>
                {
                    jwtOptions.Authority = $"{appConfiguration.AppSettings.AadInstance}/{appConfiguration.AppSettings.AadDomain}";
                    jwtOptions.Audience = appConfiguration.AppSettings.AadClientId;
                    jwtOptions.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = arg =>
                        {
                            // invoked if authentication fails
                            return Task.FromResult(0);
                        }
                    };
                    
                });
            
            services.AddAuthorization(options => 
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().AddAuthenticationSchemes("AAD").Build();

                options.AddPolicy("AAD", new AuthorizationPolicyBuilder().RequireAuthenticatedUser().AddAuthenticationSchemes("AAD").Build());
            });

And, add an attribute to the desired Controller/Action method to be protected like below:

[Authorize(Policy = "AAD")]

Upvotes: 1

Related Questions