/*
         *    public override Task ValidateTokenRequest(OAuthValidateTokenRequestContext context)
         *    {
         *        var token = context.TokenRequest;
         *        return base.ValidateTokenRequest(context);
         *    }
         */

        /// <summary>
        /// 验证持有 refresh token 的客户端
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (context.Ticket == null || context.Ticket.Identity == null)
            {
                context.Rejected();
                return(base.GrantRefreshToken(context));
            }
            var currentClient  = context.OwinContext.Get <string>("as:client_id");
            var originalClient = context.ClientId;

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return(base.GrantRefreshToken(context));
            }
            context.OwinContext.Set <string>("as:client_id", currentClient);
            context.OwinContext.Set <string>("as:refresh_token_time", "36000");
            // chance to change authentication ticket for refresh token requests
            var claimsIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket      = new AuthenticationTicket(claimsIdentity, context.Ticket.Properties);

            context.Validated(newTicket);
            return(base.GrantRefreshToken(context));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }
            var existingIdentity = new ClaimsIdentity(context.Ticket.Identity);

            //Ensure that the user is still a apart of the roles.
            using (var userManager = _userManagerFactory())
            {
                var user = await userManager.FindByNameAsync(existingIdentity.Name); //<--Fixed this. Get the current name property

                if (user == null)
                {
                    context.SetError("invalid_user",
                                     string.Format("{0} not a valid user", existingIdentity.NameClaimType));
                    context.Rejected();
                    return;
                }

                var newId = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);

                var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
                context.Validated(newTicket);
            }
        }
Example #3
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.ClientId;

            var userGuid = context.Ticket.Identity.Claims.Where(c => c.Type == "UserGuid").First().Value;

            if (!memCache.Contains(userGuid, null))
            {
                context.Rejected();
                return;
            }


            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            //var newId = new ClaimsIdentity(context.Ticket.Identity);
            ////newId.AddClaim(new Claim("tokenId", Guid.NewGuid().ToString()));

            //var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            //context.Validated(newTicket);
            context.Validated(context.Ticket);
        }
Example #4
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (context.Ticket == null || context.Ticket.Identity == null)
            {
                context.Rejected();
                return(base.GrantRefreshToken(context));
            }
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return(base.GrantRefreshToken(context));
            }
            // chance to change authentication ticket for refresh token requests
            var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            var props          = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:client_id", context.ClientId }
            });
            var newTicket = new AuthenticationTicket(claimsIdentity, props);

            context.Validated(newTicket);
            return(base.GrantRefreshToken(context));
        }
Example #5
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                context.Rejected();
                return(Task.FromResult <object>(null));
            }

            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            foreach (var claim in newIdentity.Claims)
            {
                if (claim.Type == "newClaim")
                {
                    newIdentity.RemoveClaim(claim);
                    break;
                }
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];

            var currentClient = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            var oAuthIdentity = new ClaimsIdentity(context.Ticket.Identity);

            var props = new AuthenticationProperties(new Dictionary <string, string> {
                { "client_id", context.ClientId }
            });

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));//"newClaim", "refreshToken"

            var newTicket = new AuthenticationTicket(oAuthIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            await base.GrantRefreshToken(context);
        }
Example #7
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                return(Task.FromResult <object>(null));
            }

            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var roleId      = context.Request.Query.Get("roleId");

            if (roleId != null)
            {
                if (newIdentity.Claims.Any(x => x.Type == "roleId"))
                {
                    newIdentity.RemoveClaim(newIdentity.Claims.FirstOrDefault(x => x.Type == "roleId"));
                }

                newIdentity.AddClaim(new Claim("roleId", roleId));
            }

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Example #8
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // grant_type = refresh_token 체크
            var originalClient = context.Ticket.Properties.Dictionary[Startup.ClientPropertyName];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");

                return(Task.FromResult <object>(null));
            }

            // change auth ticket for refresh token request
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            // NOTE: 여기서 추가 클레임 로직을 설정해서 리턴할 수 있음.
            // ex) API 측에서 일괄적으로 클라이언트들에게 적용해야 되는 클레임 변경 사항들에 대해서
            // db context 등에서 검색해서 클레임을 추가하거나,
            // 리프레시 토큰 아이디에 대해 특정 클레임을 설정하는 등의 작업

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);

            //EXTREMAMENTE NECESSÁRIO, pois quando se trata do middleware do OWIN, o CORS não atende
            if (!context.OwinContext.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            }
        }
