【问题标题】:using aspnet identity with custom tables将 aspnet 身份与自定义表一起使用
【发布时间】:2017-03-28 20:49:24
【问题描述】:

我正在开发 asp.net MVC 核心应用程序。我有带有用户和角色表的自定义数据库。我想将 asp.net 身份与自定义表一起使用,这样我就不必使用 aspnetusers、aspnet 角色表。如何使用 asp.net 身份和 asp.net 核心来做到这一点

【问题讨论】:

    标签: c# asp.net-core-mvc asp.net-identity-2


    【解决方案1】:

    祝你好运! :) 我最近几天刚刚经历了这个过程。我已经让它工作了,但在某些阶段真的很痛苦。

    简而言之:

    1. 您需要创建自己的用户模型来实现 IUser 接口。
    2. 您需要创建自己的 DAL,从您的自定义数据库表中获取数据
    3. 您需要实现自己的 UserStore,根据您要使用的 asp.identity 的功能实现不同的接口

    此链接将帮助您: https://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity

    【讨论】:

    • 我自己的表是否可以替代 asp.net 身份或 aspnet 身份?
    • 我不确定我是否理解您的问题。你能解释一下你的意思吗?
    • 啊哈,好的。不,它不能替代 asp.net 身份。它是 asp.identity 使用您自己的数据库。这就是重点:asp.identity 内部使用它的接口,然后您必须实现接口以与您的自定义数据库进行通信,以便告诉 asp.identity 如何使用它。正如链接上的第一句话所说:“ASP.NET Identity 是一个可扩展的系统,它使您能够创建自己的存储提供程序并将其插入到您的应用程序中,而无需重新处理应用程序。”
    • 提供的链接是为 IdentityServer 2.0 编写的文章,而不是最新版本,目前为 4.0。要求可能有所不同,但这是一个很好的起点。
    【解决方案2】:

    您可以使用 Cookie 中间件身份验证。

    在您的 Startup.cs 中添加

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
       {
           AuthenticationScheme = "MyCookieMiddlewareInstance",
           LoginPath = new PathString("/Account/Unauthorized/"),
           AccessDeniedPath = new PathString("/Account/Forbidden/"),
           AutomaticAuthenticate = true,
           AutomaticChallenge = true
       });
    

    在您的代码中,验证用户名和密码后,登录您调用

    await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);
    

    签字

    await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
    

    更多详情请查看Microsoft website的文章

    【讨论】:

    • 这种情况下如何处理注册?是用我自己的表替代 asp.net 身份还是 aspnet 身份?
    • 您必须使用您自己的注册方法使用此方法。您的用户和角色表可以看起来没有任何限制。
    猜你喜欢
    • 2020-04-10
    • 2021-01-03
    • 1970-01-01
    • 2023-04-02
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多