充分利用MVC Owin身份验证与n(3)层架构

4
我一直在学习Owin Identity并喜欢它提供的用户管理易用性。但是,它直接通过ApplicationDbContext与EF交互(似乎是这样),而我不想要这种情况。我希望使用我的三层架构,即它与服务层(BLL)交互,再由服务层与EF交互。我找不到一个模板、教程或者起点来维护所有已提供的功能并实现我想要的分离方法。

所以,是否有一种方法可以在MVC Identity包中使用服务层来代替ApplicationDbContext呢?


您想要使用自定义表格来使用ASP.Net身份验证吗? - Win
@Win 我想使用我的DAL层正在使用的数据库,其中有一个名为User的表,但我对使用的列名感到满意。 - Halter
1个回答

1
如果您想使用现有的数据库/表格,就无需使用整个ASP.Net身份验证。相反,您可以只使用Owin Cookie身份验证中间件。
我在GitHub上有可用的样例代码。如果您想进行测试,只需在AccountController.cs设置断点并返回true即可。
以下是配置中间件和登录的两个主要类。

Startup.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);
    }
}

很酷,使用这个我只需要在OwinAuthenticationService中利用我的BLL?然后从那里我可以添加像注册、电子邮件验证、短信验证等东西。我正在使用个人帐户,这就是我试图保持功能完整的原因,比如生成的AccountController - Halter
您需要将ActiveDirectoryService替换为您的服务,该服务基本上会验证用户的凭据并返回true或false。 - Win

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接