asp.net identity
来源:互联网 发布:战舰世界2017岛风数据 编辑:程序博客网 时间:2024/05/17 09:07
想要给自己创建的程序,添加用户和权限,今天开始看下asp.net identity
参考资料:http://asp.net/identity
asp.net的用户系统,从2005年开始主要有4个,asp.net membership,asp.net simple membership,asp.net universal provider和asp.net identity
目前的asp.net identity是2.0 ,和1.0相比改动较大。
可以在项目属性里开启ssl登录,并配置项目只允许ssl访问,在controller中配置需要ssl访问,可以通过如下方式
[RequireHttps]
publicclassHomeController:Controller{
publicActionResultIndex(){
returnView();
}
}
或者在filterConfig.cs中配置全局启用https
Add the Authorize filter and the RequireHttps filter to the application. An alternative approach is to add theAuthorize attribute and theRequireHttps attribute to each controller, but it's considered a security best practice to apply them to the entire application. By adding them globally, every new controller and action method you add will automatically be protected, you won't need to remember to apply them. For more information see Securing your ASP.NET MVC App and the new AllowAnonymous Attribute. Open the App_Start\FilterConfig.cs file and replace the RegisterGlobalFilters method with the following (which adds the two filters):
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new System.Web.Mvc.AuthorizeAttribute()); filters.Add(new RequireHttpsAttribute()); }
看到的大部分文字都是配置社交账号的,基本的application 账号,反而提到很少。
默认情况下,在identityModels.cs中可以配置数据库连接,dbcontext。
在AccountViewModels.cs中配置可以配置注册、登录时需要提供那些信息。
这些字段名,不知道是不是可以自己随便取得。
1.默认创建的程序,注册可以,登录出现以下错误
@Html.ActionLink("注册", "Register")(如果你没有本地帐户)。
默认产生的代码有bug,把(如果你没有本地帐户)。 注释掉就可以了
因为不准备采用其他方式登录,login.cshtml中的这部分代码可以删除
<div class="col-md-4">
<section id="socialLoginForm">
@Html.Partial("_ExternalLoginsListPartial", new { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
</section>
</div>
经过上面的设置,所有的网页都必须要登录才能访问了。把首页改成支持匿名访问。
在你想支持匿名的方法前加[AllowAnonymous]即可。account模块已经自动加上了。
下面,添加用户 角色,系统有admin,instructor,student 3种角色。
直接打开aspnetroles表添加即可3种角色即可。
也可以在seed中写。问题出来了,configure.cs中的seed方法
protected override void Seed(tenhours.DAL.cmsContext context){},context中只有自己定义的类,没有identity默认设置的类。
运行Enable-Migrations ,会提示发现多个上下文,好像一次只能配置一个上下文的迁移。
Enable-Migrations -ContextTypeName tenhours.Models.ApplicationDbContext -EnableAutomaticMigrations
对上下文tenhours.models.applicationdbcontext启用自动迁移数据库。
发现identity中id不是自动加1 的int类型,而是用guid,这个方法好。
密码是hash码,asp.net中hash码
identity中的规则比自己的models要复杂很多。
identity中的seed方法可以这样写
var userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(
new ApplicationDbContext()));
var roleManager = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(
new ApplicationDbContext()));
string roleAdmin = "Admin";
string roleInstructor = "Instructor";
string roleStudent = "Student";
if (!roleManager.RoleExists(roleAdmin))
{
var roleresult = roleManager.Create(new IdentityRole(roleAdmin));
}
if (!roleManager.RoleExists(roleInstructor))
{
var roleresult = roleManager.Create(new IdentityRole(roleInstructor));
}
if (!roleManager.RoleExists(roleStudent))
{
var roleresult = roleManager.Create(new IdentityRole(roleStudent));
}
var user = new ApplicationUser();
user.UserName = "admin";
var userresult= userManager.Create(user, "123456");
if(userresult.Succeeded){
var result = userManager.AddToRole(user.Id, roleAdmin);
}
为了防止代码被自动覆盖,可以把上面的代码放在一个common类中 写成一个静态方法initUser,然后再seed中直接调用即可。
自动产生的代码中尽量不要放自己写的代码,被覆盖掉就碉堡了。。
下面,来限制某些页面只能由admin和instructor打开。
只要指定在controller中的对应方法前加[Authorize(roles=“admin,instructor”)]即可。
在看identity的代码时,发现很多地方都使用了await async,简单的说,用async把一个方法标记为异步方法。异步方法的返回结果是task<>类型的。
如果程序接下去的处理要用到异步方法返回的结果,则用await someasyncresult,来等待。
也就是说程序调用了async方法后不会等待,一直到遇到await 。
所以可以用async方法异步调用10个网页,之后等待调用完成。非常美妙,把需要并发的任务,通过async 和await 关键字就简单的完成了。
下面是微软演示程序,配合注释,很容易懂。
- public partial class MainWindow : Window
- {
- // Mark the event handler with async so you can use await in it.
- private async void StartButton_Click(object sender, RoutedEventArgs e)
- {
- // Call and await separately.
- //Task<int> getLengthTask = AccessTheWebAsync();
- //// You can do independent work here.
- //int contentLength = await getLengthTask;
- int contentLength = await AccessTheWebAsync();
- resultsTextBox.Text +=
- String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
- }
- // Three things to note in the signature:
- // - The method has an async modifier.
- // - The return type is Task or Task<T>. (See "Return Types" section.)
- // Here, it is Task<int> because the return statement returns an integer.
- // - The method name ends in "Async."
- async Task<int> AccessTheWebAsync()
- {
- // You need to add a reference to System.Net.Http to declare client.
- HttpClient client = new HttpClient();
- // GetStringAsync returns a Task<string>. That means that when you await the
- // task you'll get a string (urlContents).
- Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
- // You can do work here that doesn't rely on the string from GetStringAsync.
- DoIndependentWork();
- // The await operator suspends AccessTheWebAsync.
- // - AccessTheWebAsync can't continue until getStringTask is complete.
- // - Meanwhile, control returns to the caller of AccessTheWebAsync.
- // - Control resumes here when getStringTask is complete.
- // - The await operator then retrieves the string result from getStringTask.
- string urlContents = await getStringTask;
- // The return statement specifies an integer result.
- // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
- return urlContents.Length;
- }
- void DoIndependentWork()
- {
- resultsTextBox.Text += "Working . . . . . . .\r\n";
- }
- }
- asp.net identity
- ASP.NET Identity
- ASP.NET Identity Authentication
- [ASP.NET Identity 2.0]
- ASP.NET Identity简介
- ASP.NET Identity
- ASP.NET Identity
- ASP.NET Identity 使用简介
- ASP.NET WebForm Identity使用
- Asp.Net Core-Identity 配置
- Asp.Net Core-Identity迁移
- asp.net Context.User.Identity.Name说明
- asp.net Context.User.Identity.Name说明
- ASP.NET Identity with the Entity Framework
- Asp.Net 5 Identity 快速集成
- Announcing RTM of ASP.NET Identity 2.0.0
- 从Membership 到 .NET4.5 之 ASP.NET Identity
- 在ASP.NET Core Identity外面使用Cookie中间件
- no-ip类似花生壳的动态IP
- c和c++的输入输出
- ios - UITableViewController 笔记
- AOSP Privileged vs System app
- Swap Nodes in Pairs
- asp.net identity
- HDU1506 Largest Rectangle in a Histogram (动规)
- HTML字符实体
- 多线程队列的算法优化 转载Parallel Labs
- 软件开发部门经理岗位职责
- (HDU 2680、HDU 1599、hdu2066,POJ 1125)n元最短路问题
- Discuz-x3使用手册--目录结构
- 设计模式---模版方法模式
- CMD命令大全