1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 3.5 in C# and Visual Basic Part 107 pps

10 220 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 428,44 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Name Provides the username of the user as well as the domain of the user only if he logged on with a Windows account.. Listing 21-12: Getting the username of the logged-in user VB Dim Us

Trang 1

❑ IsInRole: This method takes a single parameter, a string representation of the system role It

returns a Boolean value that indicates whether the user is in the role specified

Working with User.Identity

TheUser.Identityproperty enables you to work with some specific contextual information about the

authorized user Using the property within your ASP.NET applications enables you to make

resource-access decisions based on the information the object provides

WithUser.Identity, you can gain access to the user’s name, his authentication type, and whether he is

authenticated The following table details the properties provided throughUser.Identity

Attribute Description

Authentication

Type Provides the authentication type of the current user Example values include

Basic,NTLM,Forms, andPassport

IsAuthenticated Returns a Boolean value specifying whether the user has been authenticated

Name Provides the username of the user as well as the domain of the user (only if he

logged on with a Windows account)

For some examples of working with theUserobject, take a look at checking the user’s login name To do

this, you use code similar to that shown in Listing 21-12

Listing 21-12: Getting the username of the logged-in user

VB

Dim UserName As String

UserName = User.Identity.Name

C#

string userName;

userName = User.Identity.Name;

Another task you can accomplish with theUser.Identityobject is checking whether the user has been

authenticated through your application’s authentication methods, as illustrated in Listing 21-13

Listing 21-13: Checking whether the user is authenticated

VB

Dim AuthUser As Boolean

AuthUser = User.Identity.IsAuthenticated

C#

bool authUser;

authUser = User.Identity.IsAuthenticated;

This example provides you with a Boolean value indicating whether the user has been authenticated

You can also use theIsAuthenticatedmethod in anIf/Thenstatement, as shown in Listing 21-14

Trang 2

Listing 21-14: Using an If/Then statement that checks authentication

VB

If (User.Identity.IsAuthenticated) Then

’ Do some actions here for authenticated users

Else

’ Do other actions here for unauthenticated users

End If

C#

if (User.Identity.IsAuthenticated) {

// Do some actions here for authenticated users

}

else {

// Do other actions here for unauthenticated users

}

You can also use theUserobject to check the authentication type of the user This is done with the

AuthenticationTypeproperty illustrated in Listing 21-15

Listing 21-15: Using the AuthenticationType property

VB

Dim AuthType As String

AuthType = User.Identity.AuthenticationType

C#

string authType;

authType = User.Identity.AuthenticationType;

Again, the result isBasic,NTLM,Forms, orPassport

Working with User.IsInRole()

If you are using Windows-based authentication, you can check to make sure that an authenticated user is

in a specific Windows role For example, you might want to show specific information only for users in theSubscribersgroup in the Computer Management Utility To accomplish that, you can use theUser

object’sIsInRolemethod, as shown in Listing 21-16

Listing 21-16: Checking whether the user is part of a specific role

VB

If (User.IsInRole("ReutersServer\Subscribers")) Then

’ Private information for subscribers

Else

’ Public information

End If

C#

Trang 3

else {

// Public information

}

TheIsInRolemethod’s parameter provides a string value that represents the domain and the group

(Windows role) In this case, you specify that any user in theSubscribersWindows role from the

ReutersServerdomain is permitted to see some information not available to users who don’t belong

to that specific role

Another possibility is to specify some of the built-in groups available to you Ever since Windows 2000,

Windows has included a series of built-in accounts such as Administrator, Guest, PrintOperator, and

User You can access these built-in accounts in a couple of ways One is to specify the built-in account

with the domain directly:

User.IsInRole("ReutersServer\Administrator")

The other possibility is to use theBUILTINkeyword:

User.IsInRole("BUILTIN\Administrator")

Pulling More Information with WindowsIdentity

So far, in working with the user’s identity information, you have used the standardIdentityobject that

is part of ASP.NET by default If you are working with Windows-based authentication, you also have

the option of using theWindowsIdentityobject and other objects To gain access to these richer objects,

create a reference to theSystem.Security.Principalobject in your application

Used in combination with theIdentityobject from the preceding examples, these additional objects

