Esempio n. 1
0
        /// <summary>
        /// 取一个访问令牌
        /// </summary>
        /// <returns></returns>
        public TokenResponse TakeToken()
        {
            if (dictUserToken.ContainsKey(this.UserName))
            {
                UserTokenInfo uti = dictUserToken[this.UserName];
                //获取当前用户的读写锁
                this.CurrentTokenLock = uti.TokenLock;
                //this.CurrentTokenLock.EnterUpgradeableReadLock();
                //Console.WriteLine("...EnterUpgradeableReadLock...,Thread ID:{0}",Thread.CurrentThread.ManagedThreadId);
                this.OldToken = uti.Token;
                //Thread.Sleep(1000);
                Console.WriteLine("thread waite one.thread:{0}", Thread.CurrentThread.ManagedThreadId);
                this.CurrentTokenLock.WaitOne(10000);

                if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= uti.Token.expires_in - 2)
                {
                    //等待所有使用此令牌的线程使用完成
                    Console.WriteLine("thread reset begin. thread:{0}", Thread.CurrentThread.ManagedThreadId);
                    this.CurrentTokenLock.Reset();
                    try
                    {
                        if (uti.UseCount > 0)
                        {
                            Thread.Sleep(2000);//睡2秒,等待之前的请求处理完
                        }
                        //防止线程重入,再次判断
                        if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= uti.Token.expires_in - 2)
                        {
                            //刷新令牌
                            OAuthClient oc       = new OAuthClient();
                            var         newToken = oc.RefreshToken(uti.Token);
                            uti.ResetToken(newToken);
                            this.TokenExctionMessage = oc.ExceptionMessage;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.TokenExctionMessage = ex.Message;
                        return(null);
                    }
                    finally
                    {
                        Console.WriteLine("thread set. thread:{0}", Thread.CurrentThread.ManagedThreadId);
                        this.CurrentTokenLock.Set();
                    }
                }

                Console.WriteLine("thread continue. thread:{0}", Thread.CurrentThread.ManagedThreadId);
                this.CurrentUserTokenInfo = uti;
                uti.BeginUse();
                this.CurrentTokenLock.Set();
                return(uti.Token);
            }
            else
            {
                throw new Exception(this.UserName + " 还没有访问令牌。");
            }
        }
Esempio n. 2
0
        public static void SetUserToken(TokenResponse value, string identityName)
        {
            if (value == null)
            {
                throw new ArgumentNullException();
            }
            string        token_key = "AccessToken_" + identityName;
            UserTokenInfo ut        = new UserTokenInfo(identityName, value);

            HttpContext.Current.Cache[token_key] = ut;
        }
Esempio n. 3
0
        /// <summary>
        /// 使用密码模式,给当前用户创建一个访问令牌
        /// </summary>
        /// <param name="password">用户登录密码</param>
        /// <returns></returns>
        public async Task <TokenResponse> CreateToken(string password)
        {
            OAuthClient oc       = new OAuthClient();
            var         tokenRsp = await oc.GetTokenOfPasswardGrantType(this.UserName, password);

            if (tokenRsp != null)
            {
                UserTokenInfo uti = new UserTokenInfo(this.UserName, tokenRsp);
                dictUserToken[this.UserName] = uti;
            }
            else
            {
                this.TokenExctionMessage = oc.ExceptionMessage;
            }
            return(tokenRsp);
        }
Esempio n. 4
0
        public static void SetUserToken(TokenResponse value)
        {
            var identity = HttpContext.Current.User.Identity;

            if (identity == null || identity.IsAuthenticated == false)
            {
                throw new Exception("获取用户访问令牌但是用户未登录!");
            }
            if (value == null)
            {
                throw new ArgumentNullException();
            }
            string        token_key = "AccessToken_" + identity.Name;
            UserTokenInfo ut        = new UserTokenInfo(identity.Name, value);

            HttpContext.Current.Cache[token_key] = ut;
        }
