.NET Security

M

Martin

Hi all,

Those days, I explore the System.Security namespace but, of course, I
have a question.

I really appreciate the way we can secure a method with the
PrincipalPermissionAttribute above the method signature. In the
following case, to execute the function, the user must be Bob and his
role must be Supervisor. So far, everything is OK.

[PrincipalPermissionAttribute(SecurityAction.Demand, Name="Bob",
Role="Supervisor")]
public void MaSuperFonction()
{
Console.WriteLine("Allô!");
}

Now, why I can't do that?

[PrincipalPermissionAttribute(SecurityAction.Demand,
Name=GetAllowedUsers(), Role=GetAllowedRoles())]
public void MaSuperFonction()
{
Console.WriteLine("Allô!");
}

I can't beleive that I have to hardcode Users and Roles to use
Microsoft security...

Thanks for you help!

Martin
 
N

Nicholas Paldino [.NET/C# MVP]

Martin,

Well, the reason you can't do it in the attribute is because the
attribute is part of the compiled metadata for the assembly, and you are
looking for something more dynamic.

What you can do, is something like this:


public void MaSuperFonction()
{
// Get the current principal.
IPrincipal principal = Thread.CurrentPrincipal;

// At this point, you can check to see if the user is in a current role.
// In your case, you would cycle through the roles that are allowed, and
make
// a call to IsInRole for each one.
bool isInRole = principal.IsInRole("some role");

// You can also get the current user's name:
string name = principal.Identity.Name;

// If the name or role doesn't match, throw a SecurityException here.


// Continue with your code.
Console.WriteLine("Allô!");
}

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)



Hi all,

Those days, I explore the System.Security namespace but, of course, I
have a question.

I really appreciate the way we can secure a method with the
PrincipalPermissionAttribute above the method signature. In the
following case, to execute the function, the user must be Bob and his
role must be Supervisor. So far, everything is OK.

[PrincipalPermissionAttribute(SecurityAction.Demand, Name="Bob",
Role="Supervisor")]
public void MaSuperFonction()
{
Console.WriteLine("Allô!");
}

Now, why I can't do that?

[PrincipalPermissionAttribute(SecurityAction.Demand,
Name=GetAllowedUsers(), Role=GetAllowedRoles())]
public void MaSuperFonction()
{
Console.WriteLine("Allô!");
}

I can't beleive that I have to hardcode Users and Roles to use
Microsoft security...

Thanks for you help!

Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top