make certain tasks even easier For instance, if you are working with roles,System.Security.Principal

provides access to theWindowsBuiltInRoleenumeration

Listing 21-17 is an example of using theWindowsBuiltInRoleenumeration

Listing 21-17: Using the WindowsBuiltInRole enumeration

VB

Dim AdminUser As Boolean

AdminUser = User.IsInRole(WindowsBuiltInRole.Administrator.ToString())

C#

bool adminUser;

adminUser = User.IsInRole(WindowsBuiltInRole.Administrator.ToString());

Instead of specifying a string value of the domain and the role, you can use theWindowsBuiltInRole

enumeration to easily access specific roles on the application server When working with this and other

enumerations, you also have IntelliSense (see Figure 21-11) to help you make your selections easily

Trang 4

Figure 21-11

The roles in theWindowsBuiltInRoleenumeration include the following:

Trang 5

UsingSystem.Security.Principal, you have access to theWindowsIdentityobject, which is much

richer than working with the defaultIdentityobject Listing 21-18 lists some of the additional

informa-tion you can get through theWindowsIdentityobject

Listing 21-18: Using the WindowsIdentity object

VB

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Security.Principal" %>

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, _

ByVal e As System.EventArgs)

Dim AuthUser As WindowsIdentity = WindowsIdentity.GetCurrent()

Response.Write(AuthUser.AuthenticationType.ToString() & "<br>" & _

AuthUser.ImpersonationLevel.ToString() & "<br>" & _

AuthUser.IsAnonymous.ToString() & "<br>" & _

AuthUser.IsAuthenticated.ToString() & "<br>" & _

AuthUser.IsGuest.ToString() & "<br>" & _

AuthUser.IsSystem.ToString() & "<br>" & _

AuthUser.Name.ToString()) End Sub

</script>

C#

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Security.Principal" %>

<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

WindowsIdentity AuthUser = WindowsIdentity.GetCurrent();

Response.Write(AuthUser.AuthenticationType.ToString() + "<br>" +

AuthUser.ImpersonationLevel.ToString() + "<br>" +

AuthUser.IsAnonymous.ToString() + "<br>" +

AuthUser.IsAuthenticated.ToString() + "<br>" +

AuthUser.IsGuest.ToString() + "<br>" +

AuthUser.IsSystem.ToString() + "<br>" +

AuthUser.Name.ToString());

}

</script>

In this example, an instance of theWindowsIdentityobject is created and populated with the current

identity of the user accessing the application Then you have access to a number of properties that are

written to the browser using aResponse.Write()statement The displayed listing shows information

about the current user’s credentials, such as if the user is authenticated, anonymous, or running under

a guest account or a system account It also gives you the user’s authentication type and login name A

result is shown in Figure 21-12

Trang 6

Figure 21-12

Identity and Impersonation

By default, ASP.NET runs under an account that has limited privileges For instance, you may find that although the account can gain access to a network, it cannot be authenticated to any other computer on the network

The account setting is provided in themachine.configfile:

<processModel

enable="true"

userName="machine"

password="AutoGenerate" />

These settings force ASP.NET to run under the system account (ASPNET or Network Service) This is

really specified through theuserNameattribute that contains a value ofmachine The other possible value you can have for this attribute issystem Here’s what each entails:

❑ machine: The most secure setting You should have good reasons to change this value It’s the

ideal choice mainly because it forces the ASP.NET account to run under the fewest number of

privileges possible

❑ system: Forces ASP.NET to run under the local SYSTEM account, which has considerably more privileges to access networking and files

It is also possible to specify an account of your choosing using the<processModel>element in either the

machine.configorweb.configfiles:

Trang 7

enable="true"

userName="MySpecifiedUser"

password="MyPassword" />

In this example, ASP.NET is run under a specified administrator or user account instead of the default

ASPNET or Network Service account It inherits all the privileges this account offers You should consider

encrypting this section of the file Encrypting sections of a configuration file are covered in Chapter 32

You can also change how ASP.NET behaves in whatever account it is specified to run under through the

<identity>element in theweb.configfile The<identity>element in theweb.configfile allows you

to turn on impersonation Impersonation provides ASP.NET with the capability to run as a process using

