Base solution for your next web application
Open Closed

How to change custome session and store it hardly #9380


User avatar
0
kansoftware created

I created custom session using claim. check my complete code related to it.

First i created CustomeSession

namespace Ksoft.Authorization
{
   public class CustomSession : ClaimsAbpSession, ITransientDependency
    {
        public CustomSession(
        IPrincipalAccessor principalAccessor,
        IMultiTenancyConfig multiTenancy,
        ITenantResolver tenantResolver,
        IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) :
        base(principalAccessor, multiTenancy, tenantResolver, sessionOverrideScopeProvider)
        {

        }

        public string FinancialYear
        {
            get
            {
                var financialYearClaim = PrincipalAccessor.Principal?.Claims.
                    FirstOrDefault(c => c.Type == "Application_UserFinancial");
                if(string.IsNullOrEmpty(financialYearClaim?.Value)) {                    
                    return null;
                }                
                return financialYearClaim.Value;
            }
        }

    }
}

Then created CreateAsync override in UserClaimsPrincipalFactory.cs

        public override async Task<ClaimsPrincipal> CreateAsync(User user)
        {
            var claim = await base.CreateAsync(user);       
            var TenantId = user.TenantId;
            long financialYearId = 0;
            var financialList = await _financialYearRepository.GetAllListAsync(c => c.TenantId == TenantId && 
            Clock.Now.Date >= c.FromMonth.Date && Clock.Now.Date <= c.EndMonth.Date);

            if (financialList != null && financialList.Count > 0)
            {
                financialYearId = financialList[0].Id;
            }

            claim.Identities.First().AddClaim(new Claim("Application_UserFinancial", financialYearId.ToString()));

            
          


            return claim;
        }

And i am getting this session value in one off service by code. In this code i fatch current value in sseion and set it current financial in model and fill drodown with selected accorrding to current financial Code

        public async Task<List<GetFinancialYearGlobalDto>> FillFinancialYearGlobal()
        {
            var ap = _principalAccessor.Principal.Claims;
            var apValue = ap.FirstOrDefault(c => c.Type == "Application_UserFinancial").Value;
            var financialYr = Convert.ToInt64(apValue);

            var financialList = _financialYearRepository.GetAll().
                Select(C => new GetFinancialYearGlobalDto
                {
                    FinancialYear = new FinancialYearDto
                    {
                        Id = C.Id,
                        EndMonth = C.EndMonth,
                        FromMonth = C.FromMonth,
                        YearName = C.YearName
                    },
                    CurrentFinancial = (C.Id == financialYr ? true : false)
                }
                ).ToList();

            return financialList;
        }

Now i want to update this claim value after change the option from dropdown and refresh the page. So i just tring this code. in this code claim value is updated but it again replaced by initail value from UserClaimsPrincipalFactory just after page refreshed. I do not get recently change value.

Code

    public async Task UpdateFinancialYearSession(long id)
        {
            AddUpdateClaim("Application_UserFinancial", id.ToString());
        }

            public void AddUpdateClaim(string key, string value)
        {
            

            var identity = _principalAccessor.Principal.Identity as ClaimsIdentity;
            if (identity == null)
                return;

            // check for existing claim and remove it
            var existingClaim = identity.FindFirst(key);
            if (existingClaim != null)
                identity.TryRemoveClaim(existingClaim);

            // add new claim
            identity.AddClaim(new Claim(key, value));                   

        }

Is any other alternate work plz share

Thanks


5 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    hi

    The changes to the AddUpdateClaim method will not work. You may consider storing this value in the cache. Refresh or remove the cache when necessary.

  • User Avatar
    0
    kansoftware created

    Thanks,

    So I dont need to add fucntion in UserClaimsPrincipalFactory ?? i need to save value as user login at where i can do this. and how to update it.

    Any code available for the reference ? Do you have complete code to achive this session work.

  • User Avatar
    0
    maliming created
    Support Team

    So I dont need to add fucntion in UserClaimsPrincipalFactory ??

    Yes

    You may consider storing this value in the cache. Refresh or remove the cache when necessary.

    https://aspnetboilerplate.com/Pages/Documents/Caching

  • User Avatar
    0
    kansoftware created

    At where i write the code?? At accountControler I need to set cache initailly just after user logged-In

  • User Avatar
    0
    kansoftware created

    Issue resolved, Thanks