Search code examples
asp.netentity-frameworkasp.net-coreasp.net-identityidentity

identity logical concepts and misconcepts


i find this rather awkward to say but i can't really wrap my head around the way identity works, i can do pretty much anything i need programmatically but it's just not coming together

so for instance and in a nutshell, if i want to mark someone as admin, should i create a claim called "IsAdmin"

or a role called "Admin" ?

or should i create my own identityuser and include that property

or even override the ClaimsPrincipalFactory to include it as claim (the property in the third choice)

so i pretty much can do it with those 4 ways but i don't understand when to do what and which fits better or how was it intended to work


Solution

  • If you need to mark someone as admin it means you need to persist that state. The easiest way to save user's admin state is to add a "role" claim "admin" to users claim collection in the database(by using SQL query/simple console app/or an admin interface). But this is not the only way you can keep user's admin state. You can imagine whatever persisting mechanism that makes sense for your application and use your 4th option to create the identity.

    Then it comes to determining if the user is an admin at runtime. When the user is signed in he usually gets the users persisted claims collection attached to the user's identity. If you have added role claim, you can read that claim to check if the logged in user is an admin. If you rely on other mechanisms determining if the user is an admin, you should query those resources to check if the user is admin and add the relevant claim to users claims collection at runtime(usually done when the user signed in). When the user's claims are finalized by adding default and constructed custom claims a session is created with a cookie containing all the runtime claims. Then the web app will not be required to query users persisted state as it can now construct the runtime claim collection by using the cookie in subsequent requests.

    1. should I create a claim called "IsAdmin"? Yes if it makes your authorization code simpler. But this claim should not be persisted. It should be constructed when the user logging in based on other persisted properties/claims of the user.

    2. a role called "Admin"? Yes, this is the most common way of marking users as admin. The role can be persisted to the database and read at runtime using asp.net identity.

    3. should I create my own identityuser and include that property, No, you should not modify identity user to include frequently changing properties like this.

    4. even override the ClaimsPrincipalFactory to include it as claim (the property in the third choice) If you need to access additional resources before creating the user's identity this route can be taken. e.g you have saved your user's admin state in your own mapping table.