the privileges of another user for a specific session In more detail, impersonation allows ASP.NET to

run under the account of the entity making the request to the application To turn on this impersonation

capability, you use theimpersonateattribute in the<identity>element as shown here:

<configuration>

<system.web>

<identity impersonate="true" />

</system.web>

</configuration>

By default, theimpersonateattribute is set tofalse Setting this property totrueensures that ASP.NET

runs under the account of the person making the request to the application If the requestor is an

anony-mous user, ASP.NET runs under the IUSR_MachineName account To see this in action, run the example

shown in Listing 21-18, but this time with impersonation turned on (true) Instead of getting a username

ofREUTERS-EVJEN\ASPNETas the user, you get the name of the user who is requesting the page —

REUTERS-EVJEN\Administratorin this example — as shown in Figure 21-13

Figure 21-13

Trang 8

You also have the option of running ASP.NET under a specified account that you declare using the

<identity>element in theweb.configfile:

<identity impersonate="true" userName="MySpecifiedUser" password="MyPassword" />

As shown, you can run the ASP.NET process under an account that you specify through theuserName

andpasswordattributes These values are stored as clear text in theweb.configfile

Look at the rootweb.configfile, and you can see that ASP.NET runs under full trust, meaning that it has some pretty high-level capabilities to run and access resources Here is the setting:

<system.web>

<location allowOverride="true">

<system.web>

<securityPolicy>

<trustLevel name="Full" policyFile="internal"/>

<trustLevel name="High" policyFile="web_hightrust.config"/>

<trustLevel name="Medium" policyFile="web_mediumtrust.config"/>

<trustLevel name="Low" policyFile="web_lowtrust.config"/>

<trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>

</securityPolicy>

<trust level="Full" originUrl=""/>

</system.web>

</location>

</system.web>

Five possible settings exist for the level of trust that you give ASP.NET —Full,High,Medium,Low,

andMinimal The level of trust applied is specified through the<trust>element’slevelattribute

By default, it is set toFull Each one points to a specific configuration file for the policy in which the

level can find its trust level settings TheFullsetting does not include a policy file because it simply

skips all the code access security checks

Securing Through IIS

ASP.NET works in conjunction with IIS; not only can you apply security settings directly in ASP.NET

(through code or configuration files), but you can also apply additional security measures in IIS itself IIS enables you to apply access methods you want by working with users and groups (which were discussed earlier in the chapter), working with restricting IP addresses, file extensions, and more Security through IIS is deserving of a chapter in itself, but the major topics are explored here

IP Address and Domain Name Restrictions

You can work with the restriction of IP addresses and domain names in Windows Server 2003,

Win-dows 2000 Server, or WinWin-dows NT Through IIS 6.0, you can apply specific restrictions based on a single computer’s IP address, a group of computers, or even a specific domain name

Trang 9

settings to every Web application on the server From the menu, choose Properties and select the

Directory Security tab

Click the Edit button in the IP Address and domain name restrictions box and a dialog appears The

resulting dialog enables you to grant or restrict access based on an IP address or domain name These

dialogs are shown in Figure 21-14

Figure 21-14

Figure 21-15

Trang 10

Think twice about restricting based on a domain name It can hinder performance when the reverse DNS lookup is performed on each request to check the domain

You not only can restrict specific IP addresses and domain names, but you can also restrict everyone and just allow specified entities based on the same items Although Figure 21-14 shows restricting a specific

IP address, you can restrict or grant access to an entire subnet as well Figure 21-15 shows how to grant access just to the servers on the 192.168.1.0 subnet (defined by a Linksys router)

Working with File Extensions

You can work with many types of files in ASP.NET These files are defined by their extensions For

example, you know that.aspxis a typical ASP.NET page, and.asmxis an ASP.NET Web service file

extension These files are actually mapped by IIS to the ASP.NET DLL,aspnet_isapi.dll

Figure 21-16

To access the dialog in IIS 6.0 that maps the file extensions, pull up the Properties dialog of your Web

application in IIS or pull up the Default Web Site Properties In a specific Web application, you must

work from the Directory tab; but if you are working with the Default Web Site Properties dialog, you

Ngày đăng: 05/07/2014, 19:20

TỪ KHÓA LIÊN QUAN