public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var usedRefreshTokenWasExpired = context.OwinContext.Get <bool>("as:refreshTokenExpired");

            if (usedRefreshTokenWasExpired)
            {
                context.SetError("invalid_refreshtoken", "The refreshtoken has expired.");
                return(Task.CompletedTask);
            }

            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.CompletedTask);
            }

            var newIdentity = new ClaimsIdentity(context.Ticket.Identity); //though here you can change existing claims with updated claims.
            var newTicket   = new AuthenticationTicket(newIdentity, context.Ticket.Properties);

            context.Validated(newTicket);

            //var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
            //identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            //identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            //context.OwinContext.Authentication.SignIn(identity);
            return(Task.CompletedTask);
        }
Ejemplo n.º 2
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (string.IsNullOrEmpty(context.ClientId))
            {
                context.SetError("invalid_grant", "Invalid token requrst.");
                return(Task.FromResult <object>(null));
            }
            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 client.");
                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));
        }
Ejemplo n.º 3
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["client_id"];
            var currentClient  = context.ClientId;

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

            var id           = context.Ticket.Identity.GetUserId();
            var userManager  = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var tokenService = UnityConfig.Container.Resolve <ITokenService>();

            var user = userManager.FindById(id);

            if (user == null)
            {
                context.SetError("refresh_token", Resources.Resource.UsernameOrPasswordNotValid);
                return;
            }
            if (!user.IsActive)
            {
                context.SetError("refresh_token", Resources.Resource.UserAccountNotActive);
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

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

            context.Validated(ticket);
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var userId = context.Ticket.Properties.Dictionary["userId"];

            if (string.IsNullOrEmpty(userId))
            {
                context.SetError("invalid_grant", "User Id not set.");
                return(Task.FromResult <object>(null));
            }

            var             userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            ApplicationUser user        = userManager.Users.Single(i => i.Id == userId);

            if (user == null)
            {
                context.SetError("invalid_grant", "User not found.");
                return(Task.FromResult <object>(null));
            }

            if (!user.IsActive)
            {
                context.SetError("invalid_grant", "Error logging in user.");
                return(Task.FromResult <object>(null));
            }

            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            // newIdentity.AddClaim(new Claim(Consts.CLAIM_USERPROFILEID, userProfileId));

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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 5
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            try
            {
                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);
                newIdentity.AddClaim(new Claim("newClaim", "newValue"));

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

                return(Task.FromResult <object>(null));
            }
            catch (Exception ex)
            {
                var msg = FWUtils.ExpLogUtils.ExceptionTranslator.TryToTranslate(ex).Message;
                context.SetError("error", msg);
                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));
            }

            if (currentClient != ClientId)
            {
                context.SetError("invalid_clientId", "Incorrect client id found in token.");

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

            using (var db = new Models.APIContext())
            {
                var user = db.Users
                           .Where(u => u.Id == int.Parse(context.Ticket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value))
                           .FirstOrDefault();

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

                // Change auth ticket for refresh token requests
                var newIdentity = GetIdentityFromUser(db, user, context.Options.AuthenticationType);

                var newTicket = new AuthenticationTicket(newIdentity, BuildTicketProperties(db, user, context.ClientId == null ? String.Empty : context.ClientId));
                context.Validated(newTicket);

                return(Task.FromResult <object>(null));
            }
        }
Ejemplo n.º 8
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            if (!ObjectId.TryParse(context.ClientId, out var mongoObjectId))
            {
                context.SetError("invalid_request");
                return;
            }
            var client = await _clientManager.FindClientByIdAsync(context.ClientId);

            if (client == null || !client.IsActive)
            {
                context.SetError("invalid_client");
                return;
            }
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType, client.Name, "client_application");

            oAuthIdentity.AddClaim(new Claim("client_id", context.ClientId));
            foreach (var scope in client.Scopes)
            {
                oAuthIdentity.AddClaim(new Claim(CustomClaimTypes.AuthorisedScopes, scope));
            }
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            ticket.Properties.Dictionary.Add("client_id", client.Id);
            context.Validated(ticket);
        }
