还在为各个系统之间的身份认证问题头疼吗?是不是厌倦了在不同项目中重复编写登录逻辑?或者你的微服务架构中,用户信息分散各处,难以统一管理?今天我要介绍的IdentityServer4可能就是你一直在寻找的解决方案!
IdentityServer4是一个基于ASP.NET Core的开源认证框架,它实现了OpenID Connect和OAuth 2.0协议。简单来说,它就是一个强大的身份认证服务器,可以集中处理所有的认证和授权问题。(超级实用!)
这篇教程将带你从零开始搭建一个IdentityServer4服务,并且实现基本的身份认证功能。不管你是微服务架构的拥趸,还是正在构建SPA应用,这篇文章都能帮你解决认证难题。
在深入学习之前,我们先来聊聊为什么需要一个专门的身份认证服务器。
传统的Web应用通常是这样处理身份认证的:每个应用都有自己的用户数据库,实现自己的登录页面,管理自己的会话状态。这在单体应用时代还算可行,但在现代分布式系统中就显得非常低效了。
想象一下,你有5个不同的应用,用户在每个应用都需要单独注册、登录。这不仅用户体验差,开发和维护成本也高得吓人!
IdentityServer4的出现就是为了解决这个问题。它提供了:
如果你正在构建微服务架构或者维护多个应用,IdentityServer4绝对是你不能错过的技术!
在开始动手之前,我们需要了解IdentityServer4中的几个核心概念:
资源是你想要保护的东西,分为两类:
```csharp // 身份资源的例子 new IdentityResources.OpenId(), new IdentityResources.Profile()
// API资源的例子 new ApiResource("myApi", "我的API") { Scopes = { "api1.read", "api1.write" } } ```
客户端是请求访问资源的应用程序。可以是网站、手机APP、桌面应用等。
csharp new Client { ClientId = "myWeb", ClientName = "我的Web应用", AllowedGrantTypes = GrantTypes.Code, ClientSecrets = { new Secret("secret".Sha256()) }, RedirectUris = { "https://myapp.com/callback" }, AllowedScopes = { "openid", "profile", "api1.read" } }
作用域定义了客户端可以请求的访问权限范围。
csharp new ApiScope("api1.read", "读取数据的权限"), new ApiScope("api1.write", "写入数据的权限")
这个就不用多说了,就是你系统中的用户。在IdentityServer4中,用户通常由ASP.NET Core Identity管理,或者你可以自定义存储。
理解了这些概念,我们就可以开始动手实践了!
在开始之前,确保你已经安装了:
好了,工具准备完毕,让我们开始吧!
首先,我们需要创建一个ASP.NET Core项目作为我们的IdentityServer宿主:
bash dotnet new web -n IdentityServer cd IdentityServer
然后添加IdentityServer4包:
bash dotnet add package IdentityServer4
接下来,我们需要在Startup.cs中配置IdentityServer4服务。编辑Startup.cs文件:
```csharp public void ConfigureServices(IServiceCollection services) { // 添加IdentityServer服务 services.AddIdentityServer() .AddInMemoryIdentityResources(Config.IdentityResources) .AddInMemoryApiScopes(Config.ApiScopes) .AddInMemoryClients(Config.Clients) .AddTestUsers(Config.Users) // 在开发环境使用临时密钥 .AddDeveloperSigningCredential(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
} ```
我们需要一个单独的配置类来定义资源、客户端和用户。在项目根目录创建一个Config.cs文件:
```csharp using IdentityServer4.Models; using IdentityServer4.Test; using System.Collections.Generic; using System.Security.Claims;
public static class Config { public static IEnumerable IdentityResources => new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email() };
} ```
这里我们定义了:
注意,这里的用户是内存中的测试用户,实际生产环境中你应该使用数据库存储用户信息。
IdentityServer4默认没有提供UI界面,我们需要自己添加登录、注销等页面。幸运的是,IdentityServer团队提供了一个快速入门UI模板。
在项目根目录运行以下命令:
```bash // 安装模板 dotnet new -i IdentityServer4.Templates
// 添加UI页面 dotnet new is4ui ```
这会为我们添加一系列视图、控制器和样式,提供基本的登录、注销和授权页面。
现在我们的Startup.cs需要添加MVC支持:
```csharp public void ConfigureServices(IServiceCollection services) { // 添加MVC服务 services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ...之前的代码
} ```
现在我们已经完成了IdentityServer4的基本配置!让我们运行服务器看看效果:
bash dotnet run
服务器应该会在https://localhost:5001上启动。访问这个地址,应该能看到一个简单的页面。
接下来,访问https://localhost:5001/.well-known/openid-configuration,你应该能看到一个JSON文档,这是OpenID Connect的发现文档,包含了服务器的各种端点信息。如果你能看到这个文档,说明IdentityServer4已经成功配置了!
现在我们有了身份服务器,但还需要一个客户端应用来测试它。让我们创建一个简单的MVC应用作为客户端:
bash dotnet new mvc -n MvcClient cd MvcClient
添加认证包:
bash dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
然后在Startup.cs中配置认证:
```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ...常规配置代码
} ```
最后,让我们创建一个需要认证的控制器:
```csharp using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc;
public class SecureController : Controller { [Authorize] public IActionResult Index() { return View(); } } ```
创建对应的视图(Views/Secure/Index.cshtml):
```html @{ ViewData["Title"] = "安全页面"; }
你现在可以看到这个受保护的页面,因为你已经通过IdentityServer4认证了。
用户名: @User.Identity.Name
```
在_Layout.cshtml中添加链接:
```html
```
现在运行MvcClient:
bash dotnet run
客户端应该会在https://localhost:5002上启动。点击"安全页面"链接,你应该会被重定向到IdentityServer4的登录页面。使用我们之前定义的用户(alice/Pass123$)登录,然后你应该会被重定向回客户端应用的安全页面,显示你已经认证成功!
最后一步,让我们创建一个API项目,并使用IdentityServer4保护它:
bash dotnet new webapi -n Api cd Api
添加验证包:
bash dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
配置Startup.cs:
```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ...常规配置代码
} ```
然后在控制器上添加授权特性:
csharp [ApiController] [Route("[controller]")] [Authorize("ApiScope")] public class WeatherForecastController : ControllerBase { // ...控制器代码 }
运行API:
bash dotnet run
API应该会在https://localhost:5003上启动。现在你需要获取一个访问令牌才能访问API。这个令牌需要从IdentityServer4获取,可以通过我们的MVC客户端应用来测试。
恭喜你!你已经成功搭建了一个完整的IdentityServer4认证系统,包括:
这只是一个基础的入门示例,IdentityServer4还有很多高级功能,比如:
随着你的系统复杂度增加,IdentityServer4可以为你提供强大的身份认证基础设施,帮助你构建安全、可扩展的应用程序。
希望这篇教程对你有所帮助!如果你想深入学习IdentityServer4,官方文档是最好的资源。动手尝试,才能真正掌握这个强大的框架!
A: IdentityServer4是一个认证服务器,实现了OpenID Connect和OAuth 2.0协议,主要负责认证用户并发放令牌。而ASP.NET Core Identity是一个用户管理系统,负责用户注册、密码重置等功能。两者可以结合使用,IdentityServer4使用ASP.NET Core Identity作为用户存储。
A: 是的,IdentityServer4可以支持多租户架构。你可以通过自定义存储实现多租户,或者为每个租户部署一个单独的IdentityServer实例。
A: 主要包括: - 在生产环境中使用持久化的签名密钥 - 使用HTTPS保护所有通信 - 妥善保管客户端密钥 - 定期轮换密钥 - 实施适当的日志和监控
记住,安全是一个持续的过程,而不是一次性的工作!
希望这篇教程能帮助你开始使用IdentityServer4!不断实践才能掌握这个强大的工具。祝你的项目成功!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。