mortware
mortware

Reputation: 1940

Creating ready-made users with claims with ASP.NET

The application I'm working on is an MVC 5 web application, using ASP.NET Identity.

We're trying to allow certain users to create other users (i.e. pre-register them). On creation, we'd like to pass in some meta-data, that we want stored as claims against that user such as email address, age etc.

The example I've seen where claims are created, call a SignIn method to persist the claims in the database. We obviously don't want these accounts to sign in, just save the claims.

var user = new ApplicationUser { UserName = "[email protected]" };
var pwd = "password123"
var result = await _identityService.CreateAsync(user, pwd);

if (!result.Succeeded)
   return null;

var identity = await _identityService.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.Email, "[email protected]"));
// PERSIST THIS CLAIM

Of course I could be very confused about the way claims work, but this seems like quite a common scenario to me. Appreciate any help or feedback.

Upvotes: 1

Views: 466

Answers (1)

MisterJoe
MisterJoe

Reputation: 61

Claims are pretty confusing when you first approach them. First, you'll want some resources about what Claims and Identity really are:

https://msdn.microsoft.com/en-us/library/ff359101.aspx does a decent job of explaining it.

Explain "claims-based authentication" to a 5-year-old was asked a few years ago and goes well with the MSDN link.

Distilled, Claims are basically attributes. The username is a Claim. The email address is a Claim. Each role the user has is a Claim. Combined they make up the Identity. Claims are meant to be used by the application's authorization system but how they are persisted/stored is completely arbitrary.

What you actually want to do here is store the email address, age, etc. in the database like you would any other user data. How you do that is up to you. The only time that information would become a "claim" would be if you wanted that information to be available as part of the logged in user's Identity, at which point you'd pull the information (like email address) from the database and add it to the user's Claims (which is probably a separate question/discussion).

Upvotes: 1

Related Questions