nemo_87
nemo_87

Reputation: 4781

Put custom claims into security token and create it in ASP.NET Web API

Is it possible to take some custom Claims, for example like this:

Find a user with given PIN number and Device_Id, grab values for that user and put them into claims.

CredentialsDb dbctx = new CredentialsDb();
var usr = dbctx.Credentials.Where(u => u.PIN == model.PIN && u.Device_Id == model.Device_Id).SingleOrDefault();

var identity = new ClaimsIdentity();
identity.AddClaim(new Claim("UserName", usr.UserName));
identity.AddClaim(new Claim("Device_Id", usr.Device_Id));
identity.AddClaim(new Claim("Device_Name", usr.Device_Name));
identity.AddClaim(new Claim("PIN", usr.PIN.ToString()));

And create a security token out of them? How this token can be build, if we are not using some STS and how can client consume it later? Anyone has some idea or good tutorial for sharing?

Upvotes: 0

Views: 1228

Answers (1)

Behrooz
Behrooz

Reputation: 1955

This is how I am doing it in my web api application, where I want to fetch all the roles for the user from the database and add them one by one to my Identity's claims:

Fetching the user:

IdentityUser user = new ApplicationDbContext().Users.Where([your conditions here...]).FirstOrDefault();

Creating the Identity:

var id = new ClaimsIdentity(context.Options.AuthenticationType);

And using a loop to add the roles to the claims of that identity:

foreach (IdentityUserRole R in user.Roles)
            {
                id.AddClaim(new Claim(ClaimTypes.Role, RolesProvider.RoleNameById(R.RoleId)));
            }

Of course you can use a similar logic to add any kind of information you have obtained about that specific user. Does that answer you question?

Upvotes: 1

Related Questions