Learn More, Pay Less!
Limited Time Offer!

Activities of "jmalla.cp"

Hi,

I can't acces to the CurrentPrincipal from my application services.

Can you give me some examples please?

Thanks

  • ABP Framework version: v6.0.1
  • UI type: MVC
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): Tired
  • UI Theme: LeptonX: Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonX 1.0.0

I get strange behavior when running my project on my production service.

Everything starts up fine, but after a few minuts doing nothing on the web, when I run some action on the web, such as click menu option, the left hand menu disappear, and the web shows me that I'm not authorized. If I try to logout and go back in again the issue persists. I need to clean the browser cache and redis cache and then everything shows up.

Hi,

My cuestion is, how can I deny access some user/role that tries to access through some client_id?

Thanks

Question
  • ABP Framework version: v6.0.1
  • UI type: MVC
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): Tired

Hi,

I want to deny access from some client_id application with some role to some application sevice.

Is that possbile? How can I do that?

Thanks for all

Answer

Ok, thanks for your information

Answer

Hi,

Sorry maliming, Now it's going well, I think yesterday I was really obfuscated with this topic.

On the other hand, could you tell me if there is another option to create and maintain access tokens per user from the web interface?

Thanks

Question
  • ABP Framework version: v6.0.1
  • UI type: MVC
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): Tired
  • Exception message and stack trace:
  • Steps to reproduce the issue:"

Hi,

I want to publish an API access from a 3rd external party like a Postman.

These ara the step I followed: 1.- Create the new client_id 2.- Acced from Postman to the URI https://localhost:44335/connect/token with client_id, secret and more 3.- I have obtenied the access_token *****************************

But with this token I can't call the API, because the request is 401 Unauthorized

For example: https://localhost:44368/api/openiddict/applications with header => Authorization: Bearer *****************************

What am I doing wrong?

Thanks for all

Hi,

Now Everythink works fine.

Thanks for all.

And my code is

Code

public class SyncActiveFarmsWorker : HangfireBackgroundWorkerBase
    {
        private readonly FarmImportManager _farmImportManager;
        private readonly ExtendedIdentityUserImportManager _extendedIdentityUserImportManager;
        private readonly BreedingImportManager _breedingImportManager;
        private readonly IRepository<Farm, Guid> _farmRepository;
        private readonly IdentityUserManager _identityUserManager;
        private readonly IObjectMapper _objectMapper;

        public SyncActiveFarmsWorker(
            FarmImportManager farmImportManager,
            BreedingImportManager breedingImportManager,
            IRepository<Farm, Guid> farmRepository,
            ExtendedIdentityUserImportManager extendedIdentityUserImportManager,
            IdentityUserManager identityUserManager,
            IObjectMapper objectMapper)
        {
            RecurringJobId = nameof(SyncActiveFarmsWorker);
            CronExpression = Cron.Daily(20);
            _farmImportManager = farmImportManager;
            _breedingImportManager = breedingImportManager;
            _farmRepository = farmRepository;
            _extendedIdentityUserImportManager = extendedIdentityUserImportManager;
            _identityUserManager = identityUserManager;
            _objectMapper = objectMapper;
        }

        public override async Task DoWorkAsync(CancellationToken cancellationToken = default)
        {
            Logger.LogInformation("Executed Sync Agents..!");
            // Pending to recive information from support of ABP
            await ImportAllAgentsAsync();
            Logger.LogInformation("Executed Sync farms..!");
            await _farmImportManager.ImportAllActiveFarmsAsync();
            Logger.LogInformation("Executed Sync last active breedings..!");
            await ImportLastActiveBreedingsAsync();
        }

        private async Task ImportLastActiveBreedingsAsync()
        {
            List<Farm> farms = await _farmRepository.GetListAsync();

            foreach (var farm in farms)
            {
                await _breedingImportManager.ImportLastActiveBreedingsByFarmIdAsync(farm.EkonClientCodeId);
            }
        }

        private async Task ImportAllAgentsAsync()
        {
            AgentsImportDto input = new AgentsImportDto();
            input.AgentType = AgentType.Veterinarian;
            await _extendedIdentityUserImportManager.CreateAllUsersActiveFromExternalSericeAsync(input);

            input = new AgentsImportDto();
            input.AgentType = AgentType.Visitor;

            await _extendedIdentityUserImportManager.CreateAllUsersActiveFromExternalSericeAsync(input);

            input = new AgentsImportDto();
            input.AgentType = AgentType.Haulier;

            await _extendedIdentityUserImportManager.CreateAllUsersActiveFromExternalSericeAsync(input);
        }

    }
