ASP.NET Core实现OAuth2.0的AuthorizationCode模式

  • Post author:
  • Post category:其他


ASP.NET Core实现OAuth2的AuthorizationCode模式

授权服务器

Program.cs –> Main方法中:需要调用UseUrls设置IdentityServer4授权服务的IP地址

1             var host = new WebHostBuilder()
2                 .UseKestrel()
3                 //IdentityServer4的使用需要配置UseUrls
4                 .UseUrls("http://localhost:5114")
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.AddSingleton<IClientStore, MyClientStore>();   //注入IClientStore的实现,可用于运行时校验Client
 8             services.AddSingleton<IScopeStore, MyScopeStore>();    //注入IScopeStore的实现,可用于运行时校验Scope
 9             //注入IPersistedGrantStore的实现,用于存储AuthorizationCode和RefreshToken等等,默认实现是存储在内存中,
10             //如果服务重启那么这些数据就会被清空了,因此可实现IPersistedGrantStore将这些数据写入到数据库或者NoSql(Redis)中
11             services.AddSingleton<IPersistedGrantStore, MyPersistedGrantStore>();
12             services.AddIdentityServer()
13                 .AddSigningCredential(new RsaSecurityKey(rsa));
14                 //.AddTemporarySigningCredential()   //生成临时的加密证书,每次重启服务都会重新生成
15                 //.AddInMemoryScopes(Config.GetScopes())    //将Scopes设置到内存中
16                 //.AddInMemoryClients(Config.GetClients())    //将Clients设置到内存中

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

1             //使用IdentityServer4
2             app.UseIdentityServer();
3             //使用Cookie模块
4             app.UseCookieAuthentication(new CookieAuthenticationOptions
5             {
6                 AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
7                 AutomaticAuthenticate = false,
8                 AutomaticChallenge = false
9             });

Client配置

方式一:

.AddInMemoryClients(Config.GetClients())    //将Clients设置到内存中,IdentityServer4从中获取进行验证

方式二(推荐):

services.AddSingleton<IClientStore, MyClientStore>();   //注入IClientStore的实现,用于运行时获取和校验Client

IClientStore的实现

 1     public class MyClientStore : IClientStore
 2     {
 3         readonly Dictionary<string, Client> _clients;
 4         readonly IScopeStore _scopes;
 5         public MyClientStore(IScopeStore scopes)
 6         {
 7             _scopes = scopes;
 8             _clients = new Dictionary<string, Client>()
 9             {
10                 {
11                     "auth_clientid",
12                     new Client
13                     {
14                         ClientId = "auth_clientid",
15                         ClientName = "AuthorizationCode Clientid",
16                         AllowedGrantTypes = new string[] { GrantType.AuthorizationCode },   //允许AuthorizationCode模式
17                         ClientSecrets =
18                         {
19                             new Secret("secret".Sha256())
20                         },
21                         RedirectUris = { "http://localhost:6321/Home/AuthCode" },
22                         PostLogoutRedirectUris = { "http://localhost:6321/" },
23                         //AccessTokenLifetime = 3600, //AccessToken过期时间, in seconds (defaults to 3600 seconds / 1 hour)
24                         //AuthorizationCodeLifetime = 300,  //设置AuthorizationCode的有效时间,in seconds (defaults to 300 seconds / 5 minutes)
25                         //AbsoluteRefreshTokenLifetime = 2592000,  //RefreshToken的最大过期时间,in seconds. Defaults to 2592000 seconds / 30 day
26                         AllowedScopes = (from l in _scopes.GetEnabledScopesAsync(true).Result select l.Name).ToList(),
27                     }
28                 }
29             };
30         }
31 



版权声明:本文为kuihuan2771原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。