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.");
                return Task.FromResult<object>(null);
            }

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

            var newClaim = newIdentity.Claims.FirstOrDefault(c => c.Type == "newClaim");
            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

            return Task.FromResult<object>(null);
        }
Exemplo n.º 2
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

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

            return Task.FromResult<object>(null);
        }
Exemplo n.º 3
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // 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(base.GrantRefreshToken(context));
        }
Exemplo n.º 4
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            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 newId = new ClaimsIdentity(context.Ticket.Identity);

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

            await Task.Run(() =>
            {
                var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
                context.Validated(newTicket);
            });
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Change auth ticket for refresh token requests
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindByNameAsync(context.Ticket.Identity.Name);

            var newIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);
        }
Exemplo n.º 7
0
 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");
     }
     else
     {
         //Additional claim is needed to separate access token updating from authentication
         //requests in RefreshTokenProvider.CreateAsync() method
     }
     return(base.GrantRefreshToken(context));
 }
Exemplo n.º 8
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Change auth ticket for refresh token requests
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user = await userManager.FindByNameAsync(context.Ticket.Identity.Name);

            var newIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

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

            context.Validated(newTicket);
        }
Exemplo n.º 9
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var identity     = context.Ticket.Identity;
            var id           = identity.GetUserId();
            var domain       = identity.FindFirst("ac_domain");
            var companyToken = identity.FindFirst("c_token");

            Identity.AdobeConnectUser user = null;
            using (Identity.AdobeConnectUserManager userManager = _userManagerFactory())
            {
                try
                {
                    user = await userManager.RefreshSession(id, companyToken.Value, domain.Value, identity.Name);

                    _logger?.Info($"[GrantRefreshToken.AfterLogin] ACSession={user.AcSessionToken}");
                }
                catch (Exception ex)
                {
                    // TODO: production-ready exceptions
                    context.SetError("server_error", ex.Message);
                    return;
                }
            }

            if (user == null)
            {
                context.SetError("token_refresh_error", "User session has not been updated successfully.");
                return;
            }
            // check for existing claim and remove it
            var existingClaims = identity.Claims.Where(x => x.Type == "ac_session" || x.Type == ClaimTypes.Role);

            foreach (var existingClaim in existingClaims)
            {
                identity.RemoveClaim(existingClaim);
            }

            identity.AddClaim(new Claim("ac_session", user.AcSessionToken));

            if (user.Roles != null)
            {
                foreach (var role in user.Roles)
                {
                    var roleClaim = new Claim(ClaimTypes.Role, role);
                    identity.AddClaim(roleClaim);
                }
            }
            context.Validated(context.Ticket);
            _logger?.Info($"[GrantRefreshToken.Success] PrincipalId={user.Id}, ACSession={context.Ticket.Identity.FindFirst("ac_session")}");
            //            return Task.FromResult<object>(null);
        }
Exemplo n.º 10
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            string originalClient = context.Ticket.Properties.Dictionary["Client_Id"];
            string currentClient  = context.ClientId;

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

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 11
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();
        }
Exemplo n.º 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 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.");
                return(Task.FromResult <object>(null));
            }

            context.Validated(new AuthenticationTicket(context.Ticket.Identity, context.Ticket.Properties));

            return(Task.FromResult <object>(null));
        }
        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.");
                return Task.FromResult<object>(null);
            }

            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            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.ClientId;

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

            var newIdentity = await DoGrantRefreshToken(context);

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

            context.Validated(newTicket);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 验证持有 refresh token 的 clientId
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClientId = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClientId  = context.ClientId;

            if (originalClientId != currentClientId)
            {
                await Task.FromResult <object>(null);
            }

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

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

            context.Validated(newTicket);
        }
        /// <summary>
        /// 客户端模式 重载RefreshToken分发
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            try
            {
                var newId = new ClaimsIdentity(context.Ticket.Identity);
                newId.AddClaim(new Claim("newClaim", "refreshToken"));

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

                await base.GrantRefreshToken(context);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 18
0
 //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);
     }));
 }
Exemplo n.º 19
0
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            var newClaim = newIdentity.Claims.Where(c => c.Type == "newClaim").FirstOrDefault();

            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

            context.Validated(newTicket);

            return(Task.FromResult(0));
        }