public class ExtendedIdentityUserImportManager : DomainService
    {
        private readonly AgentExternalService _agentExternalService;
        private readonly IOptions<IdentityOptions> _identityOptions;
        private readonly IdentityUserManager _identityUserManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IObjectMapper _objectMapper;
        private readonly IDistributedEventBus _distributedEventBus;

        public ExtendedIdentityUserImportManager(
            IOptions<IdentityOptions> identityOptions,
            IUnitOfWorkManager unitOfWorkManager,
            IObjectMapper objectMapper,
            IDistributedEventBus distributedEventBus,
            IdentityUserManager identityUserManager
            )
        {
            _agentExternalService = new AgentExternalService();
            _identityOptions = identityOptions;
            _unitOfWorkManager = unitOfWorkManager;
            _objectMapper = objectMapper;
            _distributedEventBus = distributedEventBus;
            _identityUserManager = identityUserManager;
        }

        public async Task<IdentityUserCreateDto> GetAgentToImport(AgentImportDto input)
        {
            AgentDto agent = new AgentDto();
            ExternalService.Contracts.Agents.AgentType agentType = (ExternalService.Contracts.Agents.AgentType)Enum.Parse(typeof(ExternalService.Contracts.Agents.AgentType), input.AgentType.ToString());

            if (!_agentExternalService.HaveService(agentType))
                throw new ServiceIsNotReady().WithData("Name", agentType.ToString());

            agent = await _agentExternalService.Services[agentType].GetAsync(input.AgentCode);

            IdentityUserCreateDto identityUserCreateDto = GetIdentityUserCreateDtoFromExternalAgent(agent, input.AgentType);

            return identityUserCreateDto;
        }

        private IdentityUserCreateDto GetIdentityUserCreateDtoFromExternalAgent(AgentDto agent, AgentType agentType)
        {
            IdentityUserCreateDto identityUserCreateDto = new IdentityUserCreateDto();
            identityUserCreateDto.Name = agent.Name;
            identityUserCreateDto.Surname = agent.Surname;
            identityUserCreateDto.SetAgentType(agentType);
            identityUserCreateDto.SetAgentErpId(agent.Code);
            identityUserCreateDto.UserName = agent.Username;
            identityUserCreateDto.Email = agent.Email;
            identityUserCreateDto.SetDefaultPassword();

            return identityUserCreateDto;
        }

        public async Task<List<IdentityUserCreateDto>> GetAllActiveAgents(AgentType agentTypeToImport)
        {
            ExternalService.Contracts.Agents.AgentType agentType = (ExternalService.Contracts.Agents.AgentType)Enum.Parse(typeof(ExternalService.Contracts.Agents.AgentType), agentTypeToImport.ToString());

            if (!_agentExternalService.HaveService(agentType))
                throw new ServiceIsNotReady().WithData("Name", agentType.ToString());

            List<AgentDto> agentsToImport = await _agentExternalService.Services[agentType].GetAllActiveAsync();

            if (agentsToImport == null || agentsToImport.Count == 0)
                return new List<IdentityUserCreateDto>();

            return agentsToImport.Select(x => GetIdentityUserCreateDtoFromExternalAgent(x, agentTypeToImport)).ToList();
        }

        public async Task<IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input)
        {
            await _identityOptions.SetAsync();

            var user = await _identityUserManager.GetByIdAsync(id);

            using (var uow = _unitOfWorkManager.Begin(
                requiresNew: true, isTransactional: false
            ))
            {
                user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);

                (await _identityUserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();
                
                await UpdateUserByInput(user, input);
                
                input.MapExtraPropertiesTo(user);
                
                (await _identityUserManager.UpdateAsync(user)).CheckErrors();

                await uow.CompleteAsync();
            }

            var userDto = _objectMapper.Map<IdentityUser, IdentityUserDto>(user);

            return userDto;
        }

        private async Task UpdateUserByInput(IdentityUser user, IdentityUserCreateOrUpdateDtoBase input)
        {
            if (!string.Equals(user.Email, input.Email, StringComparison.InvariantCultureIgnoreCase))
            {
                (await _identityUserManager.SetEmailAsync(user, input.Email)).CheckErrors();
            }

            if (!string.Equals(user.PhoneNumber, input.PhoneNumber, StringComparison.InvariantCultureIgnoreCase))
            {
                (await _identityUserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors();
            }

            (await _identityUserManager.SetLockoutEnabledAsync(user, input.LockoutEnabled)).CheckErrors();

            user.Name = input.Name;
            user.Surname = input.Surname;
            (await _identityUserManager.UpdateAsync(user)).CheckErrors();
            user.SetIsActive(input.IsActive);
            
            (await _identityUserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors();
        }

        public async Task<IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            await _identityOptions.SetAsync();

            var user = new IdentityUser(
                GuidGenerator.Create(),
                input.UserName,
                input.Email,
                CurrentTenant.Id
            );

            input.MapExtraPropertiesTo(user);

            using (var uow = _unitOfWorkManager.Begin(
                requiresNew: true, isTransactional: false
            ))
            {
                (await _identityUserManager.CreateAsync(user, input.Password)).CheckErrors();
                
                await UpdateUserByInput(user, input);
                
                (await _identityUserManager.UpdateAsync(user)).CheckErrors();
                
                await uow.CompleteAsync();
            }

            await _distributedEventBus.PublishAsync(new IdentityUserCreatedEto()
            {
                Id = user.Id,
                Properties =
                {
                    { "SendConfirmationEmail", input.SendConfirmationEmail.ToString().ToUpper() },
                    { "AppName", "MVC" }
                }
            });

            var userDto = _objectMapper.Map<IdentityUser, IdentityUserDto>(user);

            return userDto;
        }

        public async Task CreateAllUsersActiveFromExternalSericeAsync(AgentsImportDto input)
        {
            List<IdentityUserCreateDto> identityUsersToImport = await GetAllActiveAgents(input.AgentType);

            foreach (var identityUserToImport in identityUsersToImport)
            {
                AssignRoleToUserFromAgentType(identityUserToImport);

                await CreateOrUpdateIdentityUser(identityUserToImport);
            }
        }

        private void AssignRoleToUserFromAgentType(IdentityUserCreateDto identityUserToImport)
        {
            if (identityUserToImport.RoleNames == null)
                identityUserToImport.RoleNames = new string[1];

            identityUserToImport.RoleNames[0] = identityUserToImport.GetAgentType().GetRoleName();
        }

        private async Task<IdentityUserDto> CreateOrUpdateIdentityUser(IdentityUserCreateDto input)
        {
            IdentityUser identityUser = await _identityUserManager.FindByNameAsync(input.UserName);

            Guid? userId = identityUser?.Id;

            if (identityUser != null && !identityUser.IsActive)
            {
                var userUpdateDto = _objectMapper.Map<IdentityUserCreateDto, IdentityUserUpdateDto>(input);

                IdentityUserDto userUpdated = await UpdateAsync(identityUser.Id, userUpdateDto);
                userId = userUpdated.Id;
            }
            else if (identityUser == null)
            {
                IdentityUserDto createdUser = await CreateAsync(input);
                userId = createdUser.Id;
            }

            return _objectMapper.Map<IdentityUser, IdentityUserDto>(await _identityUserManager.GetByIdAsync((Guid)userId));
        }
    }

