源视频教程:https://www.bilibili.com/video/BV1Qa4y1n7bb IdentityServer4官网文档:https://identityserver4.readthedocs.io/en/latest/index.html

一、OAuth2.0与OpenID

OAuth2.0:是一种授权协议
OpenID:认证协议

1.1-【推荐:授权码许可】场景一:小明——第三方软件(软文系统)——微信开放平台

image.png
四种角色:资源拥有者(小明)、客户端应用(第三方平台-软文系统软文系统、授权服务(微信开放平台)、受保护资源(小明在微信公众号中的文章)
image.png
授权码——>临时的,安全性不高,一次性的,很短的有效期
访问令牌——>权限很高,访问用户资料,有效期比授权码长很多
刷新令牌——>刷新访问令牌,先调用刷新接口,然后返回的新的访问令牌;有 有效期,但是有效期比较长。
两个措施:
(1)刷新令牌必须保存在客户端的服务器上(软文系统的服务器上),调用刷新接口的时候,必须是第三方应用的后端服务器到授权服务器的访问。
(2)每一个第三方应用,必须在授权服务器注册自己的信息。

直接通信:通过授权码换取访问令牌的交互
image.png
间接通信:获取授权码的交互
image.png

1.2-【推荐:资源拥有者凭据许可】场景二:软文系统是微信的一个子系统

资源拥有者凭据(用户名和密码)许可:小明是微信的用户,然后直接可以使用微信的用户名和密码,去使用软文系统。使用访问令牌代替用户名和密码,保护敏感数据;用一次用户名和密码去换取访问令牌。
image.png

1.3-【客户端凭据许可】场景三:没有明确的资源拥有者情况,如访问网站的logo

第三方应用就是资源拥有者本身,这样的话第三方引用就会在授权服务中心去注册自己的身份信息,然后的到应用ID和应用秘钥。然后通过应用ID和引用秘钥去换取访问令牌。
image.png

1.4-【隐式许可类型】场景四:就是一个前端应用/桌面应用/APP/工具

安全性极低,相当于没有安全性;加入一个纯JS引用,不需要秘钥,也不需要授权码了,只需要通过第三方 应用ID 获取即可。

1.5-四种许可类型的区别

其实就是获取令牌的方式不同。
image.png

OpenID:认证和证明——知乎使用QQ登录——>QQ登录页面——>认证——>登录。
OAuth:授权和许可——授权页面——>两个复选框——>用户数据(昵称/头像)——>知乎。
OpenID Connect(OIDC):是认证和授权的结合

1.6-OpenID Connect

image.png

EU=End User:终端用户(实际的用户)
RP=Relying Party:受信任的客户端(身份认证的消费房)
OP=授权服务(身份认证+授权服务的结合)
ID Token=身份令牌,是授权服务器提供包含用户信息JWT格式的数据结构。
AuthN:认证
AuthZ:授权
image.png

1.7-IdentityServer4有什么用?

  1. 身份验证服务器
  2. 单点登录/注销
  3. API的访问控制

二、IdentityServer4实战

2.1-IdentityServer4项目的创建

环境: 目标框架:.NET Core 3.1 IdentityServer4使用版本:v4.1.1

(1)新建一个Web应用程序的项目【Sample.IdentityServer4】
image.png
(2)安装IdentityServer4的Nuget包。
image.png
(3)在【Properties/launchSettings.json】修改端口,方便后期使用是区分。
image.png
(4)新建一个静态Config类,用来配置受保护的API范围,然后使用中间件的形式将Config添加到ASP.NET Core的管道中。

  1. /// <summary>
  2. /// 定义一个静态Config类
  3. ///
  4. /// 配置受保护的API范围,哪些客户端可以使用这些被保护的API
  5. ///
  6. /// IdentityServer4是以中间件形式添加到ASP.NET Core的管道中
  7. /// </summary>
  8. public static class Config
  9. {
  10. /*
  11. * API范围
  12. * ApiScope=分组
  13. */
  14. public static IEnumerable<ApiScope> ApiScopes => new[]{
  15. new ApiScope{
  16. Name="Sample_Api",//API范围的名称
  17. DisplayName="Sample API"//显示名称
  18. }
  19. };
  20. /*
  21. * 客户端应用
  22. 哪些客户端可以使用这些被保护的API
  23. */
  24. public static IEnumerable<Client> Clients => new[] {
  25. //客户端1:客户端凭据
  26. new Client
  27. {
  28. ClientId="sample_clientid",//应用ID
  29. //应用秘钥
  30. ClientSecrets =
  31. {
  32. new Secret("sample_client_seret".Sha256())
  33. },
  34. //指定凭证许可模式
  35. AllowedGrantTypes=GrantTypes.ClientCredentials,//客户端凭证许可
  36. //允许访问API范围
  37. AllowedScopes={ "Sample_Api"}
  38. },
  39. //客户端2:资源拥有者凭据
  40. new Client
  41. {
  42. ClientId="sample_clientid_password",//应用ID
  43. //应用秘钥
  44. ClientSecrets =
  45. {
  46. new Secret("sample_client_seret".Sha256())
  47. },
  48. //指定凭证许可模式
  49. AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,//用户名密码凭证许可
  50. //允许访问API范围
  51. AllowedScopes={ "Sample_Api"}
  52. },
  53. //客户端3:OIDC客户端【例子:Sample.MVCClient】
  54. new Client
  55. {
  56. ClientId="sample_clientid_mvc",//应用ID
  57. ClientName="Sample_MVC_Client",
  58. //应用秘钥
  59. ClientSecrets =
  60. {
  61. new Secret("sample_client_seret".Sha256())
  62. },
  63. //指定凭证许可模式
  64. AllowedGrantTypes=GrantTypes.Code,//授权码Code凭证许可方式
  65. RedirectUris={ "http://localhost:4001/signin-oidc"},//回调地址(登录重定向)
  66. PostLogoutRedirectUris={ "http://localhost:4001/signout-callback-oidc"},//回调地址(登出重定向)
  67. //允许访问API范围(配置哪些资源可以被授权)
  68. AllowedScopes={
  69. //需要用户授权的内容
  70. IdentityServerConstants.StandardScopes.OpenId,
  71. IdentityServerConstants.StandardScopes.Profile,
  72. "Sample_Api"
  73. },
  74. RequireConsent=true//是否需要用户进行"同意"
  75. }
  76. };
  77. //配置身份资源
  78. public static IEnumerable<IdentityResource> IdentityResources => new List<IdentityResource> {
  79. new IdentityResources.OpenId(),//必须被保护的
  80. new IdentityResources.Profile()//昵称、头像等基本信息
  81. };
  82. //配置测试用户
  83. public static List<TestUser> Users = new List<TestUser> {
  84. new TestUser{
  85. SubjectId="1",
  86. Username="admin",
  87. Password="123"
  88. }
  89. };
  90. }

(4)在Startup.cs类中进行配置,将Config添加到ASP.NET Core的管道中。

  1. public class Startup
  2. {
  3. // This method gets called by the runtime. Use this method to add services to the container.
  4. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  5. public void ConfigureServices(IServiceCollection services)
  6. {
  7. //注册IdentityServer4服务
  8. var builder = services.AddIdentityServer();
  9. builder.AddDeveloperSigningCredential();//开发环境,自动生成秘钥
  10. //内存形式进行添加
  11. builder.AddInMemoryClients(Config.Clients);
  12. builder.AddInMemoryApiScopes(Config.ApiScopes);
  13. builder.AddInMemoryIdentityResources(Config.IdentityResources);
  14. builder.AddTestUsers(Config.Users);
  15. }
  16. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  17. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  18. {
  19. if (env.IsDevelopment())
  20. {
  21. app.UseDeveloperExceptionPage();
  22. }
  23. //将IdentityServer4添加到管道中(包含认证功能)
  24. app.UseIdentityServer();
  25. }
  26. }

(5)然后运行项目,使用postman进行测试输入以下命令进行测试。
image.png
//5.1-测试文档是否能正常打开:

Get请求: http://localhost:6002/.well-known/openid-configuration

image.png
//5.2-测试能不能使用客户端获取到Token:

Post请求: http://localhost:6002/connect/token

入参(看Config.cs怎么配置的,这里使用【客户端1:客户端凭据】作为例子): 1.client_id:客户端ID 2.client_secret:客户端秘钥 3.grant_type:凭证许可模式

image.png
//access_token解析出来具体内容如下:
image.png

2.2-IdentityServer4-MVC模板的创建

IdentityServer4提供了一个快速入门的界面,包含一个简单的入门用户界面,包括登录、注销和同意页面。

(1)使用Git方式进行安装,打开链接然后将代码拉取下来:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
(2)拉取下来之后,然后将这3个文件夹拷贝到项目中。
image.png
(3)然后在Startup中注册相关信息。
image.png
(4)运行项目可以看到这个界面说明成功了。
image.png

2.3-创建一个【Sample.WebAPI】受保护资源的WebAPI项目

(1)在【Properties/launchSettings.json】修改端口,方便后期使用是区分。
image.png
(2)需要导入两个包。
image.png
(3)在Startup.cs写入以下代码。

  1. public class Startup
  2. {
  3. // This method gets called by the runtime. Use this method to add services to the container.
  4. public void ConfigureServices(IServiceCollection services)
  5. {
  6. services.AddControllers();
  7. //添加认证服务
  8. services.AddAuthentication(defaultScheme: "Bearer")
  9. //添加JWT认证方案
  10. .AddJwtBearer(authenticationScheme: "Bearer", configureOptions: options => {
  11. options.Authority = "http://localhost:6002";//指定OIDC的服务地址
  12. //设置JWT的认证参数(默认不需要设置,jwt)
  13. options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
  14. ValidateAudience = false//不验证这个参数
  15. };
  16. options.RequireHttpsMetadata = false;//取消https
  17. });
  18. //注册授权服务
  19. services.AddAuthorization(option =>
  20. {
  21. option.AddPolicy("ApiScope", builder =>
  22. {
  23. //判断用户有没有通过认证
  24. builder.RequireAuthenticatedUser();
  25. //鉴定有没有这条信息-scope=Sample_Api
  26. builder.RequireClaim("scope", "Sample_Api");
  27. });
  28. option.AddPolicy("ApiScope2", builder =>
  29. {
  30. //判断用户有没有通过认证
  31. builder.RequireAuthenticatedUser();
  32. //鉴定有没有这条信息-scope=Sample_Api
  33. builder.RequireClaim("scope2", "Sample_Api");
  34. });
  35. });
  36. }
  37. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  38. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  39. {
  40. if (env.IsDevelopment())
  41. {
  42. app.UseDeveloperExceptionPage();
  43. }
  44. app.UseRouting();
  45. //添加认证
  46. app.UseAuthentication();
  47. //添加授权
  48. app.UseAuthorization();
  49. app.UseEndpoints(endpoints =>
  50. {
  51. endpoints.MapControllers()
  52. //.RequireAuthorization("ApiScope")//添加全局授权
  53. ;
  54. });
  55. }
  56. }