Ejemplo n.º 9
0
        /// <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)
        {
            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;
            }

            var applicationUserManager = context.OwinContext.Get <ApplicationUserManager>();

            var identityUser = await this.FindUserFromTicket(applicationUserManager, context);

            if (identityUser.AccessRevokedDate != null)
            {
                context.SetError("invalid_grant", "User access is revoked.");
                return;
            }

            var newIdentity = await ProviderUtils.GenerateUserIdentityAsync(applicationUserManager, identityUser);

            var authenticationProperties = this.GetAuthenticationProperties(context.ClientId, newIdentity, identityUser);

            var newTicket = new AuthenticationTicket(newIdentity, authenticationProperties);

            await UpdateLastActivity(identityUser.Id);

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

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

            var usuarioClaim    = newIdentity.FindFirst(Constant.ClaimTypes.Usuario.UsuarioId);
            var aplicacionClaim = newIdentity.FindFirst(Constant.ClaimTypes.AplicacionId);
            var empresaClaim    = newIdentity.FindFirst(Constant.ClaimTypes.EmpresaId);

            if (usuarioClaim == null || aplicacionClaim == null || empresaClaim == null)
            {
                context.SetError("invalid_access", "Invalid token.");
                return(Task.FromResult <object>(null));
            }

            #region Update User Tasks
            List <Tarea> tasks;
            //Retrieve tasks
            using (IAccountService accountService = new AccountService(new AccountInfrastructure(new SqlServerAccess <Usuario>("ASConnectionString"))))
            {
                tasks = accountService.GetUserTasks(new Core.Entities.Filter.Filter {
                    UsuarioId = int.Parse(usuarioClaim.Value), EmpresaId = int.Parse(empresaClaim.Value), AplicacionId = int.Parse(aplicacionClaim.Value)
                });
                if (tasks == null)
                {
                    context.SetError("invalid_access", "The user has not access to the application.");
                    return(Task.FromResult <object>(null));
                }
            }
            //Remove previous tasks
            var claimsTareas = newIdentity.Claims;
            foreach (var claim in claimsTareas)
            {
                if (claim.Type == Constant.ClaimTypes.Tarea)
                {
                    newIdentity.RemoveClaim(claim);
                }
            }
            //Add new tasks
            foreach (var task in tasks)
            {
                newIdentity.AddClaim(new Claim(Constant.ClaimTypes.Tarea, task.Codigo));
            }
            #endregion

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

            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 11
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.SetError("NOT_LOGIN", "登录失败");
                context.SetError("ErrorCode", "ERROR_LOGIN");
                context.SetError("res_code", "60007");
                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);

            #region 当前用户信息
            //var rep = ContainerManager.Resolve<IEfRepository>();
            //var cache = ContainerManager.Resolve<ICacheManager>();
            //var companyCode = context.OwinContext.Environment["companyCode"].ToString();
            //var culture = context.OwinContext.Environment["culture"].ToString();
            //var user = ContainerManager.Resolve<IAuthRepository>().FindUser(context.Ticket.Identity.Name, companyCode);
            //cache.Clear();
            //var workUser = new WorkUser
            //{
            //    User = user,
            //    Culture = culture,
            //    RoleCodeList = rep.All<T_SysRoleUser>().Where(c => c.IsDeleted != 1 && c.UserID == user.Id && c.CompanyCode == user.CompanyCode).Select(s => s.RoleCode).ToList(),
            //    Position = (from p in rep.All<T_SysPosition>()
            //                join u in rep.All<T_SysOrgUser>() on p.Id equals u.PosID
            //                where u.UserID == user.Id && p.CompanyCode == user.CompanyCode
            //                select p).FirstOrDefault() ?? new T_SysPosition(),
            //    Orgnation = (from o in rep.All<T_SysOrgnation>()
            //                 join u in rep.All<T_SysOrgUser>() on o.OrgCode equals u.OrgCode
            //                 where u.UserID == user.Id && o.CompanyCode == user.CompanyCode
            //                 select o).FirstOrDefault() ?? new T_SysOrgnation(),
            //    CompanyCode = companyCode
            //};
            //cache.Set("CurrentUser", workUser, 12);
            #endregion
            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 12
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);
        }
        //called when HTTP GET /Token with "grant_type" of "refresh_token"
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary[Constants.KEY_CLIENT_ID];
            var currentClient  = context.ClientId;

            //var currentClient = context.OwinContext.Get<string>(Constants.KEY_CLIENT_ID);

            if (originalClient != currentClient)
            {
                context.SetError(Constants.INVALID_CLIENT_ID, "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);

            //we can add some new claims here:
            //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));
        }
Ejemplo n.º 14
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.");
                return(Task.FromResult <object>(null));
            }

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

            //var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
            //string usuario = principal.Claims.ToList()[1].ToString();
            // TODO Alvaro Actualizar funcionalidades

            /* string perfilId = "";
             * foreach (RolDto role in queryResult.UsuarioDto.Roles)
             *  perfilId += role.Id;
             *
             * FuncionalidadesSingleton.Instance.replaceFuncionalidades(perfilId, queryResult.FuncionalidadesDto);*/


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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 15
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));
        }
