Using ASP.NET Identity for a Role Provider easily

2019-02-18 06:47发布

问题:

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 Existing DbContext.

Now, I have a working UserStore and RoleStore, but I can't seem to figure out how to leverage them in my ASP.NET MVC 5 application without writing what seems like colossal amounts of code like in all the Identity samples that confuse me.

There's two things I want to achieve: 1) use cookies to maintain the authorizations and 2) use roles to limit application access both in what is rendered in the views and on the controllers.

To be able to use those I need to obviously use the Controller.User property which represents the authorized user and peek into it's roles. How do I get my Identity implementation to make that happen?

Lastly, in the Identity samples I see they're using OWIN, which I kind of get, but it seems like it's a super roundabout way, which I still don't get how to properly implement. As far as Claims, they confuse me twice as much as I understand them.

I'd appreciate any pointers in the right direction.

回答1:

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.



回答2:

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")