Esempio n. 5
0
        /// <summary>
        /// 获取用户访问令牌,如果没有找到,不抛出异常
        /// </summary>
        /// <returns></returns>
        public static UserTokenInfo TryGetUserToken()
        {
            var identity = HttpContext.Current.User.Identity;

            if (identity == null || identity.IsAuthenticated == false)
            {
                return(null);
            }
            string token_key = "AccessToken_" + identity.Name;
            var    obj       = HttpContext.Current.Cache[token_key];

            if (obj == null)
            {
                return(null);
            }
            UserTokenInfo ut = (UserTokenInfo)obj;

            return(ut);
        }
Esempio n. 6
0
        /// <summary>
        /// 获取用户的访问令牌,如果不存在,会抛异常
        /// </summary>
        /// <returns></returns>
        public static UserTokenInfo GetUserToken()
        {
            var identity = HttpContext.Current.User.Identity;

            if (identity == null || identity.IsAuthenticated == false)
            {
                throw new Exception("获取用户访问令牌但是用户未登录!");
            }
            string token_key = "AccessToken_" + identity.Name;
            var    obj       = HttpContext.Current.Cache[token_key];

            if (obj == null)
            {
                throw new Exception("未找到用户的访问令牌,key:" + token_key);
            }
            UserTokenInfo ut = (UserTokenInfo)obj;

            return(ut);
        }
Esempio n. 7
0
        /// <summary>
        /// 取一个访问令牌
        /// </summary>
        /// <returns>如果没有或者获取令牌失败,返回空</returns>
        public TokenResponse TakeToken()
        {
            if (dictUserToken.ContainsKey(this.UserName))
            {
                UserTokenInfo uti = dictUserToken[this.UserName];
                //获取当前用户的读写锁
                //this.CurrentTokenLock = uti.TokenLock;
                //this.CurrentTokenLock.EnterUpgradeableReadLock();
                //Console.WriteLine("...EnterUpgradeableReadLock...,Thread ID:{0}",Thread.CurrentThread.ManagedThreadId);
                this.OldToken = uti.Token;

                //如果令牌超期,刷新令牌
                if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= uti.Token.expires_in)
                {
                    lock (uti.SyncObject)
                    {
                        //防止线程重入,再次判断
                        if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= uti.Token.expires_in)
                        {
                            //等待之前的用户使用完令牌
                            while (uti.UseCount > 0)
                            {
                                if (DateTime.Now.Subtract(uti.LastUseTime).TotalSeconds > 10)
                                {
                                    //如果发出请求超过10秒使用计数还大于0,可以认为资源服务器响应缓慢,最终请求此资源可能会拒绝访问
                                    this.TokenExctionMessage = "Resouce Server maybe Request TimeOut.";
                                    OAuthClient.WriteErrorLog("00", "**警告** " + DateTime.Now.ToString() + ":用户" + this.UserName + " 最近一次使用当前令牌("
                                                              + uti.Token.AccessToken + ")已经超时(10秒),使用次数:" + uti.UseCount + "。\r\n**下面将刷新令牌,但可能导致之前还未处理完的资源服务器访问被拒绝访问。");
                                    break;
                                }
                                System.Threading.Thread.Sleep(100);
                                Console.WriteLine("----waite token Use Count is 0.--------");
                            }
                            //刷新令牌
                            try
                            {
                                OAuthClient oc       = new OAuthClient();
                                var         newToken = oc.RefreshToken(uti.Token);
                                if (newToken == null)
                                {
                                    throw new Exception("Refresh Token Error:" + oc.ExceptionMessage);
                                }
                                else if (string.IsNullOrEmpty(newToken.AccessToken))
                                {
                                    throw new Exception("Refresh Token Error:Empty AccessToken. Other Message:" + oc.ExceptionMessage);
                                }

                                uti.ResetToken(newToken);
                                this.TokenExctionMessage = oc.ExceptionMessage;
                            }
                            catch (Exception ex)
                            {
                                this.TokenExctionMessage = ex.Message;
                                return(null);
                            }
                        }
                    }//end lock
                }

                this.CurrentUserTokenInfo = uti;
                uti.BeginUse();
                //this.CurrentTokenLock.Set();
                return(uti.Token);
            }
            else
            {
                //throw new Exception(this.UserName+" 还没有访问令牌。");
                this.TokenExctionMessage = this.UserName + " 还没有访问令牌。";
                return(null);
            }
        }