[英]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: 是否可以采用一些自定义的Claims,例如:
Find a user with given PIN number and Device_Id, grab values for that user and put them into claims. 查找具有给定PIN码和Device_Id的用户,获取该用户的值并将其放入声明中。
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?
如果我们不使用某些STS,那么如何构建此令牌?客户端以后如何使用它? Anyone has some idea or good tutorial for sharing?
任何人都有一些想法或好的教程可以分享吗?
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: 这就是我在Web api应用程序中所做的工作,在该应用程序中,我想从数据库中获取用户的所有角色,并将这些角色一个接一个地添加到我的Identity声明中:
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?
这是否回答了您的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.