轻松地为角色提供程序使用ASP.NET标识

时间:2014-01-31 00:31:13

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我花了最近两天用我现有的数据库研究和实现新的ASP.NET身份系统。更多相关内容:Integrating ASP.NET Identity into Existing DbContext

现在,我有一个工作UserStoreRoleStore,但我似乎无法弄清楚如何在我的ASP.NET MVC 5应用程序中利用它们而不编写看似庞大的数量所有身份样本中的代码都让我感到困惑。

我想要实现两件事:1)使用cookie来维护授权; 2)使用角色限制应用程序访问视图和控制器中呈现的内容。

为了能够使用我需要的那些显然使用代表授权用户的Controller.User属性并查看它的角色。我如何获得我的Identity实现来实现这一目标?

最后,在身份示例中,我看到他们正在使用OWIN,这是我得到的,但它似乎是一种超级迂回的方式,我仍然没有得到如何正确实现。至于索赔,他们让我误解了我的两倍。

我很欣赏任何正确方向的指示。

2 个答案:

答案 0 :(得分:2)

回到此之后,我想我找到了一个简单有效的解决方案。我最终为OWIN创建了一个启动配置类。根据我的理解,因为OWIN是一个中间件,它拦截请求,计算出身份验证(如果有的话),并更新User类的Controller属性,其中User是一个实例一个ClaimsIdentity课程。

之后,其他一切都正常,就像您通常使用ASP.NET的User属性一样。我确实使用名为UserId的额外属性扩展了我的基本Controller,该属性解析User属性以获取数据库中使用的实际Id。我的意图是让我可以查询我Employee使用的真实DbContext类。我们会看到是否保留,同时,这是我StartupConfiguration的代码:

public sealed class StartupConfig {
    public void Configuration(
        IAppBuilder app) {
        this.ConfigureAuthentication(app);
    }

    public void ConfigureAuthentication(
        IAppBuilder app) {
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/"),
            ExpireTimeSpan = new TimeSpan(0, 60, 0)
        });
    }
}

以下是我配置UserId属性的方式:

protected int UserId {
    get {
        return Convert.ToInt32(base.User.Identity.GetUserId());
    }
}

不要忘记用[assembly: OwinStartupAttribute(typeof(namespace.StartupConfig))]装饰班级。希望这有助于某人。

答案 1 :(得分:1)

您是否记得将您的应用程序名称放在Web配置中?

<roleManager enabled="true">
   <providers>
      <clear />
        <add connectionStringName="ApplicationServices" 
             name="AspNetSqlRoleProvider"       
             type="System.Web.Security.SqlRoleProvider" 
             applicationName="DONT FORGET THIS PART" />
    </providers>
</roleManager>       

在控制器中使用以下某项。

[Authorize] //Anyone with authorization
[Authorize(Roles="Administrator")] //Admin role only

您也可以这样做。

HttpContext.User.IsInRole("Administrator")
UserManager.IsInRole(userID, "Administrator")
相关问题