Exemplo n.º 20
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 Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //var oAuthIdentity = new ClaimsIdentity();
            //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "jeremy"));
            //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            //var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties { AllowRefresh = true, RedirectUri = "/token", IssuedUtc = DateTime.Now, ExpiresUtc = DateTime.Now.AddMonths(1)});
            //context.Validated(context.Ticket);
                        
            var originalClient = "jeremy";
            var currentClient = context.OwinContext.Get<string>("as:client_id");

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

        }
Exemplo n.º 22
0
        /// <summary>
        /// 授予刷新令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("无效的客户端信息", "刷新令牌是来自一个不同的客户ID。");
                return(Task.FromResult <object>(null));
            }
            // Change auth ticket for refresh token requests 改变授权票刷新令牌的请求
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket   = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 23
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

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

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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 24
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

            var originalIPAddress = context.Ticket.Properties.Dictionary["ip_address"];
            var currentIPAddress  = HttpContext.Current.Request.Form["ip_address"];

            var originalUserAgent = context.Ticket.Properties.Dictionary["user_agent"];
            var currentUserAgent  = HttpContext.Current.Request.Form["user_agent"];


            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return(Task.FromResult <object>(null));
            }
            if (TokenHelper.ValidateIPAddress())
            {
                if (originalIPAddress != currentIPAddress)
                {
                    context.SetError("invalid_IP_Address", "Refresh token is issued to a different IP Address.");
                    return(Task.FromResult <object>(null));
                }
            }
            if (TokenHelper.ValidateUserAgent())
            {
                if (originalUserAgent != currentUserAgent)
                {
                    context.SetError("invalid_User_Agent", "Refresh token is issued to a different device.");
                    return(Task.FromResult <object>(null));
                }
            }
            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            newIdentity.AddClaim(new System.Security.Claims.Claim("newClaim", "newValue"));

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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
        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);
        }
Exemplo n.º 26
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // TODO: Implement this when each member website has their own ClientID
            //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;
            //}

            var identity  = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket = new AuthenticationTicket(identity, context.Ticket.Properties);

            context.Validated(newTicket);
            return(Task.FromResult(0));
        }
Exemplo n.º 27
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            using (var repo = new ApplicationUserManager(new UserStore <ApplicationUser>()))
            {
                var user = repo.Users.SingleOrDefault(u => u.UserName == context.Ticket.Identity.Name);

                if (user == null)
                {
                    // unlikely, but it's possible the account has been deleted
                    context.SetError("invalid_grant", "Account does not exist.");

                    return;
                }


                context.Validated();
                this.LogInfo("Successfully refreshed {0}'s auth token.", user.UserName);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// RefreshToken
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            context.OwinContext.Set(_asGrantType, GrantTypes.RefreshToken);
            context.OwinContext.Set(_asClientID, context.ClientId);
            var newId = new ClaimsIdentity(context.Ticket.Identity);
            var role  = newId.FindFirstValue(newId.RoleClaimType);

            if (role != null)
            {
                if (role.Split(',').All(c => !c.Equals(RoleConfig.AppRole, StringComparison.OrdinalIgnoreCase)))
                {
                    context.OwinContext.Set(_asUserID, newId.GetUserId());
                }
            }
            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);
        }
Exemplo n.º 30
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return(Task.FromResult <object>(null));
            }
            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            newIdentity.AddClaim(new Claim("newClaim", "newValue"));
            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 31