Example #10
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            context.Validated();
        }
 //called when a request for token is called passing (refresh_token) as a grant_type
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     return(Task.Run(() =>
     {
         var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
         var currentClient = context.OwinContext.Get <string>("as:client_id");
         // enforce client binding of refresh token
         if (originalClient != currentClient)
         {
             context.Rejected();
             return;
         }
         // chance to change authentication ticket for refresh token requests
         var newId = new ClaimsIdentity(context.Ticket.Identity);
         var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
         context.Validated(newTicket);
     }));
 }
Example #12
0
        /// <summary>
        /// 刷新客户端令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            string originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            string currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                return(Task.FromResult(0));
            }
            ClaimsIdentity identity = new ClaimsIdentity(context.Ticket.Identity);

            identity.AddClaim(new Claim("newClaim", "refreshToken"));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, context.Ticket.Properties);

            context.Validated(ticket);
            return(base.GrantRefreshToken(context));
        }
        public override async System.Threading.Tasks.Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
        }
Example #14
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];

            if (originalClient != _clientId)
            {
                context.Rejected();
            }
            else
            {
                var newId = new ClaimsIdentity(context.Ticket.Identity);
                newId.AddClaim(new Claim("newClaim", "refreshToken"));

                var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
                context.Validated(newTicket);
            }

            return base.GrantRefreshToken(context);
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);
            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            context.Validated(newTicket);
        }
Example #16
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var codigoClienteOriginal = context.Ticket.Properties.Dictionary["client_id"];
            var codigoClienteAtual    = context.OwinContext.Get <string>("client_id");

            if (codigoClienteOriginal == codigoClienteAtual)
            {
                var novoCodigo = new ClaimsIdentity(context.Ticket.Identity);
                novoCodigo.AddClaim(new Claim("newClaim", "refreshToken"));

                var newTicket = new AuthenticationTicket(novoCodigo, context.Ticket.Properties);
                context.Validated(newTicket);
            }
            else
            {
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
        }
        /*
         * public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
         * {
         *  if (context.ClientId == _publicClientId)
         *  {
         *      Uri expectedRootUri = new Uri(context.Request.Uri, "/");
         *
         *      if (expectedRootUri.AbsoluteUri == context.RedirectUri)
         *      {
         *          context.Validated();
         *      }
         *  }
         *
         *  return Task.FromResult<object>(null);
         * }
         */

        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            bool validated = false;

            if (context.Ticket != null && context.Ticket.Identity != null)
            {
                ApplicationUser      user        = context.OwinContext.Get <ApplicationUser>(OwinUserKey);
                OAuthClient          oauthClient = context.OwinContext.Get <OAuthClient>(OwinClientKey);
                ApplicationDbContext dbContext   = context.OwinContext.Get <ApplicationDbContext>();
                var oauthSessions = dbContext.OAuthSessions.Where(oas => oas.UserId.ToString() == user.Id && oas.ClientId == oauthClient.Id);
                foreach (OAuthSession oauthSession in oauthSessions)
                {
                    dbContext.OAuthSessions.Remove(oauthSession);
                }

                Guid oauthSessionValue = Guid.NewGuid();

                dbContext.OAuthSessions.Add(new OAuthSession
                {
                    ClientId       = oauthClient.Id,
                    OrganizationId = user.OrganizationId,
                    UserId         = user.Id,
                    Id             = oauthSessionValue
                });
                dbContext.SaveChanges();

                context.Ticket.Identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));

                context.Validated();
                context.Request.Context.Authentication.SignIn(context.Ticket.Identity);
                validated = true;
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
        }
Example #19
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            string originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            string currentClient  = context.ClientId;

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
        }
