Enable or disable a method that runs in .NET.

I need to arrange some simple safety in the class, depending on the value of the enumeration. All I can figure out is to use the method attribute, and then run the check, and then if it does not throw an exception. Example:

    [ModulePermission(PermissonFlags.Create)]
    public void CreateNew()
    {
        CheckPermission();
        System.Windows.Forms.MessageBox.Show("Created!");
    }
    protected void CheckPermission()
    {
        var method = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
        if (!flags.HasFlag(method.GetCustomAttributes(true).Cast<ModulePermissionAttribute>().First().Flags))
        {
            throw new ApplicationException("Access denied");
        }
    }

Is there a more elegant or simple way to do this, for example, just throw an event when the method starts?

+3
source share
4 answers

Not with the enumeration, but with the strings - voila (forcibly executed at runtime, even in full trust):

public static class PermissionFlags {
    public const string Create = "Create";
}

[PrincipalPermission(SecurityAction.Demand, Role = PermissionFlags.Create)]
public void CreateNew() {
    System.Windows.Forms.MessageBox.Show("Created!");
}

, , . ASP.NET, winform ( VS2008 ..) ASP.NET . winilla winforms WCF; , GenericPrincipal/GenericIdentity:

// during login...
string[] roles = { PermissionFlags.Create /* etc */ };
Thread.CurrentPrincipal = new GenericPrincipal(
    new GenericIdentity("Fred"), // user
        roles);

/ (, / ).

+3

Code Access Security ?

, , , , . , ...

+6

- . , Postsharp, "" , ModulePermission.

, CheckPermission "" , Postsharp.

( Postsharp: http://fgheysels.blogspot.com/2008/08/locking-system-with-aspect-oriented.html)

0

You might want to look at this with PostSharp , which will give you a framework for applying attributes so you don't have to run validation in your method. This can, however, increase complexity depending on how the currently active flags are accessed. You probably need some class to cache the current permissions for the current user.

0
source

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


All Articles