Home > Back-end >  ASP.NET Core 6.0 Web Application not redirecting to identity server on authorization
ASP.NET Core 6.0 Web Application not redirecting to identity server on authorization

Time:02-20

Setting up a simple testproject for MVC application with OpenIDConnect using IdentityServer4.

The Privacy view is set up with [Authorize], but when I try to navigate to it, it tries to redirect to the ASP.NET Identity page /Account/Login (which does not exist in the web app). It should redirect to the IdentityServer 4 project.

Program.cs

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  .AddCookie()
  .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme,
  options =>
  {
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Authority = "https://localhost:5001";
    options.ClientId = "testapplication";
    options.ClientSecret = "test";
    options.ResponseType = "code";
    options.Scope.Add("openid");
    //options.ResponseMode = "form_post";
    options.SaveTokens = true;
    options.UsePkce = true;
  });

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.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
 {
   endpoints.MapControllers();

 });

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

app.Run();

It should redirect to https://localhost:5001 (which is where the Identity Server is running), but it does not.

enter image description here

This is a Core 6.0 project, so there might be something which I am missing as I've used Core 3.1 examples.

CodePudding user response:

You need to configure authentication like this so that the authentication middleware knows what handler is in charge of what task.

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