Web API 2 自定义默认Identity Table Name
One of the first issues you will likely encounter when getting started with ASP.NET Identity centers on customizing the underlying data model. The Entity Framework provider uses Code-First to generate the data model and, initially, it may seem as if it is imposing its model upon your application. Fortunately, since the implementation of the provider uses Code-First, we can make significant customizations to the model and still take advantage of the features that ASP.NET Identity and EF provide.
In part one of this series, we will customize the ASP.NET Identity data model by simply changing the default schema and renaming the tables. In part two of this series, we will add audit fields to some of the tables and change the primary key data types from GUIDs to integers.
To get started, let’s generate the default data model to see what we are working with:
- Start by creating a new ASP.NET MVC and/or Web API project. Be sure the Authentication Mode is set to “Individual User Accounts” so the project template pulls in the required references, as well as the scaffolding for the default security model.
- Update the default connection string (“DefaultConnection”) in the web.config to point to your SQL Server database.
- Build and run the application.
Next, navigate to the login page and attempt to sign in with any credentials. Your login attempt will fail because no accounts are registered, but the Entity Framework should have generated the default data model for users, roles, and claims. If you check the database, you will find something similar to the following:
That is all well and good and if you have worked with the Membership Provider for .NET, you should be reasonably comfortable with what you see. However, we are interested in customizing the model; so let’s get started by renaming the tables and moving them into our application schema.
Step 1: Create the object model
To get started, add the following classes to your project. These classes form the object model that will be mapped to the data model. If you are following along in the attached sample project, you will find these classes under the NAM_Sample_Pt1.Models namespace.
ApplicationUserRole.cs
public class ApplicationUserRole : IdentityUserRole { }
ApplicationRole.cs
public class ApplicationRole : IdentityRole<string, applicationuserrole=""> { }
ApplicationUserClaim.cs
public class ApplicationUserClaim : IdentityUserClaim { }
ApplicationUserLogin.cs
public class ApplicationUserLogin : IdentityUserLogin { }
IdentityModels.cs
Update the ApplicationUser class with the following:
public class ApplicationUser : IdentityUser<string, applicationuserlogin,="" applicationuserrole,="" applicationuserclaim="">
{
public async Task GenerateUserIdentityAsync(ApplicationUserManager manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
Step 2: Create the EF data context
Create a new security data context in IdentityModels.cs according to the following definition:
public class ApplicationDbContext : IdentityDbContext<applicationuser, applicationrole,="" string,="" applicationuserlogin,="" applicationuserrole,="" applicationuserclaim="">
{
public ApplicationDbContext() : base("DefaultConnection") { } public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Note that the data context inherits from IdentityDbContext, which is the generic base data context that is included in the EF Provider for Identity. IdentityDbContext includes several generic type parameters, which should be set to the various types defined in the object model we created in the previous step.
We will revisit the data context once we have finished configuring the objects required to customize the model; however, be aware that this is where we will implement the fluent mapping.
Step 3: Create a custom user store
In ASP.NET Identity 2.0 user stores are the repositories for user data. The Entity Framework implementation of the user store requires a data context. Here is the implementation of our custom user store:
public class ApplicationUserStore :
UserStore<applicationuser, applicationrole,="" string,="" applicationuserlogin,="" applicationuserrole,="" applicationuserclaim="">,
IUserStore,
IDisposable
{
public ApplicationUserStore(ApplicationDbContext context) : base(context) { }
}
Step 4: Modify ApplicationUserManager to use the new object model
There are several lines in the ApplicationUserManager (included in the default project template) that must be modified. First, in the static Create() method, modify the creation of the ApplicationUserManager so that it takes an ApplicationUserStore and ApplicationDbContext as arguments in its constructor, as such:
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get()));
Step 5: Create the fluent mapping
We are finally ready to map our objects to our new data model. Begin by overriding OnModelCreating() in ApplicationDbContext . We will use EF Fluent API to map each of the five objects in our security object model to new tables in a new schema. The full fluent API mapping is included below:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("NAM"); modelBuilder.Entity().Map(c =>
{
c.ToTable("UserLogin");
c.Properties(p => new
{
p.UserId,
p.LoginProvider,
p.ProviderKey
});
}).HasKey(p => new { p.LoginProvider, p.ProviderKey, p.UserId }); // Mapping for ApiRole
modelBuilder.Entity().Map(c =>
{
c.ToTable("Role");
c.Property(p => p.Id).HasColumnName("RoleId");
c.Properties(p => new
{
p.Name
});
}).HasKey(p => p.Id);
modelBuilder.Entity().HasMany(c => c.Users).WithRequired().HasForeignKey(c => c.RoleId);
modelBuilder.Entity().Map(c =>
{
c.ToTable("User");
c.Property(p => p.Id).HasColumnName("UserId");
c.Properties(p => new
{
p.AccessFailedCount,
p.Email,
p.EmailConfirmed,
p.PasswordHash,
p.PhoneNumber,
p.PhoneNumberConfirmed,
p.TwoFactorEnabled,
p.SecurityStamp,
p.LockoutEnabled,
p.LockoutEndDateUtc,
p.UserName
});
}).HasKey(c => c.Id);
modelBuilder.Entity().HasMany(c => c.Logins).WithOptional().HasForeignKey(c => c.UserId);
modelBuilder.Entity().HasMany(c => c.Claims).WithOptional().HasForeignKey(c => c.UserId);
modelBuilder.Entity().HasMany(c => c.Roles).WithRequired().HasForeignKey(c => c.UserId); modelBuilder.Entity().Map(c =>
{
c.ToTable("UserRole");
c.Properties(p => new
{
p.UserId,
p.RoleId
});
})
.HasKey(c => new { c.UserId, c.RoleId }); modelBuilder.Entity().Map(c =>
{
c.ToTable("UserClaim");
c.Property(p => p.Id).HasColumnName("UserClaimId");
c.Properties(p => new
{
p.UserId,
p.ClaimValue,
p.ClaimType
});
}).HasKey(c => c.Id);
}
You are now ready to build and run the project. As before, navigate to the login page and attempt to sign in, which will force the creation of the new data model. You should now see the model in the custom schema with the table names we declared in the fluent mapping.
In part two of this series we will add audit fields to some of the tables and change the primary key data types from GUIDs to integers.
Attachments
Web API 2 自定义默认Identity Table Name的更多相关文章
- Web API配置自定义路由
默认访问Web API时,是无需指定method名.它会按照默认的路由来访问.如果你的Web API中出现有方法重载时,也许得配置自定义路由: 标记1为自定义路由,标记2为默认路由,需要把自定义路由排 ...
- Web API 基于ASP.NET Identity的Basic Authentication
今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms ...
- 一张图说明 Web Api 参数绑定默认规则
请求如下: 控制器如下: 慎重说明:不管请求方式是 get 还是 post , 简单类型的参数,如 name 和 id ,其值都是从 url 里面去取. Web API 从 url 还是 body 获 ...
- [Asp.Net web api]基于自定义Filter的安全认证
摘要 对第三方开放的接口,处于安全的考虑需要对其进行安全认证,是否是合法的请求.目前在项目中也遇到这种情况,提供的接口因为涉及到客户铭感数据,所以在调用的时候,不能直接暴露,需要有一个认证的机制.所以 ...
- ASP.NET Core Web API 索引 (更新Identity Server 4 视频教程)
GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...
- YbSoftwareFactory 代码生成插件【十三】:Web API 的安全性
ASP.NET Web API 可非常方便地创建基于 HTTP 的 Services,这些服务可以非常方便地被几乎任何形式的平台和客户端(如浏览器.Windows客户端.Android设备.IOS等) ...
- ASP.NET MVC4中调用WEB API的四个方法
http://tech.it168.com/a2012/0606/1357/000001357231_all.shtml [IT168技术]当今的软件开发中,设计软件的服务并将其通过网络对外发布,让各 ...
- Web API 的安全性
Web API 的安全性 ASP.NET Web API 可非常方便地创建基于 HTTP 的 Services,这些服务可以非常方便地被几乎任何形式的平台和客户端(如浏览器.Windows客户端.An ...
- ASP.NET Web API 控制器创建过程(二)
ASP.NET Web API 控制器创建过程(二) 前言 本来这篇随笔应该是在上周就该写出来发布的,由于身体跟不上节奏感冒发烧有心无力,这种天气感冒发烧生不如死,也真正的体会到了什么叫病来如山倒,病 ...
随机推荐
- Unity热更新学习(二) —— ToLua c#与lua的相互调用
tolua 下载地址:http://www.ulua.org/index.html c#调用lua的方法,tolua的官方例子提供了很多种.我初步学了一种在做项目使用的方法.通过DoFile方法执行l ...
- [转]关于oracle sql语句查询时表名和字段名要加双引号的问题
oracle初学者一般会遇到这个问题. 用navicat可视化创建了表,可是就是不能查到! 后来发现②语句可以查询到 ①select * from user; 但是,我们如果给user加上双引 ...
- 【php增删改查实例】第二十二节 - 引入百度地图
20.用户新增地址字段 在实际的开发中,经常会出现对数据表新增或者修改字段的事情,所以,当用户提出加字段的需求时,我们的页面以及后台程序都要进行相应的改动. 本节就以增加一个地址字段为例. 打开nav ...
- Spring Cloud 入门教程(八): 断路器指标数据监控Hystrix Dashboard 和 Turbine
1. Hystrix Dashboard (断路器:hystrix 仪表盘) Hystrix一个很重要的功能是,可以通过HystrixCommand收集相关数据指标. Hystrix Dashboa ...
- 两行代码玩转Spring Data排序和分页
一:唠嗑 在实际项目中对Spring Data的各种使用相当多,简单的增删改查Spring Data提供了现成的方法,一些复杂的,我们可以在接口方法写And,Not等关键字来搞定,想写原生SQL,CQ ...
- 写了个限制文本框输入最大长度的jquery插件 - jquery.restrictFieldLength.js
做了个限制文本框最大输入长度的jquery插件,效果图(共2个文本框,限制最多10个字符): 功能:当超出设置的最大字符长度后,会截断字符串.更改当前元素的css(会在1秒后还原css).支持长度超出 ...
- itoa函数实现
1. 整数字符转化为字符串数 // 将整数转换成字符串数,不用函数itoa // 思路:采用加'0',然后在逆序的方法 #include <iostream> using nam ...
- H5 24-CSS三大特性之继承性
24-CSS三大特性之继承性 我是段落 我是段落 我是超链接 我是大标题 <!DOCTYPE html> <html lang="en"> <head ...
- hibernate中实体与数据库中属性对应的类型
常用的字段及类型,在数据库中字段名称若与实体对应的属性字段名称相同,hibernate可以自动映射,在一些情况下hibernate可能报错这时候有的错误可以通过指定对应的类型避免.下面给出一些常用的 ...
- 数学基础IV 欧拉函数 Miller Rabin Pollard's rho 欧拉定理 行列式
找了一些曾经没提到的算法.这应该是数学基础系最后一篇. 曾经的文章: 数学基础I 莫比乌斯反演I 莫比乌斯反演II 数学基础II 生成函数 数学基础III 博弈论 容斥原理(hidden) 线性基(h ...