NET Core實現OAuth2.0的ResourceOwnerPassword和ClientCredentials模式

來源:互聯網
上載者:User

標籤:void   host   body   static   csp   directory   pcl   認證   request   

NET Core實現OAuth2.0的ResourceOwnerPassword和ClientCredentials模式前言

開發授權服務架構一般使用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

 

實現ResourceOwnerPassword和client credentials模式:授權伺服器:

Program.cs --> Main方法中:需要調用UseUrls設定IdentityServer4授權服務的IP地址

1             var host = new WebHostBuilder()2                 .UseKestrel()3                 //IdentityServer4的使用需要配置UseUrls4                 .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();
Client配置

在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                     //scope13                     AllowedScopes =14                     {15                         "api1",16                         //如果想帶有RefreshToken,那麼必須設定:StandardScopes.OfflineAccess17                         //如果是Client Credentials模式不支援RefreshToken的,就不需要設定OfflineAccess18                         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 day22                     //RefreshTokenUsage = TokenUsage.OneTimeOnly,   //預設狀態,RefreshToken只能使用一次,使用一次之後舊的就不能使用了,只能使用新的RefreshToken23                     //RefreshTokenUsage = TokenUsage.ReUse,   //可重複使用RefreshToken,RefreshToken,當然到期了就不能使用了24                 }
Scope設定

在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.OfflineAccess11                 StandardScopes.OfflineAccess,12             };13         }
帳號密碼驗證

Resource Owner Password模式需要對帳號密碼進行驗證(如果是client credentials模式則不需要對帳號密碼驗證了):

方式一:將Users加入到記憶體中,IdentityServer4從中擷取對帳號和密碼進行驗證:

  .AddInMemoryUsers(OAuth2Config.GetUsers())    

方式二(推薦):實現IResourceOwnerPasswordValidator介面進行驗證:

  .AddResourceOwnerValidator<MyUserValidator>() 

