使用 IdentityServer4 為帶有 OpenIDConnect 的 MVC 應用程式設定一個簡單的測驗專案。
隱私視圖是使用 [Authorize] 設定的,但是當我嘗試導航到它時,它會嘗試重定向到 ASP.NET 身份頁面 /Account/Login(在 Web 應用程式中不存在)。它應該重定向到 IdentityServer 4 專案。
程式.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();
它應該重定向到 https://localhost:5001(身份服務器正在運行的地方),但它沒有。

這是一個 Core 6.0 專案,所以在我使用 Core 3.1 示例時可能會遺漏一些東西。
uj5u.com熱心網友回復:
您需要像這樣配置身份驗證,以便身份驗證中間件知道哪個處理程式負責什么任務。
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(...)
.AddOpenIdConnect(....)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428795.html
