Using ASP.NET Identity for a Role Provider easily

前端 未结 2 1351
孤街浪徒
孤街浪徒 2021-01-14 01:49

I just spent the last two days researching and implementing the new ASP.NET Identity system with my existing database. More on that here: Integrating ASP.NET Identity into E

相关标签:
2条回答
  • 2021-01-14 01:58

    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")
    
    0 讨论(0)
  • 2021-01-14 02:05

    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.

    0 讨论(0)
提交回复
热议问题