abp icon indicating copy to clipboard operation
abp copied to clipboard

Dynamic claims not working after updating to 9.0.2

Open gvassao opened this issue 1 year ago • 9 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Description

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;

        await AddDynamicClaimsAsync(context, identity!, [new AbpDynamicClaim("testclaim", "1")]);
    }
}

The code above adds "testclaim" to the JWT after the user logs in which I can verify by copying the access token and using it on jtw.io

It works on my project which is ABP 8.0.2 + angular UI + separate auth server It also works on a brand new ABP 9.0.2 + angular UI (no separate auth server anymore)

However it doesn't work on my solution after I've updated it from 8.0.2 to 9.0.2. If I set a breakpoint I can see the code running but when I get the access token back it doesn't have the "testclaim" when I use it on jtw.io

Any ideas what has changed?

Reproduction Steps

Upgrade from ABP 8.0.2 +angular UI + separate auth server to ABP 9.0.2 (my app is using password authentication flow) Log-in to the angular app Inpect the local storage, grab the access_token an check on jwt.io

Expected behavior

testclaim is present

Actual behavior

testclaim is not present

Regression?

No response

Known Workarounds

No response

Version

8.0.2 to 9.0.2

User Interface

Angular

Database Provider

EF Core (Default)

Tiered or separate authentication server

Separate Auth Server

Operation System

Windows (Default)

Other information

No response

gvassao avatar Dec 20 '24 22:12 gvassao

Digging through the source code I think I found a solution.

I use password authentication with custom logic for my app thus I'm overrding the Token Controller

[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(TokenController))]
public class AppTokenController : TokenController
....

One of the methods I'm overriding is HandlePasswordAsync. At the end of this method SetSuccessResultAsync is called which I'm not overriding.

I noticed that SetSucessResultAsync calls SignInManager.CreateUserPrincipalAsync(user);.

Looking at HandleAuthorizationCodeAsync, which is used by the default template, it has this piece while the SetSucessResultAsync has not.

if (AbpClaimsPrincipalFactoryOptions.Value.IsDynamicClaimsEnabled)
{
    principal = await AbpClaimsPrincipalFactory.CreateDynamicAsync(principal);
    if (principal == null)
    {
        return Forbid(
            authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
            properties: new AuthenticationProperties(new Dictionary<string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.InvalidGrant,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The token is no longer valid."
            }));
    }
}

Copying the above to the SetSucessResultAsync after it creates the principal using the SignInManager made it work again. I don't understand how it is working on my current project which uses 8.0.2 and doesn't have that line. I guess something internally changed since the separate auth server is behind a paid license now?

I'd appreciate if someone tells me if this is the right solution.

Thanks.

gvassao avatar Dec 20 '24 23:12 gvassao

hi @gvassao

The right solution is to copy the latest code of Controllers to your project to override.

Thanks.

maliming avatar Dec 21 '24 01:12 maliming

Hey @maliming, Thanks for looking into this.

Just to be sure, you're guys are going to patch it right? You can reproduce this with the newest template as well:

  1. Create a new app by using abp new TestClaims -u angular.
  2. Change angular authentication to use password flow by removing responseType: 'code', from the environment.ts.
  3. Add the class TestDynamicClaimPrincipalContributor I mentioned on my original post.
  4. Log-in.
  5. Grab the access token and inspect on jwt.io.

Result: testclaim will not be there.

  1. Revert the angular change so now it'll use code flow.
  2. Log-in again.
  3. Grab the access token and inpect on jwt.io.

Result: testclaim will be there.

gvassao avatar Dec 21 '24 02:12 gvassao

hi

You can reproduce this with the newest template as well:

Can you share this test project? [email protected]

I saw you said: It also works on a brand new ABP 9.0.2 + angular UI (no separate auth server anymore)

maliming avatar Dec 21 '24 02:12 maliming

Oh sorry for the confusion. It does work with the newest template when you use the code flow, which comes by default. But if you switch to password flow then it doesn't. I just sent you a project you can run and inspect the access_token after login.

After the initial test you can switch to code flow again and see that the claim will be there

gvassao avatar Dec 21 '24 02:12 gvassao

hi

I see, : )

ABP's dynamic claims feature dynamically overrides the configured claim values in the client's authentication token/cookie with the latest values of these claims.

When you use AuthorizationCode, we can obtain the current principal. Therefore, we will attempt to override it by dynamic claims. However, when using password, we have no current principal, we completely create a new one so there is no need to override it. If you'd like to add a claim, you can use IAbpClaimsPrincipalContributor.

https://github.com/abpframework/abp/blob/dev/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.AuthorizationCode.cs#L19

https://github.com/abpframework/abp/blob/dev/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs#L372

maliming avatar Dec 21 '24 02:12 maliming

But that's exactly what TestDynamicClaimPrincipalContributor is doing right? It inherits from AbpDynamicClaimsPrincipalContributorBase which implements IAbpClaimsPrincipalContributor.

This was working before 9.0

gvassao avatar Dec 21 '24 02:12 gvassao

hi

AbpDynamicClaimsPrincipalContributorBase implements IAbpDynamicClaimsPrincipalContributor.

- IAbpClaimsPrincipalContributor
+ IAbpDynamicClaimsPrincipalContributor

The new version has some changes, The previous approach may have issues in certain cases.

You can use IAbpClaimsPrincipalContributor.

Thanks.

maliming avatar Dec 21 '24 03:12 maliming

Interesting... using IAbpClaimsPrincipalContributor worked! However the value would never get updated server side if the database changed because it was not inheriting AbpDynamicClaimsPrincipalContributorBase anymore.

The final solution was just to add IAbpClaimsPrincipalContributor to the initial class I provided in this example and then I was able to remove the code I copied from HandleAuthorizationCodeAsync:

public class TestDynamicClaimPrincipalContributor : AbpDynamicClaimsPrincipalContributorBase, IAbpClaimsPrincipalContributor, ITransientDependency
{
    public override async Task ContributeAsync(AbpClaimsPrincipalContributorContext context)
    {
        var identity = context.ClaimsPrincipal.Identities.FirstOrDefault();
        var userId = identity?.FindUserId();

        if (userId == null) return;

        await AddDynamicClaimsAsync(context, identity!, [new AbpDynamicClaim("testclaim", "1")]);
    }
}

Still weird that changing the type of authentication changes what gets put into the access_token based on wether IAbpClaimsPrincipalContributor is implemented or not.

Thanks for help!

gvassao avatar Dec 21 '24 04:12 gvassao