0
        //http://discoveringdotnet.alexeyev.org/2014/08/simple-explanation-of-bearer-authentication-for-web-api-2.html
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //enforce client binding of refresh token
            if (context.Ticket == null || context.Ticket.Identity == null || !context.Ticket.Identity.IsAuthenticated)
            {
                context.SetError("invalid_grant", "Refresh token is not valid");
            }
            else
            {
                var userIdentity         = context.Ticket.Identity;
                var authenticationTicket = await CreateAuthenticationTicket(context.OwinContext, userIdentity);

                //Additional claim is needed to separate access token updating from authentication
                //requests in RefreshTokenProvider.CreateAsync() method
                authenticationTicket.Identity.AddClaim(new Claim("refreshToken", "refreshToken"));

                context.Validated(authenticationTicket);
            }
        }
        /// <summary>
        ///  Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token"
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            logger.Debug("GrantRefreshToken");
            if (context.Ticket.Properties != null)
            {
                logger.Debug("GrantResourceOwnerCredentials,context.Ticket.Properties:" + JsonConvert.SerializeObject(context.Ticket.Properties));
            }
            string error            = "invalid_grant";
            var    originalClientId = context.OwinContext.Get <string>(OAuthKeys.ClientId);
            var    currentClientId  = context.ClientId;

            if (!string.IsNullOrEmpty(originalClientId) && !string.IsNullOrEmpty(currentClientId))
            {
                if (originalClientId != currentClientId)
                {
                    context.SetError(error, "Refresh token is issued to a different clientId.");
                }
                else
                {
                    // Change auth ticket for refresh token requests
                    var newOAuthIdentity = new ClaimsIdentity(context.Ticket.Identity);

                    //获取附加的请求参数
                    IDictionary <string, object> parameters = context.OwinContext.Environment;
                    if (parameters != null)
                    {
                        //foreach (var item in parameters)
                        //{
                        //    //添加附加凭证信息
                        //    newOAuthIdentity.AddClaim(new Claim(OAuthKeys.Prefix + item.Key, item.Value.ToString()));
                        //}
                    }
                    newOAuthIdentity.AddClaim(new Claim(OAuthKeys.RefreshTokenClaim, "refreshToken"));
                    var  newTicket      = new AuthenticationTicket(newOAuthIdentity, context.Ticket.Properties);
                    bool validateResult = context.Validated(newTicket);
                    if (!validateResult)
                    {
                        context.SetError(error, "validate 失败");
                    }
                }
            }
            await base.GrantRefreshToken(context);
        }
Exemplo n.º 33
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);
        }
Exemplo n.º 34
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var identity   = new ClaimsIdentity(context.Ticket.Identity);
            var properties = context.Ticket.Properties.Dictionary;

            ViewUser user = null;

            using (var auth = new AuthRepository())
                user = await auth.ViewUserGetAsync(Guid.Parse(identity.GetUserId()));

            if (object.Equals(user, null) || !user.IsActive)
            {
                return;
            }

            identity.AddClaims(user);

            context.Validated(new AuthenticationTicket(identity, context.Ticket.Properties));
        }
