怎样提高Windows Azure Cloud Service中的WebRole的文件访问权限

关键字:WebRole

1. 背景

Web应用程序需要读取和写入该项目下的文件的权限。

在默认情况下,W3wp.exe 和WaIISHost.exe的运行账号是Network Service,而Network Service 的对文件的访问权只有读取权限。

image

image

所以要读取和更改web站点下的文件,需要提升IIS对该文件的访问权限,也就是提高Network Service账号的访问该文件的权限。

2. 解决办法

首先我们会想到在ServiceDefinition.cscfg配置文件加上提升权限的配置。如:

<WebRole name="WebRole1" vmsize="Small">
        <Runtime executionContext="elevated"/>

这里提升的是部署WebRole的权限。
但是要知道,不管怎么提升,w3wp这个进程在webrole里面始终以Network Service 来运行,所以这种配置是无效的。
http://technet.microsoft.com/en-us/library/cc771170(v=ws.10).aspx

从上述文档中知道,

如果运行在一个具有很高权限的账号下Application pool会有安全风险的

文章Startup Lifecycle of a Windows Azure Role告诉我们不能在部署Startup task中来更改Network Service的权限,因为这个时候IIS Application Pool 还没有生成。

我们可以更改文件的访问权限,这个是跟IIS配置无关的。也就是上面贴图中network service的权限列表。

1)编写Startup.cmd

set filePath=%RoleRoot%sitesrootApp_Datamycompactdb.sdf

ModifyFileSecurity.exe "%filePath%" "NETWORK SERVICE"

EXIT /B 0

2)编写ModifyFileSecurity

ModifyFileSecurity.exe

class Program

{

static void Main(string[] args)

{

if (args.Length == 2)

{

string fileName = args[0];

string account = args[1];

AddFileSecurity(fileName, account, FileSystemRights.Modify, AccessControlType.Allow);

}

}

public static void AddFileSecurity(string fileName, string account,

FileSystemRights rights, AccessControlType controlType)

{

// Get a FileSecurity object that represents the

// current security settings.

FileSecurity fSecurity = File.GetAccessControl(fileName);

// Add the FileSystemAccessRule to the security settings.

fSecurity.AddAccessRule(new FileSystemAccessRule(account,

rights, controlType));

// Set the new access settings.

File.SetAccessControl(fileName, fSecurity);

}

}

当然我们也可以编写Powershell 命令SET-ACL来辩解访问文件的访问权限

参考:

http://technet.microsoft.com/en-us/library/hh849810.aspx
     http://technet.microsoft.com/en-us/library/ff730951.aspx
     http://blogs.msdn.com/b/johan/archive/2008/10/01/powershell-editing-permissions-on-a-file-or-folder.aspx
     How to update role code in startup task.

原文地址:https://www.cnblogs.com/ericwen/p/3494370.html