Duende.IdentityServer

~依稀 / 2024-10-23 / 原文

服务端安装 install-package Duende.IdentityServer

客户端 install-package IdentityModel

webapi  基于jwt 需要安装 install-package Microsoft.AspNetCore.Authentication.JwtBearer

 

在 IdentityServer 中启用OIDC需要

  • 交互式用户界面 dotnet new isui
  • OIDC范围的配置

    public static IEnumerable<IdentityResource> IdentityResources => new IdentityResource[]
    {
    // 创建一个IdentityResources.OpenId类型的IdentityResource对象
    new IdentityResources.OpenId(),
    // 创建一个IdentityResources.Profile类型的IdentityResource对象
    new IdentityResources.Profile(),
    };

  • OIDC客户端的配置

    new Client
    {
    ClientId = "web",
    ClientSecrets = {new Secret("secret".Sha256())},
    AllowedGrantTypes = GrantTypes.Code,
    RedirectUris = { "https://localhost:5002/signin-oidc" },
    PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },
    AllowedScopes = new List<string>
    {
    IdentityServerConstants.StandardScopes.OpenId,
    IdentityServerConstants.StandardScopes.Profile
    }
    }

  • 要登录的用户

    public static List<TestUser> TestUsers => new List<TestUser>
    {
    // 创建一个TestUser对象,并设置其属性
    new TestUser
    {
    SubjectId = "1", // 设置SubjectId属性为"1"
    Username = "admin", // 设置Username属性为"admin"
    Password = "123456" // 设置Password属性为"123456"
    }
    };

创建OIDC客户端

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect

配置身份验证服务

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "web";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.MapInboundClaims = false;
options.SaveTokens = true;
});