Exemplo n.º 35
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //var originalClient = context.Ticket.Identity.Claims.FirstOrDefault(x => x.Type == "aud").Value;
            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.");
                return(Task.FromResult <object>(null));
            }

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

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

            context.Validated(newTicket);
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 36
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");

            //       var currentClient = context.OwinContext.Request.Get<string>("as:client_id");

            ////var currentClient = context.ClientId;
            //http://leastprivilege.com/2013/11/15/adding-refresh-tokens-to-a-web-api-v2-authorization-server/
            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return(Task.FromResult <object>(null));
            }

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

            var renwewRefreshToken = newIdentity.Claims.Where(c => c.Type == "RenwewRefreshToken").FirstOrDefault();

            if (renwewRefreshToken != null)
            {
                newIdentity.RemoveClaim(renwewRefreshToken);
            }

            newIdentity.AddClaim(new Claim("RenwewRefreshToken", DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss")));


            //  var currentClient = context.OwinContext.Get<string>("m:expiredOn");
            if (context.Ticket.Properties.Dictionary != null && context.Ticket.Properties.Dictionary.ContainsKey("m:expiredOn"))
            {
                //refresh custom expire date
                var expiredOn = DateTime.UtcNow.AddMinutes(General.MAXMinutesExpiredApiToken);
                context.Ticket.Properties.Dictionary["m:expiredOn"] = expiredOn.ToString("yyyy-MM-dd HH:mm:ss");
            }


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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var identity   = new ClaimsIdentity(context.Ticket.Identity);
            var properties = context.Ticket.Properties.Dictionary;

            var client       = context.OwinContext.Get <Client>("client");
            var sessionToken = context.OwinContext.Get <SessionToken>("sessionToken");

            properties["session"] = Guid.NewGuid().ToString("N");

            if (!string.IsNullOrEmpty(sessionToken.ExternalClientName))
            {
                properties["externalClient"] = sessionToken.ExternalClientName;
            }

            string[] scope = context.OwinContext.Get <string[]>("scope");

            var accountId = Guid.Parse(identity.GetUserId());

            using (var auth = new AuthRepository())
            {
                using (var authProduct = new AuthProductRepository())
                {
                    var account = await auth.AccountGetAsync(accountId);

                    if (object.Equals(account, null))
                    {
                        return;
                    }

                    context.OwinContext.Set("user", account);

                    identity.TryRemoveClaim("module");
                    identity.AddClaims(account, client);

                    var scopeWorker = SaaSScopeWorkerFactory.Create(scope, context, auth, authProduct);
                    await scopeWorker.GrantClaims(identity);
                }
            }

            context.Validated(new AuthenticationTicket(identity, context.Ticket.Properties));
        }
Exemplo n.º 38
0
        public async Task WhenGrantingRefreshToken_AndItSucceedes_ItShouldUpdateTheAccessTokenTimestamp()
        {
            var context = new OAuthGrantRefreshTokenContext(
                new OwinContext(this.environment),
                new OAuthAuthorizationServerOptions()
            {
                AuthenticationType = AuthenticationType
            },
                new AuthenticationTicket(
                    new ClaimsIdentity(
                        new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, UserClaimsIdentity.UserId.Value.EncodeGuid())
            },
                        AuthenticationType),
                    new AuthenticationProperties(new Dictionary <string, string> {
                { Constants.TokenClientIdKey, ClientId }
            })),
                ClientId);

            this.getUserClaimsIdentity
            .Setup(v => v.HandleAsync(new GetUserClaimsIdentityQuery(UserClaimsIdentity.UserId, null, null, AuthenticationType)))
            .ReturnsAsync(UserClaimsIdentity);

            UpdateLastAccessTokenDateCommand updateTimestampCommand = null;

            this.updateLastAccessTokenDate
            .Setup(v => v.HandleAsync(It.IsAny <UpdateLastAccessTokenDateCommand>()))
            .Callback <UpdateLastAccessTokenDateCommand>(v => updateTimestampCommand = v)
            .Returns(Task.FromResult(0));

            var before = DateTime.UtcNow;

            await this.target.GrantRefreshTokenAsync(context);

            var after = DateTime.UtcNow;

            Assert.IsNotNull(updateTimestampCommand);
            Assert.AreEqual(UserClaimsIdentity.UserId, updateTimestampCommand.UserId);
            Assert.AreEqual(UpdateLastAccessTokenDateCommand.AccessTokenCreationType.RefreshToken, updateTimestampCommand.CreationType);
            Assert.IsTrue(updateTimestampCommand.Timestamp <= after);
            Assert.IsTrue(updateTimestampCommand.Timestamp >= before);
        }
 public abstract Task<ClaimsIdentity> DoGrantRefreshToken(OAuthGrantRefreshTokenContext context); 
        public override async 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.");
                return;
            }

            var newIdentity = await DoGrantRefreshToken(context);
            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);
        }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token". This occurs if your application has issued a "refresh_token" 
        ///             along with the "access_token", and the client is attempting to use the "refresh_token" to acquire a new "access_token", and possibly a new "refresh_token".
        ///             To issue a refresh token the an Options.RefreshTokenProvider must be assigned to create the value which is returned. The claims and properties 
        ///             associated with the refresh token are present in the context.Ticket. The application must call context.Validated to instruct the 
        ///             Authorization Server middleware to issue an access token based on those claims and properties. The call to context.Validated may 
        ///             be given a different AuthenticationTicket or ClaimsIdentity in order to control which information flows from the refresh token to 
        ///             the access token. The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the refresh token to 
        ///             the access token unmodified.
        ///             See also http://tools.ietf.org/html/rfc6749#section-6
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            this.options.Logger.Debug("Authenticating refresh token flow");

            var user = new SentinelPrincipal(context.Ticket.Identity);

            // Add grant type claim
            user.Identity.RemoveClaim(x => x.Type == ClaimType.GrantType);
            user.Identity.AddClaim(ClaimType.GrantType, GrantType.RefreshToken);

            // Activate event if subscribed to
            if (this.options.Events.PrincipalCreated != null)
            {
                var args = new PrincipalCreatedEventArgs(user, context);

                await this.options.Events.PrincipalCreated(args);

                user = new SentinelPrincipal(args.Principal);
            }

            context.Validated(user.Identity.AsClaimsIdentity());
        }
 public Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     throw new NotImplementedException();
 }
        /*
              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);
        }
Exemplo n.º 44
0
		public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
		{
			return base.GrantRefreshToken(context);
		}
        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.");

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

            // INFO: Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            
            // FIXME: Need to figure out how would I actually handle things here
            // This is a refresh token here, need to add proper claims and values here, but Im stuck like a moron
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

            context.Validated(newTicket);

            return Task.FromResult<object>(null);
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //We are reading the client id value from the original ticket, 
            //this is the client id which get stored in the magical signed string, 
            //then we compare this client id against the client id sent with the request, 
            //if they are different we’ll reject this request because we need to make 
            //sure that the refresh token used here is bound to the same client when it was generated.

            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.");
                return Task.FromResult<object>(null);
            }

            //We have the chance now to add new claims or remove existing claims, 
            //this was not achievable without refresh tokens, then we call 
            //“context.Validated(newTicket)” which will generate new access 
            //token and return it in the response body.


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

            var newClaim = newIdentity.Claims.Where(c => c.Type == "newClaim").FirstOrDefault();
            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

            return Task.FromResult<object>(null);

            //Lastly after this method executes successfully, the flow for the code 
            //will hit method “CreateAsync” in class “SimpleRefreshTokenProvider” 
            //and a new refresh token is generated and returned in the response 
            //along with the new access token.
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            /*ClientUserManager manager = context.OwinContext.GetUserManager<ClientUserManager>();
            ClientRoleManager managerRoles = context.OwinContext.Get<ClientRoleManager>();*/

            IDependencyScope Scope = context.OwinContext.Get<IDependencyScope>();
            ClientUserManager manager = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            ClientRoleManager managerRoles = Scope.GetService(typeof(ClientRoleManager)) as ClientRoleManager;

            var originalClient = context.Ticket.Properties.Dictionary[GenericNames.AUTHENTICATION_CLIENT_ID_KEY];
            var currentClient = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("client_id", GenericError.INVALID_GIVEN_PARAMETER);
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity(context.Ticket.Identity);
            var newTicket = new AuthenticationTicket(identity, context.Ticket.Properties);
            context.Validated(newTicket);
            return Task.FromResult<object>(null);
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //Se lee la información original del cliente
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;

            //Se compara el cliente firmado con el cliente recibido como parámetro
            if (originalClient != currentClient)
            {
                context.SetError("clientId_invalido", "El token emitido no concide con el cliente recibido");
                return Task.FromResult<object>(null);
            }

            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            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["as:client_id"];
            var currentClient = context.ClientId;

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

            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var userManager = context.OwinContext.GetUserManager<Identity.ApplicationUserManager>();

            DataLayer.Models.Identity.ApplicationUser user = await userManager.FindByNameAsync(context.Ticket.Identity.Name);

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);
        }
