0

I am trying to integrate Azure AD B2C in the ASP.net core MVC application. It is showing the login page initially and when clicking on Login after entering username and password, it goes into a loop. When click on stop loading this page icon in the browser, it shows the home page An error occurred while processing your request. (Details Correlation failed).

output

Program.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios,      see https://aka.ms/aspnetcore-hsts.

app.UseHsts(); }

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();
app.UseAuthentication();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

in the console it showing below log repeatedly.

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10245: Creating claims identity from the validated token: '[PII of type 'Microsoft.IdentityModel.JsonWebTokens.JsonWebToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX21305: OpenIdConnectProtocolValidationContext.ProtocolMessage.Code is null, there is no 'code' in the OpenIdConnect Response to validate.

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX21310: OpenIdConnectProtocolValidationContext.ProtocolMessage.AccessToken is null, there is no 'token' in the OpenIdConnect Response to validate.

2

1 Answer 1

0

The below ASP .NET Core code is for authentication and authorization using Azure AD B2C. Microsoft Identity services are used for Azure AD B2C, and token acquisition is set up for downstream API calls. Thanks to @Sridevi for providing the link to Enable authentication in your own web app by using Azure AD B2C.

Startup.cs

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using TestApp.Infrastructure;
using TestApp.Proxy;

namespace TestApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
            
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
               
                options.HandleSameSiteCookieCompatibility();
            });

        

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"))
                .EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["TestService:Scopes"] })
                .AddDistributedTokenCaches();

            services.AddDistributedMemoryCache(); // for other options see https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization

            services.AddRazorPages()
                 .AddMicrosoftIdentityUI()
                 .AddMvcOptions(options => options.Filters.Add(typeof(ReauthenticationRequiredFilter)));

            services.AddOptions();
            services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C"));

            services.AddTransient<TestServiceProxy>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthentication();
            

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}


_Layout.cshtml

@using System.Security.Principal

<ul class="navbar-nav">
    @if (User.Identity.IsAuthenticated)
    {
        <li class="nav-item">
            <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="EditProfile">Edit Profile</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
    }
    else
    {
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
    }
</ul>

Created one Sign up and Sign In user flow named B2C_1_SUSI in B2C tenant like this:

enter image description here

Register one Azure AD B2C application and add redirect URI in Web platform:

enter image description here

appSettings.json:

{

  "AzureAdB2C": {
    "Instance": "https://b2ctenant.b2clogin.com",
    "Domain": "b2ctenant.onmicrosoft.com",
    "ClientId": "appId",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath": "/signout/user_flow_name",
    "SignUpSignInPolicyId": "user_flow_name",
    "ResetPasswordPolicyId": "B2C_1_PasswordReset",
    "EditProfilePolicyId": "B2C_1_ProfileEdit",
    // To call an API
    "ClientSecret": "secret",
    "ClientCertificates": [
    ]

  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "https://localhost:44349"
      }
    }
  },
  "TestService": {
    "BaseUrl": "https://localhost:5001",
    "Scopes": "openid"
  }
}


Output: enter image description here

enter image description here

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.