IdentityServer4实战详解
IDS4
一、参考文章
注意IDS4的版本与之前的版本有所不同,这些文档有些是旧版本,需要细微调整,会在下文给予标注
1.OAuth2.0和OCID讲解
IDS4官方文档
IDS4官方文档
晓晨Master的概念详解
概念理解
*Hunter的项目实战
实战项目
阮一峰的网络日志
阮一峰的网络日志
二、个人总结
基于使用的net6版本
1.Implicit隐式流程认证服务器端
Nuget包安装
(1)创建IDS4认证服务器和客户端
创建认证服务器MVC模板
创建MVC客户端(两个都选择MVC模板)
分别打开认证服务器和客户端的Propertieswen文件中launchSetting.json修改启动地址
客户端是5001 ,认证服务器设置为5000
项目启动以项目启动
(2)修改IDS4认证服务器的视图UI
- 进入认证服务器的项目的根目录,键入CMD界面
- 创建Ids4的UI界面
执行dotnet new is4ui --force,–force是强制覆盖原有的mvc文件,
如果没有模板,先下载模板, 1)安装模板命令:dotnet new -i IdentityServer4.Templates- 现在的目录结构
删除Controller文件因为Quickstart文件中也有HomeController,会有多个端点,出现错误
(3)添加资源配置
- 创建Config.cs文件
public static class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client(){
ClientId="client1",
ClientName="mvc client",
AllowedGrantTypes=GrantTypes.Implicit,
RedirectUris={"http://localhost:5001/signin-oidc"},
PostLogoutRedirectUris={"http://localhost:5001/signout-callback-oidc"},
FrontChannelLogoutUri = "http://localhost:5000/signout-idsrv",
AllowAccessTokensViaBrowser=true,
AllowedScopes=new List<string>{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}
};
}
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password"
},
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "password"
}
};
}
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
}
(4)Program配置(相当与3.1的Startup配置,6.0Startup类被删了)
Program.CS
var builder = WebApplication.CreateBuilder(args);
//部分浏览器版本较新SameSite不设置会出现报错,
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Lax;
options.OnAppendCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
static void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
if (options.SameSite == SameSiteMode.None)
{
var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
options.SameSite = SameSiteMode.Lax;
}
}
// Add services to the container.
//添加mvc,后面登录需要
builder.Services.AddMvc();
builder.Services.AddControllersWithViews();
//这部分是对资源的配置
builder.Services.AddIdentityServer()
//添加身份资源配置
.AddInMemoryIdentityResources(Config.GetIdentityResources())
//设置证书
.AddDeveloperSigningCredential()
//添加API资源设置
.AddInMemoryApiResources(Config.GetApiResources())
//推荐测试用户
.AddTestUsers(Config.GetUsers())
//添加客户端
.AddInMemoryClients(Config.GetClients());
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
2.Implicit隐式流客户端
(1)修改Program
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
options.OnAppendCookie = cookieContext =>
SetSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext =>
SetSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
//部分浏览器版本较新SameSite不设置会出现报错,
void SetSameSite(HttpContext httpContext, CookieOptions options)
{
if (options.SameSite == SameSiteMode.None)
{
if (httpContext.Request.Scheme != "https")
{
options.SameSite = SameSiteMode.Unspecified;
}
}
}
builder.Services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddMvc();
//AddAuthentication将认证服务添加到DI
builder.Services.AddAuthentication(options => {
options.DefaultScheme = "Cookies";//设置Cookies为主要认证手段
options.DefaultChallengeScheme = "oidc";//当需要登录时使用OpenID Connect方案
})
.AddCookie("Cookies")//使用AddCookie添加可以处理cookie的处理程序。
.AddOpenIdConnect("oidc", options => {
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "client1";
options.SaveTokens = true;
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
//添加Cookie,不让报错,无法正常使用
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
// 看登录的用户是否有权限
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
(2)添加认证特性
自带的HomeController中添加,当未登录用户访问触发认证流程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律