我使用Katana for OAuth从他的LinkedIn个人资料中获取有关用户的数据。我希望将从LinkedIn收到的所有数据都收集到用户的ClaimsIdentity
对象中,以便将其发送到ASP.NET成员资格数据库中的AspNetUserClaims
表。
我并没有完全迷失。我订阅了LinkedInAuthenticationProvider的OnAuthenticated
事件,并将原始JSON反序列化为定制的业务对象。现在,我想从ApplicationUserManager
访问此对象,以便将其发送到数据库。那就是我被困住的地方。
var options = new LinkedInAuthenticationOptions();
options.ClientId = "...";
options.ClientSecret = "...";
options.Provider = new LinkedInAuthenticationProvider
{
OnAuthenticated = (context) =>
{
// I would like to get this bespoke object
// of type LinkedInBasicProfileResponse
// into the UserManager<TUser, ...>
var basicProfile =
context.User.ToObject<LinkedInBasicProfileResponse>();
return Task.FromResult<object>(null);
}
};
app.UseLinkedInAuthentication(options);
我想在这里看到基本的个人资料对象:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this,
DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
// I would like to add that data to these claims
var claims = userIdentity.Claims;
foreach(var claim in claims)
{
Debug.Print(string.Format($"{claim.Value}, {claim.ValueType}, {claim.Issuer}, {claim.OriginalIssuer}, {claim.Type}"));
foreach(var property in claim.Properties)
{
Debug.Print(string.Format($"{property.Key}, {property.Value}"));
}
}
return userIdentity;
}
}
当然,一种方法是将它放在HttpSessionState
字典中。但我希望有更优雅的方式来做到这一点。
答案 0 :(得分:1)
在您的代码中调用CreateIdentityAsync
后,您可以在AddClaim
上使用userIdentity
方法,如下所示:
userIdentity.AddClaim(new Claim("FavouriteDrink", "Beer"));
完整的代码将成为:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this,
DefaultAuthenticationTypes.ApplicationCookie);
// Add custom claim
userIdentity.AddClaim(new Claim("FavouriteDrink", "Beer"));
var claims = userIdentity.Claims;
foreach(var claim in claims)
{
Debug.Print(string.Format($"{claim.Value}, {claim.ValueType}, {claim.Issuer}, {claim.OriginalIssuer}, {claim.Type}"));
foreach(var property in claim.Properties)
{
Debug.Print(string.Format($"{property.Key}, {property.Value}"));
}
}
return userIdentity;
}
}