下面是一个使用ASP.NET Core 8和Duende Identity Server进行认证的解决方案,包括OpenIdConnect、Cookies和JWT的代码示例。
首先,确保你已经安装了Microsoft.AspNetCore.Authentication
和Duende.IdentityServer
NuGet包。
在Startup.cs
文件中配置Identity Server和认证中间件:
using Duende.IdentityServer;
using Duende.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// 配置Identity Server
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients);
// 配置认证中间件
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://identityserver.example.com";
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
Config.cs
文件来定义API范围和客户端配置:using Duende.IdentityServer.Models;
public static class Config
{
public static IEnumerable ApiScopes => new List
{
new ApiScope("api1", "API 1")
};
public static IEnumerable Clients => new List
{
new Client
{
ClientId = "your-client-id",
ClientSecrets = { new Secret("your-client-secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RedirectUris = { "https://your-app.com/signin-oidc" },
PostLogoutRedirectUris = { "https://your-app.com/signout-callback-oidc" },
AllowedScopes = { "openid", "profile", "api1" },
AllowOfflineAccess = true
}
};
}
[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
@using Microsoft.AspNetCore.Authentication
@if (User.Identity.IsAuthenticated)
{
Welcome, @User.Identity.Name!
}
else
{
}
这是一个简单的使用ASP.NET Core 8和Duende Identity Server进行认证的示例。你可以根据自己的需求进行调整和扩展。