Ejemplo n.º 16
0
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            var userId      = Guid.Parse(newIdentity.GetUserId());

            var container = new UnityContainer();

            container.RegisterType <IRequestInfo, RequestInfo>();
            container.RegisterType <IPositionDataSource, PositionDataSource>();
            container.RegisterType <IPositionService, PositionService>();
            IPositionService _positionService = container.Resolve <IPositionService>();

            var getDefaultPositionResult = _positionService.PositionDefault(userId);

            if (!getDefaultPositionResult.Success)
            {
                context.SetError("invalid_user", getDefaultPositionResult.Message);
                return(Task.FromResult(0));
            }
            var positionDefault = getDefaultPositionResult.Data;

            ReplaceClaim(newIdentity, Claims.ApplicationId, positionDefault.ApplicationID.ToString());
            ReplaceClaim(newIdentity, Claims.DepartmentId, positionDefault.DepartmentID.ToString());
            ReplaceClaim(newIdentity, Claims.PositionId, positionDefault.PositionID.ToString());
            ReplaceClaim(newIdentity, Claims.UserId, positionDefault.UserID.ToString());
            ReplaceClaim(newIdentity, Claims.UserName, positionDefault.UserName.ToString());

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

            context.Validated(newTicket);
            return(Task.FromResult(0));

            //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);
            }

            // 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);
        }
Ejemplo n.º 18
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("alerts:error.invalid_clientId", "Refresh token is issued to a different clientId.");
                return(Task.FromResult <object>(null));
            }

            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(nameof(newClaim), "newValue"));

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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 19
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”,“刷新令牌发给另一个clientId。");
                return(Task.FromResult <object>(null));
            }
            //更改刷新令牌请求的身份验证票证
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            newIdentity.AddClaim(new Claim("newClaim", "newValue"));
            var client  = context.OwinContext.Get <AuthorizationInfo>("client");
            var issued  = DateTime.Now;
            var expired = issued.AddMinutes(Convert.ToDouble(client.refresh_token_life_time));

            context.Ticket.Properties.Dictionary["issued"]  = issued.ToString("yyyy-MM-dd HH:mm:ss");
            context.Ticket.Properties.Dictionary["expires"] = expired.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 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);
            }
        }
        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));
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var  userIdClaim = context.Ticket.Identity.Claims.FirstOrDefault(i => i.Type == JwtRegisteredClaimNames.Sub);
            long userId;

            if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out userId))
            {
                context.SetError("invalid_grant", "The refresh token is invalid.");
                return(Task.FromResult <object>(null));
            }

            //var user = userService.GetById(userId);

            //if (user == null)
            //{
            //    context.SetError("invalid_grant", "The refresh token is invalid.");
            //    return Task.FromResult<object>(null);
            //}

            var user = new UserEntity
            {
                Id    = Guid.NewGuid(),
                Email = "*****@*****.**"
            };

            var ticket = CreateAuthTicket(user);

            context.Validated(ticket);

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

            if (clienteOriginal != clienteAtual)
            {
                context.SetError("invalid_clientId", "O Token Atualizado é diferente do emitido para o clienteId");

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

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

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

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

            newIdentity.AddClaim(new Claim("newIdentity", "newValue"));

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

            context.Validated(newTicket);

            return(Task.FromResult <object>(null));
        }
        // grant type = refresh_token
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var application = context.OwinContext.Get <IApplication>("oh:application");

            //-----------------------------------------------------------------------------------------------------------
            if (application != null)
            {
                context.OwinContext.Response.Headers.Remove("Access-Control-Allow-Origin");
                string[] origin = { "*" };
                if (application.AllowedOrigin != null)
                {
                    origin = application.AllowedOrigin.Split(',');
                }
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
            }
            //-----------------------------------------------------------------------------------------------------------
            if (context.Ticket != null)
            {
                context.Validated(new AuthenticationTicket(context.Ticket.Identity, context.Ticket.Properties));
            }
            else
            {
                context.SetError(Resources.InvalidUserRefreshToken);
            }
            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 25
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.");
                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 props = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:client_id", context.ClientId }
            });

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

            context.Validated(newTicket);
            // create metadata to pass on to refresh token provider


            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 26
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));
        }
Ejemplo n.º 27
0
        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_app_id"];
            var currentClient  = context.ClientId;

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


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

            context.Validated(newTicket);

            /*
             * the flow for the code will hit method “CreateAsync” in class “CustomRefreshTokenProvider”
             * and a new refresh token is generated and returned in the response along with the new access token.
             */
            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 28
