dotnet / dotnet/aspnetcore

`UserManager.AddClaimAsync` keeps throwing duplicate PK exception for new claims

Open
#48,556 17 comments 0 reactions 0 assignees View on GitHub
area-identity investigate
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

The following code snippet:
```
Claim claim = claims.FirstOrDefault(c => c.Type == "roles");
if (claim != null)
await _userManager.RemoveClaimAsync(appUser, claim);
StringBuilder sb = new StringBuilder();
if (claim != null && !string.IsNullOrEmpty(claim.Value) && !claim.Value.Contains("buyer"))
sb.Append($"{claim.Value} buyer");
else
sb.Append("buyer");
try {
await _userManager.AddClaimAsync(appUser, new Claim("roles", sb.ToString()));
} catch (Exception e) {
_logger.LogError($"{nameof(CreateOrUpdateUser)} Exception! {e}");
}
```
keeps throwing the exception. I have checked the DB this user does NOT have `roles` claim at all

### Expected Behavior

Successfully added new claim to the user.

### Steps To Reproduce

_No response_

### Exceptions (if any)

```
"23505: duplicate key value violates unique constraint \"PK_AspNetUserClaims\"\n\nDETAIL: Key (\"Id\")=(6532) already exists."
```

### .NET Version

7.0.105

### Anything else?

```
.NET SDK:
Version: 7.0.105
Commit: e1bc5e001c

Runtime Environment:
OS Name: ubuntu
OS Version: 23.04
OS Platform: Linux
RID: ubuntu.23.04-x64
Base Path: /usr/lib/dotnet/sdk/7.0.105/

Host:
Version: 7.0.5
Architecture: x64
Commit: 8042d61b17

.NET SDKs installed:
7.0.105 [/usr/lib/dotnet/sdk]

.NET runtimes installed:
Microsoft.AspNetCore.App 7.0.5 [/usr/lib/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 7.0.5 [/usr/lib/dotnet/shared/Microsoft.NETCore.App]

Other architectures found:
None

Environment variables:
DOTNET_ROOT [/usr/lib/dotnet]

global.json file:
Not found

Learn more:
https://aka.ms/dotnet/info

Download .NET:
https://aka.ms/dotnet/download
```

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the UserManager.AddClaimAsync call and the reported PK_AspNetUserClaims exception, then investigate how the claim is persisted for PostgreSQL. Reproduce the failure if possible and verify that adding a new claim no longer raises a duplicate primary-key error.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, postgresql
Domain
authorization
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.