Example #20
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            if (originalClient != currentClient)
            {
                context.Rejected();
                return(Task.FromResult <object>(null));
            }

            var            userManager   = context.OwinContext.GetUserManager <ApplicationUserManager>();
            UserModel      user          = userManager.FindByName(context.Ticket.Identity.Name);
            ClaimsIdentity oAuthIdentity = user.GenerateUserIdentity(userManager, "JWT");

            var newTicket = new AuthenticationTicket(oAuthIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(base.GrantRefreshToken(context));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public void GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.OwinContext.Get <string>("as:client_id");
            var currentClient  = context.ClientId;

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
            }

            // ticket
            var userName          = context.Ticket.Properties.Dictionary["userName"];
            var scope             = context.OwinContext.GetAutofacLifetimeScope();
            var membershipService = scope.Resolve <IMembershipService>();
            var applicationUser   = await membershipService.GetUser(userName).ConfigureAwait(false);

            var newTicket = await GenerateAuthenticationTicket(context.OwinContext, Guid.Parse(applicationUser.Id), applicationUser.UserName).ConfigureAwait(false);

            context.Validated(newTicket);
        }
Example #23
0
        /// <summary>
        /// 刷新token "grant_type", "refresh_token"
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                return(Task.FromResult <object>(null));
            }

            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTickets = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTickets);

            return(Task.FromResult <object>(null));
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (context.ClientId != null)
            {
                context.Rejected();
                return(Task.FromResult(0));
            }

            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            newIdentity.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            var userId = int.Parse(context.Ticket.Identity.FindFirst(ClaimTypes.UserData).Value);

            _usersService().UpdateUserLastActivityDate(userId);

            return(Task.FromResult(0));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.OwinContext.Get <string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.RemoveClaim(newId.FindFirst(c => c.Type == "RefreshToken"));
            newId.AddClaim(new Claim("RefreshToken", Guid.NewGuid().ToString()));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // grant_type = refresh_token
            var originalClient = context.Ticket.Properties.Dictionary[OwinEnvironment.ClientPropertyName];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.Rejected();
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");

                return(Task.FromResult <object>(null));
            }

            // change auth ticket for refresh token request
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket   = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Example #27
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId != null)
            {
                context.Rejected();
                return(Task.FromResult(0));
            }

            // Change authentication ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);


            var userId = context.Ticket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

            _unitOfWork().SaveChanges();

            return(Task.FromResult(0));
        }