IResourceOwnerPasswordValidator的實現:

 1     public class MyUserValidator : IResourceOwnerPasswordValidator 2     { 3         public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) 4         { 5             if (context.UserName == "admin" && context.Password == "123") 6             { 7                 //驗證成功 8                 //使用subject可用於在資原始伺服器區分使用者身份等等 9                 //擷取:資原始伺服器通過User.Claims.Where(l => l.Type == "sub").FirstOrDefault();擷取10                 context.Result = new GrantValidationResult(subject: "admin", authenticationMethod: "custom");11             }12             else13             {14                 //驗證失敗15                 context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");16             }17             return Task.FromResult(0);18         }19     }
設定加密認證

通過AddSigningCredential方法設定RSA的加密認證(注意:預設是使用臨時認證的,就是AddTemporarySigningCredential(),無論如何不應該使用臨時認證,因為每次重啟授權服務,就會重建新的臨時認證),RSA加密認證長度要2048以上,否則服務運行會拋異常

Startup.cs -->ConfigureServices方法中的配置:

1             //RSA:認證長度2048以上,否則拋異常2             //配置AccessToken的加密認證3             var rsa = new RSACryptoServiceProvider();4             //從設定檔擷取加密認證5             rsa.ImportCspBlob(Convert.FromBase64String(Configuration["SigningCredential"]));6             services.AddIdentityServer()7                 .AddSigningCredential(new RsaSecurityKey(rsa))    //設定加密認證

如何產生RSA加密認證(將產生的PrivateKey配置到IdentityServer4中,可以設定到設定檔中):

1             using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider(2048))2             {3                 //Console.WriteLine(Convert.ToBase64String(provider.ExportCspBlob(false)));   //PublicKey4                 Console.WriteLine(Convert.ToBase64String(provider.ExportCspBlob(true)));    //PrivateKey5             }

 

資原始伺服器

Program.cs -> Main方法中:

1             var host = new WebHostBuilder()2                 .UseKestrel()3                 //IdentityServer4的使用需要配置UseUrls4                 .UseUrls("http://localhost:4823")5                 .UseContentRoot(Directory.GetCurrentDirectory())6                 .UseIISIntegration()7                 .UseStartup<Startup>()8                 .Build();

Startup.cs --> Configure方法中的配置:

            //使用IdentityServer4的資源服務並配置            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions            {                Authority = "http://localhost:4537/",                ScopeName = "api1",                SaveToken = true,                AdditionalScopes = new string[] { "offline_access" },  //添加額外的scope,offline_access為Refresh Token的擷取Scope                RequireHttpsMetadata = false,            });

需要進行授權驗證的資源介面(控制器或方法)上設定AuthorizeAttribute:

1     [Authorize]2     [Route("api/[controller]")]3     public class ValuesController : Controller

 

測試resource owner password模式測試代碼:
 1         public static void TestResourceOwnerPassword() 2         { 3             var client = new HttpClientHepler("http://localhost:4537/connect/token"); 4             string accessToken = null, refreshToken = null; 5             //擷取AccessToken 6             client.PostAsync(null, 7                 "grant_type=" + "password" + 8                 "&username=" + "admin" + 9                 "&password=" + "123" +10                 "&client_id=" + "pwd_client" +11                 "&client_secret=" + "pwd_secret" +12                 "&scope=" + "api1 offline_access",  //scope需要用空格隔開,offline_access為擷取RefreshToken13                 hd => hd.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"),14                 rtnVal => 15                 {16                     var jsonVal = JsonConvert.DeserializeObject<dynamic>(rtnVal);17                     accessToken = jsonVal.access_token;18                     refreshToken = jsonVal.refresh_token;19                 },20                 fault => Console.WriteLine(fault),21                 ex => Console.WriteLine(ex)).Wait();22 23             if (!string.IsNullOrEmpty(refreshToken))24             {25                 //使用RefreshToken擷取新的AccessToken26                 client.PostAsync(null,27                     "grant_type=" + "refresh_token" +28                     "&client_id=" + "pwd_client" +29                     "&client_secret=" + "pwd_secret" +30                     "&refresh_token=" + refreshToken,31                     hd => hd.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"),32                     rtnVal => Console.WriteLine("refresh之後的結果: \r\n" + rtnVal),33                     fault => Console.WriteLine(fault),34                     ex => Console.WriteLine(ex)).Wait();35             }36 37             if (!string.IsNullOrEmpty(accessToken))38             {39                 //訪問資源服務40                 client.Url = "http://localhost:4823/api/values";41                 client.GetAsync(null,42                         hd => hd.Add("Authorization", "Bearer " + accessToken),43                         rtnVal => Console.WriteLine("\r\n訪問資源服: \r\n" + rtnVal),44                         fault => Console.WriteLine(fault),45                         ex => Console.WriteLine(ex)).Wait(); 46             }47         }
client credentials模式測試代碼:
 1         public static void TestClientCredentials() 2         { 3             var client = new HttpClientHepler("http://localhost:4537/connect/token"); 4             string accessToken = null; 5             //擷取AccessToken 6             client.PostAsync(null, 7                 "grant_type=" + "client_credentials" + 8                 "&client_id=" + "credt_client" + 9                 "&client_secret=" + "credt_secret" +10                 "&scope=" + "api1",  //不要加上offline_access,因為Client Credentials模式不支援RefreshToken的,不然會授權失敗11                 hd => hd.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"),12                 rtnVal =>13                 {14                     var jsonVal = JsonConvert.DeserializeObject<dynamic>(rtnVal);15                     accessToken = jsonVal.access_token;16                 },17                 fault => Console.WriteLine(fault),18                 ex => Console.WriteLine(ex)).Wait();19 20             if (!string.IsNullOrEmpty(accessToken))21             {22                 //訪問資源服務23                 client.Url = "http://localhost:4823/api/values";24                 client.GetAsync(null,25                         hd => hd.Add("Authorization", "Bearer " + accessToken),26                         rtnVal => Console.WriteLine("訪問資源服: \r\n" + rtnVal),27                         fault => Console.WriteLine(fault),28                         ex => Console.WriteLine(ex)).Wait();29             }30         }

 

注意

1.RefreshToken是儲存在記憶體中的,不像AccessToken通過授權伺服器設定的加密認證進行加密的,而是產生一個唯一碼儲存在授權服務的記憶體中的,因此授權伺服器重啟了那麼這些RefreshToken就消失了;

2.資原始伺服器在第一次解析AccessToken的時候會先到授權伺服器擷取配置資料(例如會訪問:http://localhost:4537/.well-known/openid-configuration 擷取配置的,http://localhost:4537/.well-known/openid-configuration/jwks 擷取jwks)),之後解析AccessToken都會使用第一次擷取到的配置資料,因此如果授權服務的配置更改了(加密認證等等修改了),那麼應該重啟資原始伺服器使之重新擷取新的配置資料;

3.調試IdentityServer4架構的時候應該配置好ILogger,因為授權過程中的訪問(例如授權失敗等等)資訊都會調用ILogger進行日誌記錄,可使用NLog,例如:

  在Startup.cs --> Configure方法中配置:loggerFactory.AddNLog();//添加NLog

 

源碼:http://files.cnblogs.com/files/skig/OAuth2CredentialsAndPassword.zip

 

  標籤: NETCore_IdentityServer4

NET Core實現OAuth2.0的ResourceOwnerPassword和ClientCredentials模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.