(4)创建一个控制器,名为【IdentityController.cs】。

  1. [Route("api/[controller]")]
  2. [ApiController]
  3. public class IdentityController : ControllerBase
  4. {
  5. [Authorize(policy: "ApiScope")]//受保护的资源
  6. [Route("GetDefaultAPI")]
  7. public IActionResult GetDefaultAPI()
  8. {
  9. return new JsonResult(
  10. from claim in User.Claims
  11. select new
  12. {
  13. claim.Type,
  14. claim.Value
  15. });
  16. }
  17. [Authorize]
  18. [Route("GetDefault1")]
  19. public string GetDefault1()
  20. {
  21. return "我需要进行认证,但是不需要进行授权!";
  22. }
  23. [Route("GetDefault2")]
  24. public string GetDefault2()
  25. {
  26. return "我不需要进行认证,也不需要进行授权!";
  27. }
  28. [Authorize(policy: "ApiScope2")]//受保护的资源
  29. [Route("GetDefault3")]
  30. public IActionResult GetDefault3()
  31. {
  32. return new JsonResult(
  33. from claim in User.Claims
  34. select new
  35. {
  36. claim.Type,
  37. claim.Value
  38. });
  39. }
  40. }

(5)然后使用Postman调用接口进行测试。

请求地址:http://localhost:6001/api/identity/GetDefaultAPI 需要在请求头传: key:Authorization value:Bearer xxx

