【其实和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[其五]的更多相关文章

  1. 24.集成ASP.NETCore Identity

    正常的情况下view页面的错误的显示应该是这么去判断的 这里我们就不加判断为了,直接用这个div 显示就可以了.当有错误会自动显示在div内 asp.net core Identity加入进来 这里用 ...

  2. CQRS学习——Dpfb以及其他[引]

    [Dpfb的起名源自:Ddd Project For Beginer,这个Beginer自然就是博主我自己了.请大家在知晓这是一个入门项目的事实上,怀着对入门者表示理解的心情阅读本系列.不胜感激.] ...

  3. [ASP.NET MVC] ASP.NET Identity学习笔记 - 原始码下载、ID型别差异

    [ASP.NET MVC] ASP.NET Identity学习笔记 - 原始码下载.ID型别差异 原始码下载 ASP.NET Identity是微软所贡献的开源项目,用来提供ASP.NET的验证.授 ...

  4. ASP.NET Identity 2集成到MVC5项目--笔记01

    Identiry2是微软推出的Identity的升级版本,较之上一个版本更加易于扩展,总之更好用.如果需要具体细节.网上具体参考Identity2源代码下载 参考文章 在项目中,是不太想直接把这一堆堆 ...

  5. ASP.NET Identity 2集成到MVC5项目--笔记02

    ASP.NET Identity 2集成到MVC5项目--笔记01 ASP.NET Identity 2集成到MVC5项目--笔记02 继上一篇,本篇主要是实现邮件.用户名登陆和登陆前邮件认证. 1. ...

  6. 从零搭建一个IdentityServer——集成Asp.net core Identity

    前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...

  7. 学习asp.net Identity 心得体会(连接oracle)

    asp.net Identity具体功能暂不在此细说,下面主要介绍几点连接oracle注意的事项, 1.首先下载连接oracle驱动Oracle.ManagedDataAccess.dll和Oracl ...

  8. ASP.NET Identity & OWIN 学习资料

    有关 ASP.NET Identity 的更多细节: http://www.asp.net/identity 从一个空项目中添加 ASP.NET Identity 和 OWIN 支持: http:// ...

  9. asp.net identity的学习记录

    # identity数据库 ## 创建空数据库 交给ef管理 ### 添加asp.net identity包 ``` Install-Package Microsoft.AspNet.Identity ...

随机推荐

  1. 让footer固定在页面(视口)底部(CSS-Sticky-Footer)

    让footer固定在页面(视口)底部(CSS-Sticky-Footer) 这是一个让网站footer固定在浏览器(页面内容小于浏览器高度时)/页面底部的技巧.由HTML和CSS实现,没有令人讨厌的h ...

  2. 【转载】Android设计中的.9.png

      转载自:腾讯ISUX (http://isux.tencent.com/android-ui-9-png.html) 在Android的设计过程中,为了适配不同的手机分辨率,图片大多需要拉伸或者压 ...

  3. VBA 将 ANSI 转换为 UTF-8文件

    在使用的时候,先用WriteOut生成一个临时文件(UTF-8带BOM),然后用Convert2utf8将BOM头的前三个字节删除. --------------------------------- ...

  4. APC -- Asynchronous Procedure Call 异步过程调用

    异步过程调用(APC -- Asynchronous Procedure Call )是一种与常用的和简单的同步对象不同的一种同步机制. 我们在我们线程里使用基本的同步对象如MUTEX去通知其它线程, ...

  5. 为oracle中的表格增加列和删除列

    http://blog.csdn.net/rainharder/article/details/6663458 alter table 表名 drop column 列名eg:alter table ...

  6. 暑假集训(4)第六弹——— 组合(poj1067)

    题意概括:上一次,你成功甩掉了fff机械兵.不过,你们也浪费了相当多的时间.fff团已经将你们团团包围,并且逐步 逼近你们的所在地.面对如此危机,你不由得悲观地想:难道这acm之路就要从此中断?虽然走 ...

  7. oracle 之路目录

    oracle linux单机安装 oracle windows单机安装创建实例卡死解决办法 oracle rac安装 HPDL380G8平台11.2.0.3 RAC实施手册 pl-sql develo ...

  8. 巧用Systemtap注入延迟模拟IO设备抖动

    原创文章,转载请注明: 转载自系统技术非业余研究 本文链接地址: 巧用Systemtap注入延迟模拟IO设备抖动 当我们的IO密集型的应用怀疑设备的IO抖动,比如说一段时间的wait时间过长导致性能或 ...

  9. Linux学习之路一计算机是如何工作的

    初次接触MOOC课堂,里面有个很牛X的老师教Linux,恰好自己有兴趣学,顾有了此系列学习博文. 第一讲   计算机是如何工作的 学习Linux,涉及到了C语言和汇编以及操作系统的知识,顾第一讲要讲讲 ...

  10. hibernate导入大量数据时,为了避免内存中产生大量对象,在编码时注意什么,如何去除?

    Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( i ...