CQRS学习——集成ASP.NET Identity[其五]
【其实和Cqrs没啥关系】
缘由
其实没啥原因,只是觉得以前写了不知多少遍的用户登录复用性太差,实现的功能也不多。
依赖的Nuget包
简单登陆
就简单登陆而言,只需要实现如下接口/抽象类:
Store相关:
IUserLockoutStore<DpfbUser,Guid> , IUserPasswordStore<DpfbUser,Guid>, IUserTwoFactorStore<DpfbUser,Guid>, IUserEmailStore<DpfbUser,Guid>
Manager相关:
UserManager<DpfbUser, Guid>, SignInManager<DpfbUser, Guid>
打包的代码:
public class AppSignInManager : SignInManager<DpfbUser, Guid>
{
public AppSignInManager()
: base(WebContextHelper.CurrentOwinContext.Get<AppUserManager>(),
WebContextHelper.CurrentOwinContext.Authentication)
{ } public override async Task<ClaimsIdentity> CreateUserIdentityAsync(DpfbUser user)
{
var userIdentity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
} public class AppUserManager : UserManager<DpfbUser, Guid>
{
public AppUserManager(DpfbUserStore store)
: base(store)
{ } public AppUserManager()
: this(WebContextHelper.CurrentOwinContext.Get<DpfbUserStore>())
{ }
} public class DpfbUserStore :
//IUserStore<DpfbUser, Guid>,
IUserLockoutStore<DpfbUser, Guid>,
IUserPasswordStore<DpfbUser,Guid>,
IUserTwoFactorStore<DpfbUser,Guid>,
IUserEmailStore<DpfbUser,Guid>
{
[Dependency]
internal IDpfbUserQueryEntry UserQueryEntry
{
get { return CqrsConfigurationResolver.Config.Construct<IDpfbUserQueryEntry>(); }
} internal ICommandBus CommandBus
{
get { return CqrsConfigurationResolver.CommandBus; }
} public Task CreateAsync(DpfbUser user)
{
throw new NotImplementedException();
} public Task DeleteAsync(DpfbUser user)
{
throw new NotImplementedException();
} public Task<DpfbUser> FindByIdAsync(Guid userId)
{
return UserQueryEntry.TryFetchAsync(userId);
} public Task<DpfbUser> FindByNameAsync(string userName)
{
return UserQueryEntry.TryFetchByNameAsync(userName);
} public Task UpdateAsync(DpfbUser user)
{
//throw new NotImplementedException();
return Task.FromResult();
} public void Dispose()
{
//do nothing
} public Task<DateTimeOffset> GetLockoutEndDateAsync(DpfbUser user)
{
//throw new NotImplementedException();
return Task.FromResult(new DateTimeOffset(DateTime.Now));
} public Task SetLockoutEndDateAsync(DpfbUser user, DateTimeOffset lockoutEnd)
{
//throw new NotImplementedException();
return Task.FromResult();
} public Task<int> IncrementAccessFailedCountAsync(DpfbUser user)
{
throw new NotImplementedException();
return Task.FromResult();
} public Task ResetAccessFailedCountAsync(DpfbUser user)
{
return Task.FromResult();
} public Task<int> GetAccessFailedCountAsync(DpfbUser user)
{
return Task.FromResult();
throw new NotImplementedException();
} public Task<bool> GetLockoutEnabledAsync(DpfbUser user)
{
return Task.FromResult(false);
throw new NotImplementedException();
} public Task SetLockoutEnabledAsync(DpfbUser user, bool enabled)
{
return Task.FromResult();
throw new NotImplementedException();
} public Task SetPasswordHashAsync(DpfbUser user, string passwordHash)
{
CommandBus.Send(new SetPasswordHashCommand() {UserId = user.Id, PasswordHash = passwordHash});
return Task.FromResult();
} public Task<string> GetPasswordHashAsync(DpfbUser user)
{
return UserQueryEntry.FetchPasswordHashAsync(user.Id);
} public Task<bool> HasPasswordAsync(DpfbUser user)
{
return UserQueryEntry.HasPasswordAsync(user.Id);
} public Task SetTwoFactorEnabledAsync(DpfbUser user, bool enabled)
{
return Task.FromResult(false);
throw new NotImplementedException();
} public Task<bool> GetTwoFactorEnabledAsync(DpfbUser user)
{
return Task.FromResult(false);
throw new NotImplementedException();
} public Task SetEmailAsync(DpfbUser user, string email)
{
throw new NotImplementedException();
return Task.FromResult();
} public Task<string> GetEmailAsync(DpfbUser user)
{
throw new NotImplementedException();
} public Task<bool> GetEmailConfirmedAsync(DpfbUser user)
{
throw new NotImplementedException();
return Task.FromResult(true);
} public Task SetEmailConfirmedAsync(DpfbUser user, bool confirmed)
{
throw new NotImplementedException();
return Task.FromResult();
} public Task<DpfbUser> FindByEmailAsync(string email)
{
throw new NotImplementedException();
}
}
配置
public partial class Startup
{
//配置Identity身份验证
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(() => new DpfbUserStore());
app.CreatePerOwinContext((IdentityFactoryOptions<AppUserManager> options,
IOwinContext context) =>
{
var manager = new AppUserManager(); //用户信息验证
manager.UserValidator = new UserValidator<DpfbUser, Guid>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
}; //密码验证
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = ,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
}; //配置最大出错次数
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes();
manager.MaxFailedAccessAttemptsBeforeLockout = ; //开启两步验证
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<DpfbUser, Guid>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<DpfbUser, Guid>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
}); //配置消息服务
manager.EmailService = new EmailService();
manager.SmsService = new SmsService(); var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<DpfbUser, Guid>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
});
app.CreatePerOwinContext(()=>new AppSignInManager()); //配置Cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/system/login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<AppUserManager, DpfbUser, Guid>(
TimeSpan.FromMinutes(),
(AppUserManager manager, DpfbUser user) =>
manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
user => new Guid(user.GetUserId<string>()))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes()); // Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
}
修改密码
AppUserManager的基类有个属性RequireUniqueEmail,当这个属性被置为true的时候,修改密码(以及其他敏感操作)会要求Email验证,对于内部系统而言,可以将这个属性置为false。
...
【加功能的时候再补充】
CQRS学习——集成ASP.NET Identity[其五]的更多相关文章
- 24.集成ASP.NETCore Identity
正常的情况下view页面的错误的显示应该是这么去判断的 这里我们就不加判断为了,直接用这个div 显示就可以了.当有错误会自动显示在div内 asp.net core Identity加入进来 这里用 ...
- CQRS学习——Dpfb以及其他[引]
[Dpfb的起名源自:Ddd Project For Beginer,这个Beginer自然就是博主我自己了.请大家在知晓这是一个入门项目的事实上,怀着对入门者表示理解的心情阅读本系列.不胜感激.] ...
- [ASP.NET MVC] ASP.NET Identity学习笔记 - 原始码下载、ID型别差异
[ASP.NET MVC] ASP.NET Identity学习笔记 - 原始码下载.ID型别差异 原始码下载 ASP.NET Identity是微软所贡献的开源项目,用来提供ASP.NET的验证.授 ...
- ASP.NET Identity 2集成到MVC5项目--笔记01
Identiry2是微软推出的Identity的升级版本,较之上一个版本更加易于扩展,总之更好用.如果需要具体细节.网上具体参考Identity2源代码下载 参考文章 在项目中,是不太想直接把这一堆堆 ...
- ASP.NET Identity 2集成到MVC5项目--笔记02
ASP.NET Identity 2集成到MVC5项目--笔记01 ASP.NET Identity 2集成到MVC5项目--笔记02 继上一篇,本篇主要是实现邮件.用户名登陆和登陆前邮件认证. 1. ...
- 从零搭建一个IdentityServer——集成Asp.net core Identity
前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...
- 学习asp.net Identity 心得体会(连接oracle)
asp.net Identity具体功能暂不在此细说,下面主要介绍几点连接oracle注意的事项, 1.首先下载连接oracle驱动Oracle.ManagedDataAccess.dll和Oracl ...
- ASP.NET Identity & OWIN 学习资料
有关 ASP.NET Identity 的更多细节: http://www.asp.net/identity 从一个空项目中添加 ASP.NET Identity 和 OWIN 支持: http:// ...
- asp.net identity的学习记录
# identity数据库 ## 创建空数据库 交给ef管理 ### 添加asp.net identity包 ``` Install-Package Microsoft.AspNet.Identity ...
随机推荐
- <转>cookie和缓存解析
原文来自:http://www.cnblogs.com/cuihongyu3503319/archive/2008/04/18/1160083.html 缓存cache 为了提高访问网页的速度,浏览器 ...
- response小结(二)——文件下载
我们先来看一个最简单的文件下载的例子: package com.yyz.response; import java.io.FileInputStream; import java.io.IOExcep ...
- 三星智能手机如何运用Smart Switch?
1.Smart Switch是指? 使用前注意事项: 将两部智能手机的距离保持在50cm以内 两部智能手机都下载相同的最新版本Smart Switch 确认可支持的机器参考应用程序说明 不受干扰的安静 ...
- spring @Resource和@Autowired的区别
@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了.@Resource有两个属性是比较重要的,分 ...
- day 0.
/* 嗯 就要结束了. OI生涯 2015.12-2016.11. 认识了很多人. 然后我这个学渣跟你们混在一起 感觉自卑至极啊. 好了 先不说这些伤心的话. Gryz小伙伴儿们NOIP RP++吧. ...
- Contest1065 - 第四届“图灵杯”NEUQ-ACM程序设计竞赛(个人赛)E粉丝与分割平面
题目描述 在一个平面上使用一条直线最多可以将一个平面分割成两个平面,而使用两条直线最多可将平面分割成四份,使用三条直线可将平面分割成七份--这是个经典的平面分割问题,但是too simple,作为一个 ...
- GDI+
1, 编译error的话一般是却 #include <comdef.h>#include <Windows.h> Windows.h内会包含Windows.h,但是因为在std ...
- cplusplus解析
经常在头文件包含代码里面看到如下代码 #ifndef MAC_API_H #define MAC_API_H #ifdef __cplusplus extern "C"{ #end ...
- C# 代理HTTP请求
目的: 应该有不少人需要去某些网站不停爬取数据,有时会使用HTTPRequest一直请求某个网站的某个网址.有的网站比如 QQ空间,赶集网(这是我测试的网站),不停刷新会提醒你的账号异常,可能会查封你 ...
- Android核心组件 Service
Service: 服务 Service 是Activity系统的核心组件之一. 因此需要继承和注册 Service 是内有界面的, 适合在后台长期的执行任务. (如放歌, 检测版本跟新, 下载, 上传 ...