【问题标题】:asp.net web api role based authentication custom attribute check if user in roleasp.net web api 基于角色的身份验证自定义属性检查用户是否在角色中
【发布时间】:2018-07-06 12:58:25
【问题描述】:

我在互联网上搜索了一下,但找不到我的意思......

您能否详细说明我在这里做错了什么以及我如何才能真正完成我需要的事情?多个字符串下方的代码注释中解释了问题。

um.FindByName(username) - 当然给我一个错误"The entity type ApplicationUser is not part of the model for the current context"

public class MyNewAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {


        if (actionContext.Request.Headers.Authorization == null)
        {
            base.OnAuthorization(actionContext);
        }
        else
        {
            string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
            string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
            string[] usernamePasswordArray = decodedToken.Split(':');
            string username = usernamePasswordArray[0];
            string password = usernamePasswordArray[1];


            // Here is the issue. I need to check whether the user is in admin role....
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new WeatherAppDbEntities()));
            var user = um.FindByName(username);

            var isInRole = um.IsInRole(user.Id, "Admin");


            if (// User is admin)
            {

            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }



    }

}

更新:

好吧,如果我使用,一切正常: var um = new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext())); 在我创建的新身份验证属性中......虽然不太确定使用 ApplicationDbContext() 和稍后创建的 Ado.net 数据模型的最佳实践是什么

【问题讨论】:

    标签: c# asp.net authentication user-roles


    【解决方案1】:

    就像 Stormcloak 提到的那样,您似乎有两个或多个 DbContexts,因此您使用的数据库或连接字符串不止一个。创建 Asp.Net MVC 项目时,模板带有一些模型和控制器,以及连接名为 “DefaultConnection” 的字符串。 Visual Studio 使用SQL Server Express 并使用连接字符串生成将存储用户信息的数据库,因此当您创建自己的数据库(“WeatherAppDb”)时,您基本上使用两个数据库。 如何预防?

    1. 在创建 MVC 项目时检查 Web.config 文件中的 &lt;connectionStrings&gt; 标签,如果你发现了什么 喜欢这个

     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyMVCProject-20180127104017.mdf;Initial Catalog=aspnet-MyMVCProject-20180127104017;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    
    <add name="WeatherAppDbConnectionString" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    

    最简单的方法是删除“默认连接”连接字符串并将“天气应用程序 DbConnectionString”重命名为“默认连接”,这样您就只剩下这个了

    //renamed from WeatherAppDbConnectionString to Default Connection
         <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\SQLEXPRESS;;Initial Catalog=WeatherAppDb;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    

    2. 完成第一步后,只需转到您的 WeatherAppDbEntities 并正如 StormCloack 所说,确保您在此处拥有“默认连接”

    public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
            {
                public WeatherAppDbEntities()
                    : base("DefaultConnection")
                {
                }
            }
    

    就您的代码而言,也许也有问题,但不确定,我已经修改了一点。

       WeatherAppDbEntities db = new WeatherAppDbEntities();
                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));               
                var user = db.Users.Find(username);
    

    【讨论】:

    • 抱歉,评论空间不足以解释这一切……我把它放在这里:codeshare.io/5MJjZq 但这不起作用……
    • 您看不到您使用的是两个名称不同的connection strings 吗?你试过改变 web.config 吗?
    • 好吧,先生,这就是在添加 ADO.NET 数据模型后 VS 为我生成所有这些的方式...这是整个应用程序:files.fm/u/qwffvz7x 抱歉,虽然可能无法确定如何继续对你来说似乎很明显......
    • 如果我使用,一切正常: var um = new UserManager(new UserStore(new ApplicationDbContext()));在我创建的新身份验证属性中...虽然不太确定将 ApplicationDbContext() 与稍后创建的 Ado.net 数据模型一起使用的最佳实践是什么...无论如何,感谢您的尝试,无论如何我都会将您的答案标记为正确.
    • 就在我正要启动你的应用程序 :D 时,告诉我你为什么需要使用你的身份验证 (MyNewAuthentication)?
    【解决方案2】:

    似乎ApplicationUser 身份不是您当前上下文WeatherAppDbEntities 的一部分。你应该在你的上下文中实现它。

    public class WeatherAppDbEntities : IdentityDbContext<ApplicationUser>
    {
        public WeatherAppDbEntities()
            : base("DefaultConnection")
        {
        }
    }
    

    【讨论】:

    • 我对 ASPNET 身份的事情并不是很流利,但我所做的基本上是创建了一个具有授权的 MVC 应用程序,并让它为我创建了一个数据库,然后我添加了一个额外的表到这个 DB.... 无论如何,我试过了,但似乎也不起作用,同样的错误:public partial class WeatherAppDbEntities : IdentityDbContext // DbContext { public WeatherAppDbEntities() : base("name=WeatherAppDbEntities") { } ...... } "throwIfV1Schema" 未找到,但说评论太长,秒。
    • 我得到的错误是:“实体类型 ApplicationUser 不是当前上下文模型的一部分”
    • 当我使用“DefaultConnection”时,我得到:System.Data.Entity.Infrastructure.UnintentionalCodeFirstException:'上下文正在代码优先模式下使用,代码是从 EDMX 文件生成的数据库优先或模型优先开发。这将无法正常工作。要解决此问题,请不要删除引发此异常的代码行。如果您希望使用 Database First 或 Model First,请确保 Entity Framework 连接字符串包含在启动项目的 app.config 或 web.config 中。如果您正在创建自己的 DbConn....
    猜你喜欢
    • 2017-08-26
    • 2020-11-16
    • 2016-03-07
    • 2018-09-06
    • 2021-02-21
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多