Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maintain claims principal during refresh #14918

Merged
merged 3 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/OrchardCore.Modules/OrchardCore.Users/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public override void ConfigureServices(IServiceCollection services)
options.LogoutPath = "/" + userOptions.Value.LogoffPath;
options.AccessDeniedPath = "/Error/403";
});

services.AddTransient<IPostConfigureOptions<SecurityStampValidatorOptions>, ConfigureSecurityStampOptions>();
services.AddDataMigration<Migrations>();

services.AddScoped<IUserClaimsProvider, EmailClaimsProvider>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;

namespace OrchardCore.Users.Services;

public class ConfigureSecurityStampOptions : IPostConfigureOptions<SecurityStampValidatorOptions>
{
public void PostConfigure(string name, SecurityStampValidatorOptions options)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should add a comment explaining the reason for this handler.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. I'll add comments in the next day or so.

{
options.OnRefreshingPrincipal = principalContext =>
{
var currentIdentity = principalContext.CurrentPrincipal?.Identities?.FirstOrDefault();
if (currentIdentity is not null && principalContext.NewPrincipal.Identities is not null)
{
var newIdentity = principalContext.NewPrincipal.Identities.First();
foreach (var claim in currentIdentity.Claims)
{
if (newIdentity.HasClaim(claim.Type, claim.Value))
{
continue;
}
newIdentity.AddClaim(new Claim(claim.Type, claim.Value));
}
}
return Task.CompletedTask;
};
}
}