简体   繁体   中英

How to use enum in AuthorizeAttribute the razor mvc?

I have this enum:

public enum PerfilUsuarioEnum
{
    AdministradorSistema = 1,
    AdministradorLoja = 2,
    Gerente = 3
}

And I want to pass it on my Authorize roles

[Authorize(Roles = PerfilUsuarioEnum.AdministradorLoja + ", " + PerfilUsuarioEnum.Gerente)]

There is some manner to do this?

Roles has to be constant expression such as string. Easiest way is to use cosntant.

public static class PerfilUsuario
{
   public const string AdministradorLoja = "AdministradorLoja";
   public const string Gerente = "NaviGerentegators";
}

[Authorize(Roles = PerfilUsuario.AdministradorLoja + ", " +
     PerfilUsuario.Gerente)]

Great question. Here is what I did...

I decided to make my permissions database driven so I needed a way to convert strings into something "typed" so that I could get compile time warnings and also so I could change the name of the permission in the database and not have to update all of our production code. Since the attributes are string based (so called magic strings), I decided against enumerations and went with a T4 script that read the database and generated a struct for each record. This allowed me to also add things like, a nice display name, details about the permission, and an error message that I could show the user.

Here is a sample permission row after the T4 template runs.

public struct CanViewClaimData
{
    // Using const allows the compiler to generate the values in the assembly at compile time and satisfy MVC Authorize Attribute requirements for const strings.
    public const System.String Name = "CanViewClaimData";
    public const System.String DisplayName = "Can View Claim Data";
    public const System.String Description = "The allows users to view claim data";
    public const System.String DefaultErrorMessage = "You must have the \"Can View Claim Data\" permission to access this feature.";

}

Then in code I use a sub classed Authorize and mark the Action as such,

[Security.AuthorizedAttribute(Roles = CanViewClaimData.Name, Message = CanViewClaimData.DefaultErrorMessage)]

Then during each automated build and push to our CI environment, I run the T4 template as part of the build process to keep the struct strings in sync with the database.

So far this has worked really well and allowed me to give our product owner the ability to edit the permission names, descriptions etc, in the database and without a developer having to be involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM