開發授權服務框架一般使用OAuth2.0授權框架,而開發Webapi的授權更應該使用OAuth2.0授權標准,OAuth2.0授權框架文檔說明參考:https://tools.ietf.org/html/rfc6749
.NET Core開發OAuth2的項目需要使用IdentityServer4(現在還處於RC預發行版本),可參考:https://identityserver4.readthedocs.io/en/dev/
IdentityServer4源碼:https://github.com/IdentityServer
如果在.NET中開發OAuth2的項目可使用OWIN,可參考實例源碼:https://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
Program.cs --> Main方法中:需要調用UseUrls設置IdentityServer4授權服務的IP地址
1 var host = new WebHostBuilder()
2 .UseKestrel()
3 //IdentityServer4的使用需要配置UseUrls
4 .UseUrls("http://localhost:4537")
5 .UseContentRoot(Directory.GetCurrentDirectory())
6 .UseIISIntegration()
7 .UseStartup<Startup>()
8 .Build();
Startup.cs -->ConfigureServices方法中:
1 //RSA:證書長度2048以上,否則拋異常 2 //配置AccessToken的加密證書 3 var rsa = new RSACryptoServiceProvider(); 4 //從配置文件獲取加密證書 5 rsa.ImportCspBlob(Convert.FromBase64String(Configuration["SigningCredential"])); 6 //IdentityServer4授權服務配置 7 services.AddIdentityServer() 8 .AddSigningCredential(new RsaSecurityKey(rsa)) //設置加密證書 9 //.AddTemporarySigningCredential() //測試的時候可使用臨時的證書 10 .AddInMemoryScopes(OAuth2Config.GetScopes()) 11 .AddInMemoryClients(OAuth2Config.GetClients()) 12 //如果是client credentials模式那麼就不需要設置驗證User了 13 .AddResourceOwnerValidator<MyUserValidator>() //User驗證接口 14 //.AddInMemoryUsers(OAuth2Config.GetUsers()) //將固定的Users加入到內存中 15 ;
Startup.cs --> Configure方法中:
1 //使用IdentityServer4的授權服務 2 app.UseIdentityServer();
在Startup.cs中通過AddInMemoryClients(OAuth2Config.GetClients())設置到內存中,配置:
1 new Client
2 {
3 //client_id
4 ClientId = "pwd_client",
5 //AllowedGrantTypes = new string[] { GrantType.ClientCredentials }, //Client Credentials模式
6 AllowedGrantTypes = new string[] { GrantType.ResourceOwnerPassword }, //Resource Owner Password模式
7 //client_secret
8 ClientSecrets =
9 {
10 new Secret("pwd_secret".Sha256())
11 },
12 //scope
13 AllowedScopes =
14 {
15 "api1",
16 //如果想帶有RefreshToken,那麼必須設置:StandardScopes.OfflineAccess
17 //如果是Client Credentials模式不支持RefreshToken的,就不需要設置OfflineAccess
18 StandardScopes.OfflineAccess.Name,
19 },
20 //AccessTokenLifetime = 3600, //AccessToken的過期時間, in seconds (defaults to 3600 seconds / 1 hour)
21 //AbsoluteRefreshTokenLifetime = 60, //RefreshToken的最大過期時間,in seconds. Defaults to 2592000 seconds / 30 day
22 //RefreshTokenUsage = TokenUsage.OneTimeOnly, //默認狀態,RefreshToken只能使用一次,使用一次之後舊的就不能使用了,只能使用新的RefreshToken
23 //RefreshTokenUsage = TokenUsage.ReUse, //可重復使用RefreshToken,RefreshToken,當然過期了就不能使用了
24 }
在Startup.cs中通過AddInMemoryScopes(OAuth2Config.GetScopes())設置到內存中,配置:
1 public static IEnumerable<Scope> GetScopes()
2 {
3 return new List<Scope>
4 {
5 new Scope
6 {
7 Name = "api1",
8 Description = "My API",
9 },
10 //如果想帶有RefreshToken,那麼必須設置:StandardScopes.OfflineAccess
11 StandardScopes.OfflineAccess,
12 };
13 }
Resource Owner Password模式需要對賬號密碼進行驗證(如果是client credentials模式則不需要對賬號密碼驗證了):
方式一:將Users加入到內存中,IdentityServer4從中獲取對賬號和密碼進行驗證:
.AddInMemoryUsers(OAuth2Config.GetUsers())
方式二(推薦):實現IResourceOwnerPasswordValidator接口進行驗證: