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

本文详细介绍了如何在ASP.NET Core中实现OAuth2.0的AuthorizationCode模式,包括授权服务器的配置、IClientStore和IScopeStore的实现、资源服务器的配置以及测试流程,涵盖从用户授权到令牌获取的完整步骤。
摘要由CSDN通过智能技术生成

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         }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值