1、自定义DefaultRefreshTokenService类刷新Token
Identity Server 3的默认实现类,可以参考根据自己的需求,自定义实现:DefaultRefreshTokenService源代码
下面的MyDefaultRefreshTokenService
类重写CreateRefreshTokenAsync
方法,来实现针对不同用户设置不同的刷新时间(过期时间),另外,MyDefaultRefreshTokenService
类项目中还要引用IdentityModel
,直接Nuget中安装IdentityModel
即可。
相关文档:VS(Visual Studio)中Nuget的使用
using IdentityModel; using IdentityServer3.Core.Logging; using IdentityServer3.Core.Models; using IdentityServer3.Core.Services; using IdentityServer3.Core.Services.Default; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace Host.AspNetCore { public class MyDefaultRefreshTokenService : DefaultRefreshTokenService { private readonly static ILog Logger = LogProvider.GetCurrentClassLogger(); public MyDefaultRefreshTokenService(IRefreshTokenStore store, IEventService events) : base(store, events) { } public override async Task<string> CreateRefreshTokenAsync(ClaimsPrincipal subject, Token accessToken, Client client) { // return base.CreateRefreshTokenAsync(subject, accessToken, client); Logger.Debug("Creating refresh token"); int lifetime; //这里可以根据需求,不同的用户设置不同的token刷新时间 if (client.RefreshTokenExpiration == TokenExpiration.Absolute) { Logger.Debug("Setting an absolute lifetime: " + client.AbsoluteRefreshTokenLifetime); lifetime = client.AbsoluteRefreshTokenLifetime; } else { Logger.Debug("Setting a sliding lifetime: " + client.SlidingRefreshTokenLifetime); lifetime = client.SlidingRefreshTokenLifetime; } var handle = CryptoRandom.CreateUniqueId(); var refreshToken = new RefreshToken { CreationTime = DateTimeOffset.UtcNow, LifeTime = lifetime, AccessToken = accessToken, Subject = subject }; await _store.StoreAsync(handle, refreshToken); await RaiseRefreshTokenIssuedEventAsync(handle, refreshToken); return handle; } } }
2、Startup.cs中配置RefreshTokenService
将RefreshTokenService
配置为MyDefaultRefreshTokenService
public void Configure(IApplicationBuilder app, IHostingEnvironment host)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(@"c:\logs\idsvrlog.txt")
.CreateLogger();
app.Map("/core", coreApp =>
{
var factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
.UseInMemoryUsers(Users.Get());
var refreshTokenService = new MyDefaultRefreshTokenService(new InMemoryRefreshTokenStore(), new DefaultEventService());
factory.RefreshTokenService = new Registration<IRefreshTokenService>(resolver => refreshTokenService);
var options = new IdentityServerOptions
{
SiteName = "IdentityServer3 - AspNet Core",
SigningCertificate = Certificate.Get(host.ContentRootPath),
Factory = factory,
};
coreApp.UseIdentityServer(options);
});
}