image.png

2.4-创建一个【Sample.MVCClient】MVC客户端项目

image.png
(1)在Startup中进行配置。

  1. public class Startup
  2. {
  3. // This method gets called by the runtime. Use this method to add services to the container.
  4. public void ConfigureServices(IServiceCollection services)
  5. {
  6. services.AddRazorPages();
  7. //关闭JWT身份信息类型映射
  8. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  9. //添加认证服务
  10. services.AddAuthentication(option =>
  11. {
  12. option.DefaultScheme = "Cookies";//Cookie方案,将令牌保存在Cookies
  13. //自寻方案,当MVC客户端和IdentityServer进行交互的时候使用哪一种协议
  14. option.DefaultChallengeScheme = "oidc";
  15. })
  16. .AddCookie("Cookies")
  17. .AddOpenIdConnect("oidc",options=> {
  18. //配置oidc交互方式
  19. options.Authority = "http://localhost:6002";//配置IdentityServer授权服务的地址
  20. options.ClientId = "sample_clientid_mvc";//配置客户端ID
  21. options.ClientSecret = "sample_client_seret";//配置客户端秘钥
  22. options.ResponseType = "code"; //使用的类型,授权码流程
  23. options.SaveTokens = true;//是否保存token,将令牌保存在cookie里
  24. options.RequireHttpsMetadata = false;//取消https
  25. //添加额外要验证的资源
  26. options.Scope.Add("Sample_Api");
  27. });
  28. //注册授权服务
  29. services.AddAuthorization();
  30. }
  31. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  32. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  33. {
  34. if (env.IsDevelopment())
  35. {
  36. app.UseDeveloperExceptionPage();
  37. }
  38. else
  39. {
  40. app.UseExceptionHandler("/Error");
  41. }
  42. app.UseStaticFiles();
  43. app.UseRouting();
  44. //添加认证中间件到管道中
  45. app.UseAuthentication();
  46. //添加授权中间件到管道中
  47. app.UseAuthorization();
  48. app.UseEndpoints(endpoints =>
  49. {
  50. endpoints.MapRazorPages();
  51. });
  52. }
  53. }

(2)在某个需要被授权的控制器上添加授权特性。
image.png
(3)当请求这个控制器时,如果没有进行登录时,默认会跳转到登录页面。
image.png
(4)登录后,会让你进行相关授权。
image.png

(5)点击【登录】时的代码。

  1. public ActionResult OnGet()
  2. {
  3. return SignOut(
  4. "Cookies",//在MVC清除Cookie
  5. "oidc"//在IdentityServer4授权服务中心请求Cookie
  6. );
  7. }