问题描述
我一直在学习开箱即用 Owin身份,我喜欢它的易用性为我们提供了用户管理.然后我遇到的问题是,它通过我不想要的ApplicationDbContext
直接与EF(看似)直接交互.我更喜欢利用我的3层体系结构,即IE与与EF交互的服务层(BLL)进行交互.我找不到模板,教程甚至起点来维护提供的所有功能并实现所需的分离.
I've been learning out of the box Owin Identity and I love the ease of use it provides us with user management. Then problem that I have is that it interacts directly with EF (seemingly) via ApplicationDbContext
which I don't want. I would prefer to utilize my 3 tier architecture, IE it interacts with a service layer (BLL) which interacts with EF. I can't find a template, tutorial, or even starting point to maintain all the functionality that is provided and achieve the separation I want.
因此,有一种方法可以使用服务层代替MVC Identity软件包中的ApplicationDbContext
.
So is there a way to use a service layer in place of the ApplicationDbContext
in MVC Identity package.
推荐答案
如果要使用现有的数据库/表,则不必使用整个ASP.Net Identity.相反,您可以只使用 Owin Cookie身份验证中间件 .
If you want to use existing database/tables, you do not have to use entire ASP.Net Identity. Instead, you can just use Owin Cookie Authentication middleware.
我在 GitHub 上具有有效的示例代码.如果要测试,只需在 AccountController.cs ,并返回true.
I have working sample code at GitHub. If you want to test it, you just set a break-point at AccountController.cs, and return true.
以下是配置中间件和登录的两个主要类别.
The followings are two main classes of configure the middleware and sign-in.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
OwinAuthenticationService.cs
public class OwinAuthenticationService : IAuthenticationService
{
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";
public OwinAuthenticationService(HttpContextBase context)
{
_context = context;
}
public void SignIn(User user)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
public void SignOut()
{
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignOut(AuthenticationType);
}
}
这篇关于充分利用具有n(3)层架构的MVC Owin身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!