Fork me on GitHub

一步一步学习IdentityServer3 (8)

IdentityServer3结合Hangfire及Cookies中间件实现授权 Idr3数据库Token过期管理

 GlobalConfiguration.Configuration.UseSqlServerStorage("Hangfire");
            GlobalConfiguration.Configuration.UseLog4NetLogProvider();
            app.UseHangfireDashboard("/lymtask", new DashboardOptions
            {
                AppPath = LYM.Unity.AppSetting.AppSettingsHelper.GetString("ClientUrl"),
                Authorization = new[] { new LYMDashboardAuth() }
            });
            app.UseHangfireServer();
            new HangfireTask().InvokeTask();

配置好Hangfire中间件,这里我用了Log4作为日志提供

值得注意的是Cookies中间件必须要在Hangfire之前,不然后面授权获取不到Cookies中间件中的授权信息

 app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
            });
AppPath :界面上返回应用的地址
Authorization:自定义授权类
下面我们看下LYMDashboardAuth,是我自定义的一个授权类
这里又需要结合Owin中间件
LYMDashboardAuth 只需要去实现 Hangfire的 IDashboardAuthorizationFilter 接口
  public class LYMDashboardAuth : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            var ctx = new OwinContext(context.GetOwinEnvironment());
            if (ctx.Authentication.User.Identity.IsAuthenticated)
            {
                var user = ctx.Authentication.User as ClaimsPrincipal;

                var username = user.Identities.FirstOrDefault().FindFirst(c => c.Type == "user_name").Value;
                if (username == "Administrator")
                {
                    return true;
                }
                return false;

            }
            return false;


        }
    }

这里我获取到了中间件中授权情况,我是只有帐号是Administrator用户才能访问Hangfire任务工作台

返回值为bool 是否允许授权 根据业务需要

 

下面说下 Token过期管理任务  new HangfireTask().InvokeTask();

public class HangfireTask
    {
        private readonly static log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(HangfireTask));
        private HttpClient client = new HttpClient();
        private EntityFrameworkServiceOptions ef = new EntityFrameworkServiceOptions() { ConnectionString = "IdSvr3Config" };
        /// <summary>
        /// 这里执行任务计划
        /// </summary>
        public void InvokeTask()
        {
            #region LYM Add 清空服务器过期Token 20170824 每10分钟清理一次

            RecurringJob.AddOrUpdate(() => ClearToken(), Cron.MinuteInterval(10));

            #endregion

            #region LYM Add  20170824 每30分钟预热一下

            RecurringJob.AddOrUpdate(() => PreHeatOAuth(), Cron.MinuteInterval(30));

            #endregion
        }



        /// <summary>
        /// 清空授权服务器过期的token
        /// </summary>
        /// <returns></returns>
        public async Task ClearToken()
        {
            using (var db = new OperationalDbContext(ef.ConnectionString, ef.Schema))
            {
                try
                {
                    Logger.Info("Clearing tokens");

                    var query =
                        from token in db.Tokens
                        where token.Expiry < DateTimeOffset.UtcNow
                        select token;

                    db.Tokens.RemoveRange(query);

                    await db.SaveChangesAsync();

                }
                catch (Exception ex)
                {
                    Logger.Error("Exception cleaning tokens", ex);
                }

            }

        }


        /// <summary>
        /// 预热授权
        /// </summary>
        /// <returns></returns>
        public async Task PreHeatOAuth()
        {
          
            await client.GetAsync(LYM.Unity.AppSetting.AppSettingsHelper.GetString("ClientUrl"));
        }
代码

写好任务类HangfireTask,里面写上清楚Token相关任务

 

 
 
posted @ 2017-09-15 14:57  龙码精神  阅读(682)  评论(0编辑  收藏  举报