Exemplo n.º 50
0
 public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext 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);
        }
Exemplo n.º 52
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];

            if (originalClient != context.ClientId)
            {
                context.SetError("invalid_grant", TokenStatus.InvalidClientId.ToString());
                
            }
            else
            {
                var newId = new ClaimsIdentity(context.Ticket.Identity);
                var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
                context.Validated(newTicket);
            }

            
            
            return Task.FromResult<object>(null); ;
        }
        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);
        }
        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);
        }
        /// <summary>
        /// 授予刷新令牌
        /// 验证持有 refresh token 的客户端
        /// grant_type:refresh_token
        /// 如:grant_type=refresh_token&refresh_token=fd08939b38e94f0ba154b8c51f57d256fb919fc818f4437ea24fd30fbc7c1936
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //获取'第二步'创建的元数据
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];

            //获取用户信息、验证用户身份合法性

            // 刷新令牌请求更改身份验证的机会
            var newId = new ClaimsIdentity(context.Ticket.Identity);
            newId.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            bool flag = context.Validated(newTicket);
        }
        //TODO: common parts of grant refresh token and grant resource owner credentials to separate method
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var options = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            options.Converters.Insert(0, new HttpServiceErrorConverter());
            var identity = context.Ticket.Identity;
            if (identity == null)
            {
                context.SetError("Couldn't deserialize identity from refresh token.");
                return Task.FromResult<object>(null);
            }
            var userIdClaim = identity.FindFirst(ClaimTypes.Sid);
            if (userIdClaim == null)
            {
                context.SetError("Refresh token doesn't contain user id. Can't grant access.");
                return Task.FromResult<object>(null);
            }
            var container = context.OwinContext.GetAutofacLifetimeScope();
            var transactionFactory = container.Resolve<ITransactionFactory>();
            var membershipService = container.Resolve<IAuthorizationService>();
            var userId = Guid.Parse(userIdClaim.Value);
            UserIdentityModel user = null;
            var transaction = transactionFactory.BeginTransaction(IsolationLevel.ReadCommitted);
            try
            {
                user = membershipService.RefreshLogin(new IdentityQuery<Guid>(userId));
                transaction.Commit();
            }
            catch (SecurityException ex)
            {
                transaction.Commit();
                var errorJson = JsonConvert.SerializeObject(ex.UserMessage, options);
                context.SetError("LoginFailure", errorJson);
                return Task.FromResult<object>(null);
            }
            finally
            {
                transaction.Dispose();
            }
            if (user == null)
            {
                throw new InvalidOperationException("Refresh login returned null");
            }
            var newIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            foreach (var claimModel in user.Claims)
            {
                newIdentity.AddClaim(new Claim(claimModel.Type, claimModel.Value));
            }
            var client = context.OwinContext.Get<ApplicationClientModel>("vabank:client");
            newIdentity.AddClaim(new Claim(ClaimModel.Types.ClientId, client.Id));
            context.OwinContext.Set("vabank:user", user);

            // Set CORS header
            context.Response.Headers.Set("Access-Control-Allow-Origin", client.AllowedOrigin);

            // Set state as validated
            context.Validated(newIdentity);
            var cookieIdentity = new ClaimsIdentity(identity.Claims, CookieAuthenticationDefaults.AuthenticationType);
            context.Request.Context.Authentication.SignIn(cookieIdentity);

            return base.GrantRefreshToken(context);
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // pega o id do cliente gravado no ticket e o id do cliente da requisição
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;

            // se os ID forem diferentes
            if (originalClient != currentClient)
            {
                // invalida o cliente
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return;
            }

            // adiciona ou remove novas claims setadas para este determinado usuário
            var newIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            var usuarioDomain = new UsuarioDomain();
            var claimsCollection = await usuarioDomain.GetClaimsByUsernameAsync(context.Ticket.Identity.Name);
            if (claimsCollection != null)
                newIdentity.AddClaims(claimsCollection);

            // MOCKING START
            newIdentity.AddClaim(new Claim(ClaimTypes.Name, context.Ticket.Identity.Name));
            // MOCKING END

            // gera um novo ticket e valida o contexto fazendo gerar um novo token de acesso
            // e retorná-lo na resposta da requisição
            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);
        }
        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.");
                return Task.FromResult<object>(null);
            }

            var user = context.OwinContext.GetUserManager<ApplicationUserManager>().FindById(context.Ticket.Identity.GetUserId());

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return Task.FromResult<object>(null);
            }

            var identity = user.GenerateUserIdentity(context.OwinContext.GetUserManager<ApplicationUserManager>(), OAuthDefaults.AuthenticationType);
            
            var claimsList = identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
            var roles = "";

            if (claimsList.Count > 0)
            {
                roles = claimsList.Aggregate((i, j) => i + "," + j);
            }

            context.Ticket.Properties.Dictionary["Roles"] = roles;
            var newTicket = new AuthenticationTicket(identity, context.Ticket.Properties);
            context.Validated(newTicket);

            return Task.FromResult<object>(null);
        }
 /// <summary>
 /// Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token". This occurs if your application has issued a "refresh_token" 
 /// along with the "access_token", and the client is attempting to use the "refresh_token" to acquire a new "access_token", and possibly a new "refresh_token".
 /// To issue a refresh token the an Options.RefreshTokenProvider must be assigned to create the value which is returned. The claims and properties 
 /// associated with the refresh token are present in the context.Ticket. The application must call context.Validated to instruct the 
 /// Authorization Server middleware to issue an access token based on those claims and properties. The call to context.Validated may 
 /// be given a different AuthenticationTicket or ClaimsIdentity in order to control which information flows from the refresh token to 
 /// the access token. The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the refresh token to 
 /// the access token unmodified.
 /// See also http://tools.ietf.org/html/rfc6749#section-6
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     return OnGrantRefreshToken.Invoke(context);
 }
        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.");
                return Task.FromResult<object>(null);
            }

            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            // TODO
            //We have the chance now to add new claims or remove existing claims, 
            //this was not achievable without refresh tokens, then we call “context.Validated(newTicket)” which will generate new access token and return it in the response body.
            
            //newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

            //Lastly after this method executes successfully, the flow for the code will hit method “CreateAsync” in class “SimpleRefreshTokenProvider” 
            //and a new refresh token is generated and returned in the response along with the new access token.
            return Task.FromResult<object>(null);
        }