Thanks for all

System.ArgumentNullException Value cannot be null. (Parameter 'roleNames')

Please check this line: (await _identityUserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors();

The input.RoleNames is null.

Hi,

I solved It, but now I have this new issue Exception

Failed

An exception occurred during performance of the job.
System.InvalidOperationException

The instance of entity type 'IdentityUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

System.InvalidOperationException: The instance of entity type 'IdentityUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at Volo.Abp.Domain.Repositories.EntityFrameworkCore.EfCoreRepository`2.UpdateAsync(TEntity entity, Boolean autoSave, CancellationToken cancellationToken)
   at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
   at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
   at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
   at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
   at Volo.Abp.Identity.IdentityUserStore.UpdateAsync(IdentityUser user, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.UpdateUserAsync(TUser user)
   at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
   at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
   at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
   at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
   at Microsoft.AspNetCore.Identity.UserManager`1.SetUserNameAsync(TUser user, String userName)
   at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo)
   at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue`1.ProceedAsync()
   at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
   at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
   at Cincaporc.WebApp.ExtendedIdentityUsers.ExtendedIdentityUserImportManager.UpdateAsync(Guid id, IdentityUserUpdateDto input) in C:\Users\jmalla\source\Cincaporc.WebApp\src\Cincaporc.WebApp.Domain\ExtendedIdentityUsers\ExtendedIdentityUserImportManager.cs:line 101
   at Cincaporc.WebApp.ExtendedIdentityUsers.ExtendedIdentityUserImportManager.CreateOrUpdateIdentityUser(IdentityUserCreateDto input) in C:\Users\jmalla\source\Cincaporc.WebApp\src\Cincaporc.WebApp.Domain\ExtendedIdentityUsers\ExtendedIdentityUserImportManager.cs:line 212
   at Cincaporc.WebApp.ExtendedIdentityUsers.ExtendedIdentityUserImportManager.CreateAllUsersActiveFromExternalSericeAsync(AgentsImportDto input) in C:\Users\jmalla\source\Cincaporc.WebApp\src\Cincaporc.WebApp.Domain\ExtendedIdentityUsers\ExtendedIdentityUserImportManager.cs:line 190
   at Cincaporc.WebApp.BackgroundServices.Farms.SyncActiveFarmsWorker.ImportAllAgentsAsync() in C:\Users\jmalla\source\Cincaporc.WebApp\src\Cincaporc.WebApp.BackgroundServices\Farms\SyncActiveFarmsWorker.cs:line 67
   at Cincaporc.WebApp.BackgroundServices.Farms.SyncActiveFarmsWorker.DoWorkAsync(CancellationToken cancellationToken) in C:\Users\jmalla\source\Cincaporc.WebApp\src\Cincaporc.WebApp.BackgroundServices\Farms\SyncActiveFarmsWorker.cs:line 46
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

Showing 61 to 70 of 76 entries
Made with ❤️ on ABP v9.2.0-preview. Updated on February 07, 2025, 05:40