我一直在学习开箱即用欧文身份我喜欢它为我们提供的用户管理的易用性。然后我遇到的问题是它通过(似乎)直接与 EF 交互ApplicationDbContext
这是我不想要的。我更喜欢使用我的 3 层架构,IE 它与服务层 (BLL) 交互,而服务层又与 EF 交互。我找不到模板、教程,甚至找不到起点来维护所提供的所有功能并实现我想要的分离。
那么有没有办法使用服务层来代替ApplicationDbContext
在 MVC 身份包中。
如果您想使用现有的数据库/表,则不必使用整个 ASP.Net Identity。相反,你可以使用Owin Cookie 身份验证中间件.
我有工作示例代码GitHub。如果你想测试它,你只需设置一个断点AccountController.cs,并返回 true。
以下是配置中间件和登录的两个主要类。
启动.cs
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)