Dynamic claims are not working
Dynamic claims doesn't seem to be working for me or I don't how to use it properly. According to the documentation everything should just work. Here are the steps that I did:
- Generate a new app with
abp new Acme.BookStore -u angular --separate-auth-server --theme basic -csf. ABP Version: 8.1.4 - Add a new class to the Domain project.
public class TestDynamicClaimPrincipalContributor : AbpDynamicClaimsPrincipalContributorBase, ITransientDependency
{
public override async Task ContributeAsync(AbpClaimsPrincipalContributorContext context)
{
var identity = context.ClaimsPrincipal.Identities.FirstOrDefault();
var userId = identity?.FindUserId();
if (userId == null) return;
var random = new Random();
await AddDynamicClaimsAsync(context, identity!, [new AbpDynamicClaim("testclaim", random.Next(1, 999).ToString())]);
}
}
- Run dbmigrator, authserver and host
- Run the angular app with yarn start
- Log-in to the angular app
- Inpect the local storage, grab the access_token an check on jwt.io
- testclaim has a random number
- Refresh the page
- Inpect the local storage, grab the access_token an check on jwt.io
At this point, as I understand, testclaim should have a different number because the page refreshed but it doesn't seem to be the case. I can see the code running with a debugger but it's never updated on the angular app it seems. If I log-out and log back in I get a different number on the access_token.
Am I doing something wrong? Did I completely misunderstood how this should work?
JWT is immutable, ABP will dynamically refresh the claims in the backend https://docs.abp.io/en/abp/latest/Dynamic-Claims#dynamic-claims
@realLiangshiwei Ahh I see. Is there any ABP way of doing this or anything you would recommend? I guess if roles change for example, it wouldn't change for the user until a re-login occurs?
EDIT: Reading the documentation it says:
When a client authenticates and obtains an access token or an authentication cookie, the claims in that token or cookie are not changed unless it re-authenticates. For most of the claims, that may not be a problem since claims are not frequently changing values. However, some claims may be changed and these changes should be reflected to the current session immediately. For example, we can revoke a role from a user and that should be immediately effective, otherwise user will continue to use that role's permissions until re-login to the application
Isn't this the same scenario I'm describing? I mean my goal is to not have to wait until a re-login occurs so role's permissions and others are updated. It should be immediately as the doc says.
In my example, pretty much I want to that random number to be reflected immediatly in the user session as the doc says
I kept trying to get this to work and I understand it now. When I know the data is changing, because of a user action, I can just call authService.refreshToken() which refreshes the stale data on the token.