Using an ASP.NET identifier for a role provider is easy

I just spent the last two days researching and implementing a new ASP.NET Identity system with my existing database. More on this here: Integrating an ASP.NET identifier into an existing DbContext .

Now I have workers UserStoreand RoleStore, but I can’t understand how to use them in my ASP.NET MVC 5 application without writing what seems like a huge amount of code, as in all the identity samples that confuse me.

There are two things that I want to achieve: 1) use cookies to support authorization, and 2) use roles to restrict access to applications both in what is displayed in views and on controllers.

To use those, I need to explicitly use a property Controller.Userthat represents an authorized user and peeks in his role. How can I implement my implementation of Identity?

Finally, in the Identity samples, I see that they use OWIN, which I’m getting, but it seems that this is a super circular path, which I still don’t understand how to implement correctly. As for the claims, they confuse me twice as much as I understand them.

I would appreciate any pointers in the right direction.

+4
source share
2 answers

, , , . OWIN. , , OWIN , , ( ) User Controller, User ClaimsIdentity.

, User ASP.NET. UserId, 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))]. , -.

+2

-?

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

Source: https://habr.com/ru/post/1524627/


All Articles