Visual Basic 1002005 [A Developers Notebook] [Electronic resources]

شرکت رسانه او ریلی

نسخه متنی -صفحه : 97/ 92
نمايش فراداده

6.5. Test Group Membership of the Current User

The .NET Framework has always provided security classes that let you retrieve basic information about the account of the current user. The new My.User object provided by Visual Basic 2005 makes it easier than ever to access this information.


Note: Find out who's using your application, and the groups a mystery user belongs to.


6.5.1. How do I do that?

Applications often need to test who is running the application. For example, you might want to restrict some features to certain groups, such as Windows administrators. You can accomplish this with the My.User object.

The My.User object provides two key properties that return information about the current user. These are:

IsAuthenticated

Returns true if the current user account information is available in the My.User object. The only reason this information wouldn't be present is if you've created a web application that allows anonymous access, or if the current Windows account isn't associated with the application domain.

Username

Returns the current username. Assuming you're using a Windows security policy, this is the Windows account name for the user, in the form ComputerName\UserName or DomainName\UserName.

The My.User object also provides a single method, IsInRole( ). This method accepts the name of a group (as a string) and then returns true if the user belongs to that group. For example, you could use this technique to verify that the current user is a Windows administrator before performing a certain task.

To try this out, use the following console application in Example 6-5, which displays some basic information about the current user and tests if the user is an Administrator.


Note: To check the user and group list for the current computer (or make changes), select Computer management from the Administrative Tools section of the Control Panel. Then, expand the System Tools Local Users and Groups node.


Example 6-5. Testing the current user identity
Module SecurityTest
Sub Main( )
' Use Windows security. As a result, the User object will
' provide the information for the currently logged in user
' who is running the application.
My.User.InitializeWithWindowsUser( )
Console.WriteLine("Authenticated: " & My.User.Identity.IsAuthenticated)
Console.WriteLine("User: " & My.User.Identity.Username)
Console.WriteLine("Administrator: " & My.User.IsInRole("Administrators"))
End Sub
End Module

Here's the sort of output you'll see when you run this test:

Authenticated: True
User: FARIAMAT\Matthew
Administrator: True