1、新建.net core 3.1 Web 空項目。
2、Nuget 增加 IdentityServer4(4.1.1)、Autofac(6.0.0)目前使用的版本
3、新建 Config.cs 配置文件 ,源碼如下
1 using System.Collections.Generic; 2 using IdentityServer4.Models; 3 namespace IdentityServer 4 { 5 public class Config1 6 { 7 public static IEnumerable<ApiResource> GetApiResources() 8 { 9 return new List<ApiResource> 10 { 11 new ApiResource("userapi"){Scopes={"userscopes"}} 12 }; 13 } 14 15 public static IEnumerable<ApiScope> GetApiScopes() 16 { 17 return new List<ApiScope> 18 { 19 new ApiScope("userscopes") 20 }; 21 } 22 23 public static IEnumerable<Client> GetClients() 24 { 25 return new List<Client>{ 26 new Client(){ 27 ClientId = "webclient", 28 ClientName = "webclient", 29 AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, 30 RequireClientSecret = false, //客戶端不需要輸入Secret 31 AllowedScopes = {"userscopes"}, 32 ClientSecrets = {new Secret("webclient".Sha256())} 33 } 34 }; 35 } 36 } 37 }
4、由於生產環境中帳號密碼取之於數據庫中的User表,並不是用於測試的TestUser,所以要增加兩個類,一個是驗證帳號密碼,另一個是帳號另外的一些自定義信息
1 using IdentityModel; 2 using IdentityServer4.Validation; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Security.Claims; 7 using System.Threading.Tasks; 8 using IdentityServer.DbModel; 9 namespace IdentityServer 10 { 11 public class ResourceOwnerPasswordValidatorcs : IResourceOwnerPasswordValidator 12 { 13 public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) 14 { 15 UserServices userServices = new UserServices(); 16 UserDbModel user = userServices.UserValidator(context.UserName, context.Password); 17 if (user != null) 18 { 19 List<Claim> claims = new List<Claim>() { 20 new Claim("username",user.USERNAME) 21 22 }; 23 context.Result = new GrantValidationResult( 24 context.UserName, 25 OidcConstants.AuthenticationMethods.Password, 26 claims 27 ); 28 } 29 else 30 { 31 context.Result = new GrantValidationResult( 32 IdentityServer4.Models.TokenRequestErrors.InvalidGrant, 33 "invalid custom credential" 34 ); 35 } 36 await Task.CompletedTask; 37 } 38 } 39 }
1 using IdentityServer4.Models; 2 using IdentityServer4.Services; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Threading.Tasks; 7 8 namespace IdentityServer 9 { 10 /// <summary> 11 /// 獲取用戶信息並返回給客戶端 12 /// </summary> 13 public class ProfileService : IProfileService 14 { 15 /// <summary> 16 /// 獲取用戶信息 17 /// </summary> 18 /// <param name="context"></param> 19 /// <returns></returns> 20 public Task GetProfileDataAsync(ProfileDataRequestContext context) 21 { 22 return Task.Run(()=> { 23 try 24 { 25 //用戶信息 26 var claims = context.Subject.Claims.ToList(); 27 28 //獲取用戶信息 29 context.IssuedClaims = claims.ToList(); 30 } 31 catch (Exception ex) 32 { 33 //log your error 34 } 35 }); 36 } 37 /// <summary> 38 /// 獲取或設置一個值,該值指示主題是否處於活動狀態並且可以接收令牌。 39 /// </summary> 40 /// <param name="context"></param> 41 /// <returns></returns> 42 public Task IsActiveAsync(IsActiveContext context) 43 { 44 return Task.Run(()=> { context.IsActive = true; }); 45 } 46 } 47 }
5、修改Startup.cs文件
ConfigureServices 方法中添加IdentityServer設置,與跨域設置
1 //設置IdentityServer4 2 services.AddIdentityServer() 3 .AddInMemoryApiResources(Config.GetApiResources()) 4 .AddInMemoryApiScopes(Config.GetApiScopes()) 5 .AddInMemoryClients(Config.GetClients()) 6 .AddResourceOwnerValidator<ResourceOwnerPasswordValidatorcs>() 7 .AddProfileService<ProfileService>() 8 .AddDeveloperSigningCredential(); 9 10 //設置跨域 11 services.AddCors(options => 12 { 13 options.AddPolicy("any", builder => 14 { 15 builder.WithOrigins("*"); 16 }); 17 });
Configure 方法中添加設置
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 8 app.UseCors("any"); 9 10 app.UseRouting(); 11 12 app.UseIdentityServer(); 13 }
6、此時,鑒權端已經使用開發完成,啟動即可。
7、使用postman獲取Token
以后可以將config的配置都寫入數據庫中,進行讀取。至此鑒權端已經完成,下面介紹資源端開發。