ASP.NET Core 8 和 Duende Identity Server 认证方案(OpenIdConnect、Cookies、JWT)
创始人
2024-09-15 03:01:09
0

下面是一个使用ASP.NET Core 8和Duende Identity Server进行认证的解决方案,包括OpenIdConnect、Cookies和JWT的代码示例。

  1. 首先,确保你已经安装了Microsoft.AspNetCore.AuthenticationDuende.IdentityServer NuGet包。

  2. 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();
        });
    }
}
  1. 创建一个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
        }
    };
}
  1. 在控制器中添加一个需要认证的路由:
[Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
  1. 在视图中添加一个链接来触发认证过程:
@using Microsoft.AspNetCore.Authentication

@if (User.Identity.IsAuthenticated)
{
    

Welcome, @User.Identity.Name!

} else {

Login

}

这是一个简单的使用ASP.NET Core 8和Duende Identity Server进行认证的示例。你可以根据自己的需求进行调整和扩展。

相关内容

热门资讯

避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...