dotnet / dotnet/AspNetCore.Docs

Sample Code Seems to Incorrectly Add New Identities

Open
#31,434 2 comments 0 reactions 1 assignee Claimed by @halter73 View on GitHub
re-Artak Source - Docs.ms
Dominant language
C#
Stars
13.1k
Forks
24.6k
Avg merge
1d 3h
Merged PRs (30d)
97

Description

### Description

I'm working on writing a custom transform and I'm using these docs as an example. While the code for adding a new claim works I believe it erroneously is adding a new `ClaimsIdentity` every time it is called whether it needs to or not. Given that `TransformAsync` can be called multiple times then each time this sample code is called it creates a new `ClaimsIdentity` and adds it to the principal. While it correctly doesn't add the new claim each time it still is creating an "empty" identity each time. So if the method is called 5 times in a single request then it will create 5 new `ClaimsIdentity` objects to associate with the principal but only the first one will have an actual claim associated with it.

The problems I see with this:
- The `Identities` collection of the principal is increased each time it is called which means the underlying list(?) might have to increase in size.
- The `Identities` property will consist of new identities that are empty.
- Each call allocates a ref type that shouldn't be needed.

### Page URL

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-6.0#extend-or-add-custom-claims-using-iclaimstransformation

### Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/security/authentication/claims.md

### Document ID

b01e1351-d362-fd61-4dcb-bacb21559f76

### Article author

@damienbod

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.