源视频教程:https://www.bilibili.com/video/BV1Qa4y1n7bb IdentityServer4官网文档:https://identityserver4.readthedocs.io/en/latest/index.html
一、OAuth2.0与OpenID
OAuth2.0:是一种授权协议
OpenID:认证协议
1.1-【推荐:授权码许可】场景一:小明——第三方软件(软文系统)——微信开放平台

四种角色:资源拥有者(小明)、客户端应用(第三方平台-软文系统软文系统、授权服务(微信开放平台)、受保护资源(小明在微信公众号中的文章)
授权码——>临时的,安全性不高,一次性的,很短的有效期
访问令牌——>权限很高,访问用户资料,有效期比授权码长很多
刷新令牌——>刷新访问令牌,先调用刷新接口,然后返回的新的访问令牌;有 有效期,但是有效期比较长。
两个措施:
(1)刷新令牌必须保存在客户端的服务器上(软文系统的服务器上),调用刷新接口的时候,必须是第三方应用的后端服务器到授权服务器的访问。
(2)每一个第三方应用,必须在授权服务器注册自己的信息。
直接通信:通过授权码换取访问令牌的交互
间接通信:获取授权码的交互
1.2-【推荐:资源拥有者凭据许可】场景二:软文系统是微信的一个子系统
资源拥有者凭据(用户名和密码)许可:小明是微信的用户,然后直接可以使用微信的用户名和密码,去使用软文系统。使用访问令牌代替用户名和密码,保护敏感数据;用一次用户名和密码去换取访问令牌。
1.3-【客户端凭据许可】场景三:没有明确的资源拥有者情况,如访问网站的logo
第三方应用就是资源拥有者本身,这样的话第三方引用就会在授权服务中心去注册自己的身份信息,然后的到应用ID和应用秘钥。然后通过应用ID和引用秘钥去换取访问令牌。
1.4-【隐式许可类型】场景四:就是一个前端应用/桌面应用/APP/工具
安全性极低,相当于没有安全性;加入一个纯JS引用,不需要秘钥,也不需要授权码了,只需要通过第三方 应用ID 获取即可。
1.5-四种许可类型的区别
其实就是获取令牌的方式不同。
OpenID:认证和证明——知乎使用QQ登录——>QQ登录页面——>认证——>登录。
OAuth:授权和许可——授权页面——>两个复选框——>用户数据(昵称/头像)——>知乎。
OpenID Connect(OIDC):是认证和授权的结合
1.6-OpenID Connect

EU=End User:终端用户(实际的用户)
RP=Relying Party:受信任的客户端(身份认证的消费房)
OP=授权服务(身份认证+授权服务的结合)
ID Token=身份令牌,是授权服务器提供包含用户信息JWT格式的数据结构。
AuthN:认证
AuthZ:授权
1.7-IdentityServer4有什么用?
- 身份验证服务器
- 单点登录/注销
- API的访问控制
二、IdentityServer4实战
2.1-IdentityServer4项目的创建
环境: 目标框架:.NET Core 3.1 IdentityServer4使用版本:v4.1.1
(1)新建一个Web应用程序的项目【Sample.IdentityServer4】
(2)安装IdentityServer4的Nuget包。
(3)在【Properties/launchSettings.json】修改端口,方便后期使用是区分。
(4)新建一个静态Config类,用来配置受保护的API范围,然后使用中间件的形式将Config添加到ASP.NET Core的管道中。
/// <summary>/// 定义一个静态Config类////// 配置受保护的API范围,哪些客户端可以使用这些被保护的API////// IdentityServer4是以中间件形式添加到ASP.NET Core的管道中/// </summary>public static class Config{/** API范围* ApiScope=分组*/public static IEnumerable<ApiScope> ApiScopes => new[]{new ApiScope{Name="Sample_Api",//API范围的名称DisplayName="Sample API"//显示名称}};/** 客户端应用哪些客户端可以使用这些被保护的API*/public static IEnumerable<Client> Clients => new[] {//客户端1:客户端凭据new Client{ClientId="sample_clientid",//应用ID//应用秘钥ClientSecrets ={new Secret("sample_client_seret".Sha256())},//指定凭证许可模式AllowedGrantTypes=GrantTypes.ClientCredentials,//客户端凭证许可//允许访问API范围AllowedScopes={ "Sample_Api"}},//客户端2:资源拥有者凭据new Client{ClientId="sample_clientid_password",//应用ID//应用秘钥ClientSecrets ={new Secret("sample_client_seret".Sha256())},//指定凭证许可模式AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,//用户名密码凭证许可//允许访问API范围AllowedScopes={ "Sample_Api"}},//客户端3:OIDC客户端【例子:Sample.MVCClient】new Client{ClientId="sample_clientid_mvc",//应用IDClientName="Sample_MVC_Client",//应用秘钥ClientSecrets ={new Secret("sample_client_seret".Sha256())},//指定凭证许可模式AllowedGrantTypes=GrantTypes.Code,//授权码Code凭证许可方式RedirectUris={ "http://localhost:4001/signin-oidc"},//回调地址(登录重定向)PostLogoutRedirectUris={ "http://localhost:4001/signout-callback-oidc"},//回调地址(登出重定向)//允许访问API范围(配置哪些资源可以被授权)AllowedScopes={//需要用户授权的内容IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,"Sample_Api"},RequireConsent=true//是否需要用户进行"同意"}};//配置身份资源public static IEnumerable<IdentityResource> IdentityResources => new List<IdentityResource> {new IdentityResources.OpenId(),//必须被保护的new IdentityResources.Profile()//昵称、头像等基本信息};//配置测试用户public static List<TestUser> Users = new List<TestUser> {new TestUser{SubjectId="1",Username="admin",Password="123"}};}
(4)在Startup.cs类中进行配置,将Config添加到ASP.NET Core的管道中。
public class Startup{// This method gets called by the runtime. Use this method to add services to the container.// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940public void ConfigureServices(IServiceCollection services){//注册IdentityServer4服务var builder = services.AddIdentityServer();builder.AddDeveloperSigningCredential();//开发环境,自动生成秘钥//内存形式进行添加builder.AddInMemoryClients(Config.Clients);builder.AddInMemoryApiScopes(Config.ApiScopes);builder.AddInMemoryIdentityResources(Config.IdentityResources);builder.AddTestUsers(Config.Users);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}//将IdentityServer4添加到管道中(包含认证功能)app.UseIdentityServer();}}
(5)然后运行项目,使用postman进行测试输入以下命令进行测试。
//5.1-测试文档是否能正常打开:
Get请求: http://localhost:6002/.well-known/openid-configuration

//5.2-测试能不能使用客户端获取到Token:
Post请求: http://localhost:6002/connect/token
入参(看Config.cs怎么配置的,这里使用【客户端1:客户端凭据】作为例子): 1.client_id:客户端ID 2.client_secret:客户端秘钥 3.grant_type:凭证许可模式

//access_token解析出来具体内容如下:
2.2-IdentityServer4-MVC模板的创建
IdentityServer4提供了一个快速入门的界面,包含一个简单的入门用户界面,包括登录、注销和同意页面。
(1)使用Git方式进行安装,打开链接然后将代码拉取下来:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
(2)拉取下来之后,然后将这3个文件夹拷贝到项目中。
(3)然后在Startup中注册相关信息。
(4)运行项目可以看到这个界面说明成功了。
2.3-创建一个【Sample.WebAPI】受保护资源的WebAPI项目
(1)在【Properties/launchSettings.json】修改端口,方便后期使用是区分。
(2)需要导入两个包。
(3)在Startup.cs写入以下代码。
public class Startup{// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();//添加认证服务services.AddAuthentication(defaultScheme: "Bearer")//添加JWT认证方案.AddJwtBearer(authenticationScheme: "Bearer", configureOptions: options => {options.Authority = "http://localhost:6002";//指定OIDC的服务地址//设置JWT的认证参数(默认不需要设置,jwt)options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {ValidateAudience = false//不验证这个参数};options.RequireHttpsMetadata = false;//取消https});//注册授权服务services.AddAuthorization(option =>{option.AddPolicy("ApiScope", builder =>{//判断用户有没有通过认证builder.RequireAuthenticatedUser();//鉴定有没有这条信息-scope=Sample_Apibuilder.RequireClaim("scope", "Sample_Api");});option.AddPolicy("ApiScope2", builder =>{//判断用户有没有通过认证builder.RequireAuthenticatedUser();//鉴定有没有这条信息-scope=Sample_Apibuilder.RequireClaim("scope2", "Sample_Api");});});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseRouting();//添加认证app.UseAuthentication();//添加授权app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers()//.RequireAuthorization("ApiScope")//添加全局授权;});}}
(4)创建一个控制器,名为【IdentityController.cs】。
[Route("api/[controller]")][ApiController]public class IdentityController : ControllerBase{[Authorize(policy: "ApiScope")]//受保护的资源[Route("GetDefaultAPI")]public IActionResult GetDefaultAPI(){return new JsonResult(from claim in User.Claimsselect new{claim.Type,claim.Value});}[Authorize][Route("GetDefault1")]public string GetDefault1(){return "我需要进行认证,但是不需要进行授权!";}[Route("GetDefault2")]public string GetDefault2(){return "我不需要进行认证,也不需要进行授权!";}[Authorize(policy: "ApiScope2")]//受保护的资源[Route("GetDefault3")]public IActionResult GetDefault3(){return new JsonResult(from claim in User.Claimsselect new{claim.Type,claim.Value});}}
(5)然后使用Postman调用接口进行测试。
请求地址:http://localhost:6001/api/identity/GetDefaultAPI 需要在请求头传: key:Authorization value:Bearer xxx

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

(1)在Startup中进行配置。
public class Startup{// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddRazorPages();//关闭JWT身份信息类型映射JwtSecurityTokenHandler.DefaultMapInboundClaims = false;//添加认证服务services.AddAuthentication(option =>{option.DefaultScheme = "Cookies";//Cookie方案,将令牌保存在Cookies//自寻方案,当MVC客户端和IdentityServer进行交互的时候使用哪一种协议option.DefaultChallengeScheme = "oidc";}).AddCookie("Cookies").AddOpenIdConnect("oidc",options=> {//配置oidc交互方式options.Authority = "http://localhost:6002";//配置IdentityServer授权服务的地址options.ClientId = "sample_clientid_mvc";//配置客户端IDoptions.ClientSecret = "sample_client_seret";//配置客户端秘钥options.ResponseType = "code"; //使用的类型,授权码流程options.SaveTokens = true;//是否保存token,将令牌保存在cookie里options.RequireHttpsMetadata = false;//取消https//添加额外要验证的资源options.Scope.Add("Sample_Api");});//注册授权服务services.AddAuthorization();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseRouting();//添加认证中间件到管道中app.UseAuthentication();//添加授权中间件到管道中app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapRazorPages();});}}
(2)在某个需要被授权的控制器上添加授权特性。
(3)当请求这个控制器时,如果没有进行登录时,默认会跳转到登录页面。
(4)登录后,会让你进行相关授权。
(5)点击【登录】时的代码。
public ActionResult OnGet(){return SignOut("Cookies",//在MVC清除Cookie"oidc"//在IdentityServer4授权服务中心请求Cookie);}
