Tro*_*ggy 6 oauth asp.net-web-api owin asp.net-identity
我正在使用Visual Studio 2013构建web api,并希望使用OWIN中间件和持有者令牌进行身份验证.但是我已经有了一个数据库,并且不想使用Microsoft的新Identity框架作为它自动生成的大多数表和列,我根本不需要.
任何人都可以指出我如何应用此类身份验证的正确方向,而无需使用Microsoft身份框架?
我的建议是使用该框架,但将其扩展以使用您的对象和基础设施。我目前正在做这件事并提出了这个问题。到目前为止,我是这样解决的:
第 1 步:您自己的 CustomUserObject
编写/使用您自己的“ApplicationUser”对象。在模板项目中,您想要修改“IdentityModels”文件。它在那里定义了 ApplicationUser 对象。假设您已经拥有现有应用程序的所有属性,则需要添加GenerateUserIdentityAsync()方法,但将参数类型更改为UserManager管理器。更改后,您的方法签名如下所示:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<CustomUserObject> manager)
Run Code Online (Sandbox Code Playgroud)
第 2 步:定义您自己的 IUserStore<> 实现
添加一个实现 IUserStore 的新类 CustomUserStore,如下所示:
public class CustomUserStore : IUserStore<CustomUserObject>
{
private readonly IUserManagerService _userManagerService;
public CustomUserStore(IUserManagerService userManagerService)
{
_userManagerService = userManagerService
}
//implementation code for all of the IUserStore methods here using
//userManagerService or your existing services/classes
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 Unity 注入上面的 IUserManagementService 实现。
我使用了 Microsoft Identity 框架附带的综合 UserManager 类,但扩展了该框架以使用我的 API 进行身份验证和授权。您可以编写自己的 UserManager,但我发现它非常乏味,并且 UserManager 没有理由可以适用于保护应用程序的大多数情况。
步骤 3:IdentityConfig.cs 文件中的更改
更改类定义以使ApplicationUserManager类继承自UserManager
您还需要在此类的构造函数中执行相同的操作;即有IUserStore。修改 Create 静态方法的第一行以使用新存储和包装类,该包装类提供了成为“DbContext”的方法,如下所示:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<UserManagementServiceWrapper>()));
//modify the relevant lines after this to suit your needs
...
}
Run Code Online (Sandbox Code Playgroud)
我的 UserManagementServiceWrapper 看起来像这样(请注意,我不太高兴它继承自一个具体的 UserManagementService 类,该类提供连接到提供用户数据的服务的方法,我仍在构建它):
public class UserManagementServiceWrapper : UserManagementService, IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
步骤 4:更改 ApplicationDbContext 类以返回 UserManagementServiceWrapper 实例
public class ApplicationDbContext : UserManagementServiceWrapper
{
public static UserManagementServiceWrapper Create()
{
return new UserManagementServiceWrapper();
}
}
Run Code Online (Sandbox Code Playgroud)
差不多就是这样了。您仍然需要编写 CustomUserStore 对象的实现,但一切都应该有效。
请注意,这不是样板代码,也没有接近“代码审查就绪”,正如我所说,我仍在深入研究并构建它以使用自定义存储、数据访问对象、服务等。我想您会对一些我花了几个小时才弄清楚的事情有一个良好的开端。当我有一个好的解决方案时,我会在博客上讨论这个问题。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
3343 次 |
| 最近记录: |