在使用IdentityServer3时,可以使用Asp.Net Identity 2来管理用户信息。要将用户信息映射到IdentityServer3配置文件声明,可以按照以下步骤进行操作:
创建一个用于映射用户信息的类,例如ApplicationUserClaims
。该类应该继承自IdentityUserClaim
。
using Microsoft.AspNet.Identity.EntityFramework;
namespace YourNamespace
{
public class ApplicationUserClaims : IdentityUserClaim
{
}
}
在IdentityModels.cs
中,将ApplicationUserClaims
作为用户声明的类型。
using Microsoft.AspNet.Identity.EntityFramework;
namespace YourNamespace
{
public class ApplicationUser : IdentityUser
{
public virtual ICollection Claims { get; set; }
}
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
}
在IdentityServer3的配置文件中,将ApplicationUserClaims
映射到声明。
using IdentityServer3.Core.Models;
using System.Collections.Generic;
namespace YourNamespace
{
public static class IdentityServerConfig
{
public static IEnumerable GetScopes()
{
return new List
{
// 其他scope配置...
new Scope
{
Name = "profile",
DisplayName = "User profile",
Type = ScopeType.Identity,
Claims = new List
{
new ScopeClaim("name"),
new ScopeClaim("email"),
new ScopeClaim("ApplicationUserClaims")
}
}
};
}
}
}
在IdentityServer3的Startup类中,使用ApplicationUserClaims
映射用户信息。
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Owin;
using System.Collections.Generic;
using YourNamespace;
[assembly: OwinStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(IdentityServerConfig.GetScopes())
.UseInMemoryUsers(Users.Get());
// 其他配置...
var userService = new UserService();
factory.UserService = new Registration(resolver => userService);
var options = new IdentityServerOptions
{
Factory = factory,
// 其他配置...
};
app.UseIdentityServer(options);
}
public class UserService : UserServiceBase
{
public override System.Threading.Tasks.Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
// 获取用户信息...
var user = // 获取用户信息的逻辑
if (user != null)
{
// 设置用户信息
context.AuthenticateResult = new AuthenticateResult(user.Id.ToString(), user.Username,
GetUserClaims(user));
}
return System.Threading.Tasks.Task.FromResult(0);
}
private static IEnumerable GetUserClaims(ApplicationUser user)
{
var claims = new List
{
new System.Security.Claims.Claim("name", user.Name),
new System.Security.Claims.Claim("email", user.Email),
};
// 添加用户的ApplicationUserClaims
foreach (var claim in user.Claims)
{
claims.Add(new System.Security.Claims.Claim(claim.ClaimType, claim.ClaimValue));
}
return claims;
}
}
}
}
通过以上步骤,用户的信息将被映射到IdentityServer3配置文件声明中,并可以在授权过程中使用。