Example #28
0
        /// <summary>
        /// 刷新安全令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //当前服务器对应票据中的客户对象名称
            var originalClient = context.Ticket.Properties.Dictionary["as:clientId"];
            //当前请求的客户对象名称
            var currentClient = context.ClientId;

            //判断请求刷新key的客户id是否来自安全令牌对象的客户id
            if (originalClient != currentClient)
            {
                context.Rejected();
                return(base.GrantRefreshToken(context));
            }

            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.AddClaim(new Claim("newClaim", "refreshToken"));
            //
            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);

            context.Validated(newTicket);
            return(base.GrantRefreshToken(context));
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId != null)
            {
                context.Rejected();
                return(Task.FromResult(0));
            }

            // Change authentication ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            newIdentity.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            var userId = int.Parse(context.Ticket.Identity.FindFirst(ClaimTypes.UserData).Value);

            _usersService().UpdateUserLastActivityDate(userId);

            return(Task.FromResult(0));
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.OwinContext.Get<string>("as:client_id");

            // Enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                context.SetError("invalid_grant", "Access denied.");

                return Task.FromResult(0);
            }

            // Chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);
            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            context.Validated(newTicket);

            return Task.FromResult(0);
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.OwinContext.Get<string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.RemoveClaim(newId.FindFirst(c => c.Type == "RefreshToken"));
            newId.AddClaim(new Claim("RefreshToken", Guid.NewGuid().ToString()));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            context.Validated(newTicket);
        }
        /*
              public override Task ValidateTokenRequest(OAuthValidateTokenRequestContext context)
              {
                  var token = context.TokenRequest;
                  return base.ValidateTokenRequest(context);
              }
        */

        /// <summary>
        /// 验证持有 refresh token 的客户端
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (context.Ticket == null || context.Ticket.Identity == null)
            {
                context.Rejected();
                return base.GrantRefreshToken(context);
            }
            var currentClient = context.OwinContext.Get<string>("as:client_id");
            var originalClient = context.ClientId;
            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return base.GrantRefreshToken(context);
            }
            context.OwinContext.Set<string>("as:client_id", currentClient);
            context.OwinContext.Set<string>("as:refresh_token_time", "36000");
            // chance to change authentication ticket for refresh token requests
            var claimsIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket = new AuthenticationTicket(claimsIdentity, context.Ticket.Properties);
            context.Validated(newTicket);
            return base.GrantRefreshToken(context);
        }
        /*
        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
            }

            return Task.FromResult<object>(null);
        }
        */

        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            bool validated = false;
            if (context.Ticket != null && context.Ticket.Identity != null)
            {
                ApplicationUser user = context.OwinContext.Get<ApplicationUser>(OwinUserKey);
                OAuthClient oauthClient = context.OwinContext.Get<OAuthClient>(OwinClientKey);
                ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
                var oauthSessions = dbContext.OAuthSessions.Where(oas => oas.UserId.ToString() == user.Id && oas.ClientId == oauthClient.Id);
                foreach (OAuthSession oauthSession in oauthSessions)
                {
                    dbContext.OAuthSessions.Remove(oauthSession);
                }

                Guid oauthSessionValue = Guid.NewGuid();

                dbContext.OAuthSessions.Add(new OAuthSession
                {
                    ClientId = oauthClient.Id,
                    OrganizationId = user.OrganizationId,
                    UserId = user.Id,
                    Id = oauthSessionValue
                });
                dbContext.SaveChanges();

                context.Ticket.Identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));

                context.Validated();
                context.Request.Context.Authentication.SignIn(context.Ticket.Identity);                
                validated = true;
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return Task.FromResult<object>(null);
        }
 /// <summary>
 /// 刷新客户端令牌
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     string originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
     string currentClient = context.ClientId;
     if (originalClient != currentClient)
     {
         context.Rejected();
         return Task.FromResult(0);
     }
     ClaimsIdentity identity = new ClaimsIdentity(context.Ticket.Identity);
     identity.AddClaim(new Claim("newClaim", "refreshToken"));
     AuthenticationTicket ticket = new AuthenticationTicket(identity, context.Ticket.Properties);
     context.Validated(ticket);
     return base.GrantRefreshToken(context);
 }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.OwinContext.Get<string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }
            var existingIdentity = new ClaimsIdentity(context.Ticket.Identity);
            //Ensure that the user is still a apart of the roles.
            using (var userManager = _userManagerFactory())
            {
                var user = await userManager.FindByNameAsync(existingIdentity.Name); //<--Fixed this. Get the current name property

                if (user == null)
                {

                    context.SetError("invalid_user",
                        string.Format("{0} not a valid user", existingIdentity.NameClaimType));
                    context.Rejected();
                    return;
                }

                var newId = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
                var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
                context.Validated(newTicket);
            }
        }
 /// <summary>
 /// 刷新客户端令牌
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     //if (context.Ticket == null || context.Ticket.Identity == null || !context.Ticket.Identity.IsAuthenticated)
     //{
     //    context.SetError("invalid_grant", "Refresh token is not valid");
     //}
     //return base.GrantRefreshToken(context);
     string originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
     string currentClient = context.ClientId;
     if (originalClient != currentClient)
     {
         context.Rejected();
         return Task.FromResult(0);
     }
     ClaimsIdentity identity = new ClaimsIdentity(context.Ticket.Identity);
     identity.AddClaim(new Claim("newClaim", "refreshToken"));
     AuthenticationTicket ticket = new AuthenticationTicket(identity, context.Ticket.Properties);
     context.Validated(ticket);
     return base.GrantRefreshToken(context);
 }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context) {
            var clientId = context.Ticket.Properties.Dictionary["client_id"];
            if (clientId != context.ClientId) {
                context.Rejected();
                return;
            }

            var properties = new AuthenticationProperties(new Dictionary<string, string>
            {
                {"client_id", context.ClientId}
            });

            var ticket = new AuthenticationTicket(context.Ticket.Identity, properties);
            context.Validated(ticket);
        }