Esempio n. 1
0
        /// <summary>
        /// Token自动刷新中间件,请务必放在UseAuthentication后,UseMVC前
        /// </summary>
        /// <param name="app"></param>
        /// <param name="jupiterKeys"></param>
        /// <param name="http"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseAutoRefreshToken(this IApplicationBuilder app, JupiterKeys jupiterKeys, IHttpClientFactory http)
        {
            app.Use(async(context, next) =>
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    string refreshToken = CheckTokenExp(context, jupiterKeys, http);
                    if (refreshToken != default)
                    {
                        context.Response.Headers["Authorization"] = refreshToken;
                    }
                }
                await next();
            });

            return(app);

            string CheckTokenExp(HttpContext context, JupiterKeys keys, IHttpClientFactory httpClient)
            {
                var iat = long.Parse(context.User.Claims.First(x => x.Type == "iat").Value);
                //var now = DateTime.UtcNow.TotalSeconds
                var iatDateTime = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(iat);
                var now         = DateTime.UtcNow;

                if ((now - iatDateTime) > TimeSpan.FromMinutes(5))
                {
                    try
                    {
                        return(RefreshToken());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        return(default);
Esempio n. 2
0
 /// <summary>
 /// 从本地文件中读取用来签发 Token 的 RSA Key
 /// </summary>
 /// <param name="filePath">存放密钥的文件夹路径</param>
 /// <param name="withPrivate"></param>
 /// <param name="keyParameters"></param>
 /// <returns></returns>
 private static bool TryGetKeyParameters(JupiterKeys keys, out RSAParameters keyParameters)
 {
     //keyParameters = default(RSAParameters);
     keyParameters = JsonConvert.DeserializeObject <RSAParameters>(keys.PublicKey);
     return(true);
 }