本文主要介绍ASP.NET Core使用Identity Server 3时,要自定义修改Token刷新时间的方法,以方便实现针对不同用户指定不同的Token过期刷新时间。

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);
});
}


推荐文档