Using ASP.NET Identity for a Role Provider easily

南楼画角 提交于 2019-12-01 06:26:15

After going back into this I think I figured out a solution that simply works. I ended up creating a startup configuration class for OWIN. From what I understand since OWIN is a middleware it intercepts the requests, figures out the authentication (if any), and updates the User property of the Controller classes where User is an instance of a ClaimsIdentity class.

After that everything else works just as you would normally use the User property of ASP.NET. I did extend my base Controller with an extra property called UserId which parses the User property to get the actual Id being used in the database. My intention with that is to have the Id available to me to query for the real Employee class that my DbContext uses. We'll see if that stays or not, in the mean time, here's the code for my 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)
        });
    }
}

Here's how I configured my UserId property:

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

Don't forget to decorate the class with [assembly: OwinStartupAttribute(typeof(namespace.StartupConfig))]. Hope this helps somebody.

Did you remember to put your application name in your web config?

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

Use one of the following in your controllers.

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

You could also do something like this.

HttpContext.User.IsInRole("Administrator")
UserManager.IsInRole(userID, "Administrator")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!