【其实和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. Ajax中解析Json的两种方法详解

    eval();  //此方法不推荐 JSON.parse();  //推荐方法 一.两种方法的区别 我们先初始化一个json格式的对象: var jsonDate = '{ "name&qu ...

  2. Commons Lang - StringUtils

    Operations on String that are null safe. IsEmpty/IsBlank - checks if a String is empty (判断字符串是否为空) T ...

  3. 更换用installshield打包生成exe文件的图标【转】

    最近在研究用installshield2010为自己做的产品打包,自己在网上找写资料,胡乱折腾,最后弄成了一个exe安装包,想要修改exe文件的图标,发现Basic MSI project 无法用in ...

  4. 剑指offer——替换字符串

    总结:先计算出总共有多少空格,count++:然后从后往前遍历,每遇到一个空格,count--:       替换空格 参与人数:2119时间限制:1秒空间限制:32768K 通过比例:20.23% ...

  5. LeftOuterJoin和OuterApply性能比较(转)

    建立测试环境: 建立一个表Department和Employee,并向Department插入50W条记录,向Employee插入200W条记录, 我们就拿[统计DepartmentID 从15000 ...

  6. WCF开发教程资源收集

    WCF开发教程资源收集 1.蒋金楠,网名Artech的博客 [原创]我的WCF之旅(1):创建一个简单的WCF程序[原创]我的WCF之旅(2):Endpoint Overview[原创]我的WCF之旅 ...

  7. C#编写以管理员身份运行的程序

    using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; names ...

  8. reduce + Promise 顺序执行代码

    本文地址: http://www.cnblogs.com/jasonxuli/p/4398742.html 下午的太阳晒得昏昏沉沉,和上周五一样迷糊,看一段代码半天没看明白,刚才不知不觉眯了几分钟,醒 ...

  9. 详解null

    前言 在java中初始化的时候经常用到null,也经常会碰到空指针异常(NullPointerException),由于碰到的频率比较高,我认为有必要进行一下了解,揭开它的神秘面纱. 一.null是代 ...

  10. 小黑的镇魂曲(HDU2155:贪心+dfs+奇葩解法)

    题目:点这里 题目的意思跟所谓的是英雄就下100层一个意思……在T秒内能够下到地面,就可以了(还有一个板与板之间不能超过H高). 接触这题目是在昨晚的训练赛,当时拍拍地打了个贪心+dfs,果断跟我想的 ...