Marko
Marko

Reputation: 10992

How to make "security" - attributes on classes in C#?

I want to make custom attributes on classes to restrict who calls them.

For example:

[Permission("Admin")]
public class MyData {
....

How to do that? So I want to really make some sort of Permission-class.

Upvotes: 3

Views: 4078

Answers (3)

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

You either use the ones that already exist, or you write your own and hook them into the Code Access Security architecture. This has been around for a really long time, and I was able to find these articles:

Code Access Security

Creating Your Own Code Access Permissions

Cut-away from the link above:

Implementing a custom code access permission involves the following steps, some of which are optional. Each step is described in a separate topic.

  1. Design the Permission class.
  2. Implement the IPermission and IUnrestrictedPermission interfaces.
  3. Implement the ISerializable interface, if necessary for performance or to support special data types.
  4. Handle XML encoding and decoding.
  5. Add support for declarative security, by implementing an Attribute class.
  6. Demand custom permission for your permission, where appropriate.

It's really steps 1, 2, 5 and 6 that are of interest to you.

Upvotes: 4

Jason Meckley
Jason Meckley

Reputation: 7591

Permission would inherit from Attribute. Then you would need to implement code to inspect the class for these attributes before calling the class/method. the .net framework already has this functionality built in. SecurityPermissionAttribute and FileIOPermissionAttribute are two implementations you may want to consider before rolling your own.

Upvotes: 0

Bueller
Bueller

Reputation: 2344

MSDN Custom Attributes

Here is a link to what is needed to create custom attributes.

Upvotes: -1

Related Questions