0
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            try
            {
                var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                using (var usuarioBO = new APIUsuarioBO())
                {
                    APIUsuario usuario = usuarioBO.Consultar(context.Ticket.Properties.Dictionary["userName"]);

                    if (usuario == null)
                    {
                        NewRelic.Api.Agent.NewRelic.IgnoreTransaction();
                        context.SetError("Mensagem", "Usuário ou senha incorretos");
                        return;
                    }

                    context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromHours(usuario.HorasExpiracaoToken);
                    ClaimsIdentity oAuthIdentity = await usuarioBO.CriarIdentityAsync(usuario, userManager.UserTokenProvider);

                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, CreateProperties(usuario));
                    context.Validated(ticket);
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
            }
        }
        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;
            }

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

            var currentRole = newIdentity.Claims.Where(c => c.Type == ClaimTypes.Role);

            foreach (var role in currentRole)
            {
                newIdentity.RemoveClaim(role);
            }

            using (AuthRepository repo = new AuthRepository(context.OwinContext, Startup.DataProtectionProvider))
            {
                var user = repo.FindUser(context.Ticket.Identity.Name);
                foreach (var role in await repo.GetUserRoles(user.Id))
                {
                    newIdentity.AddClaim(new Claim(ClaimTypes.Role, role));
                }
            }

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

            context.Validated(newTicket);
        }
        /// <summary>
        /// Override method form Granting Refresh Token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            try
            {
                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.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));
            }
            catch (Exception ex)
            {
                Exception excep = new Exception("Exception occured in SimpleAuthorizationServerProvider.GrantRefreshToken method." + ex.Message);
                throw excep;
            }
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext oAuthGrantRefreshTokenContext)
        {
            var originalClient = oAuthGrantRefreshTokenContext.Ticket.Properties.Dictionary[Constants.ClientId];
            var userName       = oAuthGrantRefreshTokenContext.Ticket.Properties.Dictionary[Constants.Username];
            var currentClient  = oAuthGrantRefreshTokenContext.ClientId;

            User hPayUser = _hPayDomain.GetUser(userName);

            var newIdentity = new ClaimsIdentity(oAuthGrantRefreshTokenContext.Ticket.Identity);
            var newClaim    = newIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);

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

            newIdentity.AddClaim(new Claim(ClaimTypes.Name, hPayUser.UserFirstName + " " + hPayUser.UserLastName));

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

            oAuthGrantRefreshTokenContext.Validated(newIdentity);
        }
        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 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);
        }
        /*
        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);
        }
        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);
        }
        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);
        }
        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);
        }
        public override 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.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);
        }
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     string str = context.Ticket.Properties.Dictionary["as:client_id"];
     string clientId = context.ClientId;
     if (str != clientId)
     {
         context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
         return Task.FromResult((object)null);
     }
     var identity = new ClaimsIdentity(context.Ticket.Identity);
     AppAuthorizeAttribute.UpdateClientInfoCacheTime(identity, TimeSpan.FromDays(2.0));
     if (context.Ticket.Properties.Dictionary.ContainsKey("isFirstLogin"))
         context.Ticket.Properties.Dictionary["isFirstLogin"] = bool.FalseString;
     if (clientId == "MMuaVe")
     {
         foreach (string key in _mobileProfileClaims.Values)
         {
             if (context.Ticket.Properties.Dictionary.ContainsKey(key))
                 context.Ticket.Properties.Dictionary.Remove(key);
         }
     }
     var ticket = new AuthenticationTicket(identity, context.Ticket.Properties);
     context.Validated(ticket);
     return Task.FromResult((object)null);
 }
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     if (context.Ticket.Properties.Dictionary["as:client_id"] != context.ClientId)
     {
         context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
         return (Task)Task.FromResult<object>((object)null);
     }
     ClaimsIdentity identity = new ClaimsIdentity((IIdentity)context.Ticket.Identity);
     Claim claim = Enumerable.FirstOrDefault<Claim>(Enumerable.Where<Claim>(identity.Claims, (Func<Claim, bool>)(c => c.Type == "newClaim")));
     if (claim != null)
         identity.RemoveClaim(claim);
     identity.AddClaim(new Claim("newClaim", "newValue"));
     AuthenticationTicket ticket = new AuthenticationTicket(identity, context.Ticket.Properties);
     context.Validated(ticket);
     return (Task)Task.FromResult<object>((object)null);
 }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;
            IEnumerable<Role> roles;

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

            using (AuthRepository _repo = new AuthRepository())
            {
                roles = (IEnumerable<Role>)_repo.GetRoles(context.Ticket.Properties.Dictionary["userId"]);
            }

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

            //Upgrade roles according to Database info
            AuthenticationProperties props = context.Ticket.Properties;
            if (props.Dictionary.ContainsKey("roles")) props.Dictionary.Remove("roles");
            string jsonroles = JsonConvert.SerializeObject(roles, Formatting.None);
            props.Dictionary.Add("roles", jsonroles);

            var newTicket = new AuthenticationTicket(newIdentity, props);
            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");

            // 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);
            }
        }
        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)
        {
            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);
        }
Ejemplo n.º 46
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)
        {
            // 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);
        }
        //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 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);
        }
Ejemplo n.º 50
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);
        }