Code Monkey home page Code Monkey logo

iis.administration's Introduction

Microsoft IIS Administration API

Documentation is available at https://docs.microsoft.com/en-us/IIS-Administration

Develop and Debug with Visual Studio 2022:

  • Clone this project
  • Load the solution (Microsoft.IIS.Administration.sln) in Visual Studio
  • Try restoring all the NuGet packages
  • Open src\Microsoft.IIS.Administration\config\appsettings.json, modify the users section as below,
"users": {
      "administrators": [
        "mydomain\\myusername",
        "[email protected]",
        "IIS Administration API Owners"
      ],
      "owners": [
        "mydomain\\myusername",
        "[email protected]",
        "IIS Administration API Owners"
      ]
    },
  • Run PowerShell as an Administrator
  • Run Configure-DevEnvironment.ps1 script in the scripts dir
  • From the visual studio run profile menu select option Microsoft.IIS.Administration and run the application.
  • If you are not able to browse the site or your getting generic browser error, most like SSL certificate is not configured for that. IIS express installs SSL certificates on port 44300-44399. Try changing the port to one of these in appsettings.json ex: "urls":"https://*:44326"

Build the Installer:

In the following code, replace the path to match your clone location. It first starts the developer command prompt for Visual Studio 2022, publishes the solution and finally, builds the installer at installer\IISAdministrationBundle\bin\x64\Release.

%comspec% /k "C:\Program Files\Microsoft Visual Studio\2022\Preview\Common7\Tools\VsDevCmd.bat"

cd /d C:\src\repos\IIS.Administration
msbuild -restore Microsoft.IIS.Administration.sln /t:publish

build\nuget.exe restore installer\IISAdministrationSetup\packages.config -SolutionDirectory installer
msbuild installer /p:configuration=release

Installation and Known Issues:

  • Must first remove preview builds of .Net Core. The service does not work with preview builds of .Net Core.
  • Must remove previously installed versions of IIS Administration.
  • Repair does not work. Must do a full uninstall/re-install.
  • If errors occurred during installation, manually remove folder C:\Program Files\IIS Administration and Windows service "Microsoft IIS Administration".
  • If the step above does not fix the installation failure, manually remove user group "IIS Administration API Owners" from the host machine if it exists, and run setup again.
  • If you don't have permissions for the APIs, add yourself to user group "IIS Administration API Owners" on the host machine.
  • If you still don't have permissions after adding yourself to "IIS Administration API Owners", add yourself to users/administrators and users/owners in appsettings.json.
  • If you have trouble viewing the Access Token created from the API Explorer in Microsoft Edge, go to edge://settings/reset and reset your browser's settings.
  • Microsoft.Web.Administration.dll version conflicts with .Net 6.0: Remove all code related to "ms.web.admin.refs" in the future when it is ported to .Net 6.0.
  • Supports 64 bit Windows Server 2008 R2 and above

Nano Server Installation:

There is a blog post to get up and running on Nano Server located at https://blogs.iis.net/adminapi/microsoft-iis-administration-on-nano-server.

Use APIs through API Explorer

JSON request
{
  "name": "Contoso1234",
  "physical_path": "C:\\inetpub\\wwwroot",
  "bindings": [
    {
      "port": 8080,
      "protocol": "http",
      "ip_address": "*"
    }
  ]
}
  • If you don't have permissions to create Web sites under C:\Inetpub, make sure you have files section in appsettings.json like this,
  "cors": {
    "rules": []
  },
  "files": {
    "locations": [
      {
        "alias": "inetpub",
        "path": "C:\\inetpub",
        "claims": [
          "read",
          "write"
        ]
      }
  }
  • Click -->, the new Web site should be created.
  • Open IIS Manager, you should see the newly created Web site under Sites.
  • Back to the browser, click DELETE, then -->. The newly created Web site should be deleted.

Running Tests:

  • Run the ConfigureDevEnvironment script with the test environment flag
   C:\src\repos\IIS.Administration\scripts\Configure-DevEnvironment.ps1 -ConfigureTestEnvironment
  • Open the project in Visual Studio as an Administrator and launch without debugging
  • Make sure the appsettings.json being used is similar to the one at test\appsettings.test.json. Without the "files" section, new Web sites cannot be created. "cors" section is also required.
  • Open another instance of the project (also as Administrator since tests need to create new local users and enable some IIS features) and run the tests located in the 'test' folder
  • Tests can also be run with the CLI

Examples

C#

Intialize Api Client

var apiClient = new HttpClient(new HttpClientHandler() {
   UseDefaultCredentials = true
}, true);

// Set access token for every request
apiClient.DefaultRequestHeaders.Add("Access-Token", "Bearer {token}");

// Request HAL (_links)
apiClient.DefaultRequestHeaders.Add("Accept", "application/hal+json");

Get Web Sites

var res = await apiClient.GetAsync("https://localhost:55539/api/webserver/websites");

if (res.StatusCode != HttpStatusCode.OK) {
  HandleError(res);
  return;
}

JArray sites = JObject.Parse(res.Content.ReadAsStringAsync().Result).Value<JArray>("websites");

Create a Web Site


var newSite = new {
  name = "Contoso",
  physical_path = @"C:\inetpub\wwwroot",
  bindings = new object[] {
    new {
      port = 8080,
      protocol = "http",
      ip_address = "*"
    }
  }
};

res = await apiClient.PostAsync("https://localhost:55539/api/webserver/websites", 
    new StringContent(JsonConvert.SerializeObject(newSite), Encoding.UTF8, "application/json"));

if (res.StatusCode != HttpStatusCode.Created) {
    HandleError(res);
    return;
}

JObject site = JObject.Parse(res.Content.ReadAsStringAsync().Result);

Update a Web Site


var updateObject = new {
  bindings = new object[] {
    new {
      port = 8081,
      protocol = "http",
      ip_address = "*"
    }
  }
};

var updateRequest = new HttpRequestMessage(new HttpMethod("PATCH"),
    "https://localhost:55539" + site["_links"]["self"].Value<string>("href"));

updateRequest.Content = new StringContent(JsonConvert.SerializeObject(updateObject), Encoding.UTF8, "application/json");

res = await apiClient.SendAsync(updateRequest);

if (res.StatusCode != HttpStatusCode.OK) {
    HandleError(res);
    return;
}

site = JObject.Parse(res.Content.ReadAsStringAsync().Result);

Delete a Web Site

res = await apiClient.DeleteAsync("https://localhost:55539" + site["_links"]["self"].Value<string>("href"));

PowerShell

There is a utils.ps1 script that demonstrates how to generate an access token from PowerShell.

# Replace the path to match your clone location
$accessToken = C:\src\repos\IIS.Administration\scripts\utils\utils.ps1 Generate-AccessToken -url "https://localhost:55539"

Get Web Sites

# Supply an access token to run the example

$accessToken = "{Some Access token}"

$headers = @{ "Access-Token" = "Bearer $accessToken"; "Accept" = "application/hal+json" }

$response = Invoke-RestMethod "https://localhost:55539/api/webserver/websites" -UseDefaultCredentials -Headers $headers

$response.websites

iis.administration's People

Contributors

babula38 avatar bariscaglar avatar drago-draganov avatar jhkimnew avatar jimmyca15 avatar ky7m avatar maherjendoubi avatar microsoft-github-policy-service[bot] avatar pope13 avatar radykal-com avatar robgibbens avatar shirhatti avatar tratcher avatar twaalewijn avatar yaqiyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iis.administration's Issues

Support for Web Hosting certificate store

Currently, when working with certificates, the only exposed store is "My" (or "Personal"). This store is not intended and performant enough for web hosting, so WebHosting store was added in Windows 2012.

The store name is hardcoded in CertificateHelper class to be public const StoreName STORE_NAME = StoreName.My;. Please note: the StoreName enum does not contain value for WebHosting store, you have to open the store this way: var store = new X509Store( "WebHosting", StoreLocation.LocalMachine);.

Http Request Tracing freb.xsl support

When downloading request tracing files through the /downloads API, the file will reference freb.xsl. The route /downloads/freb.xsl should redirect to the freb.xsl file for the system to enable retrieval for clients.

Directories may have different IDs

Requesting directories using the ?physical_path={value} filter may result in an inconsistent id value depending on the presence of a trailing '/'

Document access token flow

I'd like to use this with another config managment system. The UI is fine, but I can't find any documentation of how the token flow works or any swagger spec to help me.

Could you please document in detail how to get an access token using a generic http client such as curl or PowerShell's invoke-restmethod/invoke-webrequest?

Setup endpoint

Currently the API does not expose a method to enable IIS features. We could have an api/webserver/setup endpoint or something similar to provide this capability.

windows 7 Write-Error Could not get the state of IIS-HostableWebCore

windows 7 Write-Error Could not get the state of IIS-HostableWebCore

D:\software\iis.administration\setup> .\setup.ps1 Install -Verbose -Port 55555
详细信息: Verifying user is an Administrator
详细信息: Ok
详细信息: Verifying user is an Administrator
详细信息: Ok
Checking installation requirements
详细信息: Verifying IIS is enabled
详细信息: Ok
详细信息: Verifying Windows Authentication is Enabled
详细信息: Ok
详细信息: Verifying URL Authorization is Enabled
详细信息: Ok
详细信息: Verifying IIS-HostableWebCore is Enabled
Rolling back
Finished rolling back.
Write-Error : Could not get the state of IIS-HostableWebCore
所在位置 D:\software\iis.administration\setup\dependencies.ps1:51 字符: 10
+     throw <<<<  "Could not get the state of $_featureName"
所在位置 D:\software\iis.administration\setup\setup.ps1:232 字符: 16
+     Write-Error <<<<  -Exception $_.exception -Message $($_.Exception.Message + [Environment]::NewLine + $_.Invocatio
nInfo.PositionMessage)
    + CategoryInfo          : NotSpecified: (:) [Write-Error], RuntimeException
    + FullyQualifiedErrorId : System.Management.Automation.RuntimeException,Microsoft.PowerShell.Commands.WriteErrorCo
   mmand

No way to require SNI

The API does not expose any way to require SNI (Server Name Indication) in web site binding. Support for this is critical to enable setup with fallback for non-SNI clients.

File Move API can return 500 for directories

When using the move api (/api/files/move) to move a directory it is possible that a 500 may occur. The cause is a race condition between the calculation of the size of the directory and the move operation.

https://github.com/Microsoft/IIS.Administration/blob/master/src/Microsoft.IIS.Administration.Files/Copy/MoveHelper.cs#L168
https://github.com/Microsoft/IIS.Administration/blob/master/src/Microsoft.IIS.Administration.Files/Copy/MoveOperation.cs#L54

Copy is not affected.

Support for CCS in API

The API lacks support for certificates stored in Centralized Certificate Store (basically file system folder), which is supposed to be used in web farms and by web hosting providers.

Log files and auditing are not migrated on upgrade.

The log files that are created during usage of the application are not migrated on upgrade.

Proposed Solution

Move the logs folder to be directly under the installation folder. Ex:
Move
C:\Program Files\IIS Administration\1.0.37\Microsoft.IIS.Administration\logs
to
C:\Program Files\IIS Administration\logs

Server Farm Management

Hi, just wondering if it is possible to alter the status of server farms with the api? If not, is this a planned feature and any time frame for when it would be implemented? Thank you.

Error 0x800f0922 during setup on Nano Server

This error may occur when attempting to install Microsoft IIS Administration on Nano Server. This issue is caused by unlocking sections in the applicationHost.config file and then attempting to use DISM to install IIS optional features. Installing .NET Core on Nano Server requires unlocking the handlers section of the applicationHost.config. Therefore if .NET Core is installed before trying to enable windows authentication, this error will be encountered.

Avoiding

To avoid this error, enable all desired IIS optional features before making any modifications to the applicationHost.config file.

# Enable IIS Administration dependencies
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-WindowsAuthentication"
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-URLAuthorization"
# Optionally, take the chance to enable all IIS features
# Get-WindowsOptionalFeature -Online | where {$_.FeatureName -match "IIS-" -and $_.State -eq [Microsoft.Dism.Commands.FeatureState]::Disabled} | % {Enable-WindowsOptionalFeature -Online -FeatureName $_.FeatureName}

Workaround

A known work around for this error is to reset the override mode of the sections that have been unlocked. For example, if .NET Core and the ASP.NET Core Module has been installed, then the handlers section would have been unlocked. Reset it with the following PowerShell commands.

# Reset to default handlers settings
Import-module iisadministration 
Reset-IISServerManager -confirm:$false 
$sm = Get-IISServerManager 
$appHostconfig = $sm.GetApplicationHostConfiguration() 
$section = $appHostconfig.GetSection("system.webServer/handlers") 
$section.OverrideMode="Inherit" 
$sm.CommitChanges()

Using own (custom UI)

Because of enterprise security policy we are not allowed to do setup in the way it is described on "Using the new API" section. navigating to manage.iis.net is not option for us so we decided to create sort of Octopus tentacle on which will be deployed on server in order to use it and create centralized dashboard for servers. is there any way how we can obtain tokens so that our internal application is able to go to machines and use API?
Install administration API on server.
install tentacle on server.
Obtain access token from tentacle simple screen.

Navigate to http://our-dashboard.local
Click Add machine
Enter the Access Key obtained from tentacle installation on server.
Machine is added to the dashboard.

The allowDefinition attribute is not handled.

Sections in the applicationHost.config have the capability to restrict where they can be defined. A notable example is the Http Compression section which by default only allows the section to be defined in the applicationHost.config file.

Currently the API has no method to expose this data or to manipulate it.

Certificate API should show subject in default reference view

Subject is one of the most important properties of a certificate and is currently only accessible in the full representation of the certificate or by using the "fields" query parameter. This member should be present in the default reference representation.

Renaming of Application Pools leaves orphaned Web Apps

Updating the name of an application pool results in orphaned applications. When an application pool's name is updated the application's that explicitly reference that application pool should be updated to use the newly named pool. If the application pool is the default application pool, the default application pool setting should be updated. Application's that are assigned to the application pool through inheritance of the default setting should not be updated.

Change Port

Hi, i want to change localhost:55539 port to 8081 but not working

  1. change setup.config; 55539
  2. change applicationHost.config
  3. Restart Windows Service.

Installation fails on Nano Server GA

Add-Type : (8) : The type or namespace name 'X509Certificates' does not exist in the namespace 'System.Security.Cryptography' (are you missing an assembly reference?)
(7) : using System.Runtime.InteropServices;
(8) : >>> using System.Security.Cryptography.X509Certificates;
(9) : using System.Text;
At C:\IIS.Administration\setup\netsh.ps1:129 char:9

  • Add-Type $cs
  • CategoryInfo : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception
  • FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Platform Version


Win32NT 10.0.14393.0

Get-Command 'dotnet'
CommandType Name Version Source


Application dotnet.exe 1.0.1.4500 C:\dotnet\dotnet.exe

dotnet
Microsoft .NET Core Shared Framework Host
Version : 1.0.1
Build : cee57bf6c981237d80aa1631cfe83cb9ba329f12
Pierre - 5 hours ago

Expose numerical site ID trough the API

Currently there is no way how to get the numerical site ID used by the rest of IIS administration tools. I think the API should expose this information in addition to your internal string ID, because it's basically the only way how to reliably correlate sites across different administration tools/APIs.

HttpClient example authentication

The README.md gives this example for using HttpClient:
var apiClient = new HttpClient();
but after a clean install of the tool, that did not work (401 Unauthorized). I had to change it to:

var httpClientHandler = new HttpClientHandler()
    {
        Credentials = new NetworkCredential(userName, password, domain)
    };
var apiClient = new HttpClient(httpClientHandler);

Should the README be updated to include that, or instructions on changing the authentication mechanism, or am I doing something wrong?

Setup script does not rollback creation of setup.config

The install.ps1 script does not rollback the creation of the setup.config file. If the script fails after creating the setup file, subsequent calls to install will fail thinking that an installation exists.

Work around

Manually delete the setup.config file in "C:\Program Files\IIS Administration" if installation fails.

Solution

Remove setup.config file in the rollback procedure of the install script.

How do you automate installation of IIS Administration

I can see that to install IIS Administration manual step of installing MSI for .NET core plus actual executable for IIS Administration shall be run in manual fashion. How to properly automate it to put inside docker container?

Audit and Log File max files

Currently there is no way to configure a max file limit for log and audit files. This should be configurable in the appsettings.json file.

Feature Request: File System Endpoint

This API pretty much covers everything one needs to manage IIS without having to RDP into the server (Certs, IIS Functions, etc.)! Love it!

But one glaring omission is managing the file system (creating a folder to store an IIS site files or an application. We still need to remotely access the server either through RDP or UNC to do this. It would be awesome if there was a third forth endpoint for file system CRUD operations.

If the API had that functionality one could fully manage IIS servers through this interface.

Add ability to install/uninstall IIS optional features

In 1.0.39 and below the API returns 404 for endpoints that use an IIS feature that is not installed. There is no way to install the feature through the API to start using the endpoint. The API should provide the capability to install all of the IIS optional features that come with the OS. A new installation of the API should be capability of enabling all of the IIS functionality the API exposes for management.

Proposal

Features that are uninstalled will continue to return a 404 with a FeatureNotInstalled error object.

Install

Sending a POST request to the feature's endpoint without the {id} parameter will create the resource on the server by installing the feature.

Uninstall

Uninstall will be handled by sending a DELETE request to the feature's endpoint without the {id} parameter.

Update to 1.0.1

Hi @jimmyca15,

Is it possible to update the project to 1.0.1?
I suggest this pull request #10
Is there a problem with my pull request?

Thanks

Few questions on Security

  1. Is there a way we can change the binding information (ip/port/cert) for the API itself? If so how is that done?
  2. How does one customize the security? It looks like the API requires both Access Tokens and Windows IDs. Why the extra access tokens if protected with Windows Auth?
  3. Not necessarily a security question. But how often will this be updated? Trying to figure out how to keep this up-to-date on many servers in a consistent way.

Getting HTTP Error 502.5 - Process Failure when trying to get AccessToken

Hi,

As an experiment i'm trying to run the Administration API in a NanoServer Docker Container. I got through the setup process and the API seems to be running. When I try to connect via https://manage.iis.net/connect and I enter my container ip address, and request an access token i'm able to enter my credentials but then i get the following error:

image

So i'm guessing the API is accepting my credentials and then goes into error, i see there are Serilog dll's so maybe something is logged? I'm wondering where I can find these logs, or if anybody has an idea what's going on.

KR

Error starting service "Microsoft IIS Administration"

Hello,

I'm trying to install the administration tools on a Nano server and I'm getting this error message :

error

The error occurs when the install script tries to start the newly created "Microsoft IIS Administration" service. Any advice ?

Thanks in advance !

Installation Issues

So I'm trying to check this out, I'm using a fresh 2012 R2 machine.

I first installed the prerequisites:

dism.exe /online /enable-feature /featurename:IIS-WindowsAuthentication /all 
dism.exe /online /enable-feature /featurename:IIS-HostableWebCore /all
.\DotNetCore.1.0.0-WindowsHosting.exe /install /quiet

and dotnet core seems to work.

I downloaded a zip of the repository and extracted it into C:\inetpub

running:

  C:\inetpub\IIS.Administration\scripts\publish\publish.ps1

complains about a missing parameter -outputPath as the script is not documented I don't know what that means, so I provide just an empty folder.

The scripts breaks at line 173: "Could not build plugins for publishing", the dotnet publish command fails in Microsoft.DotNet.Tools.Publish.PublishCommand.TryPrepareForPublish(): System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Also the output directory IIS.Administration\src\Microsoft.IIS.Administration\plugins does not exist, but maybe dotnet.exe creates that if it would work.

At this point I stopped.

Also the publish.ps1 script has a URL:

http://gitlab/jimmyca/Microsoft.IIS.Administration.Host/repository/archive.zip?ref=master

that's an internal resource that surely will not work for me.

Enabling Central Certificate Store may hang due to system restart required

Problem

Certain conditions can cause the system to need to restart after enabling the Central Certificate Store (CCS). This will cause the request to enable CCS to hang indefinitely.

Effects

v1.1.0

Diagnosing

If the API is hanging when enabling CCS, look for a child process named DismHost.exe in the system's process list. This is the installation process that is hanging while waiting for user input.

Working Around

The DismHost.exe process will continue to hang until the process is killed. Make sure the DismHost.exe process is a child of the Microsoft IIS Administration process before killing it.

The following command can be run from the command prompt to verify that the machine needs a restart to enable CCS.
Dism.exe /Online /Enable-Feature /FeatureName:IIS-CertProvider

Finally, restart the machine.

WebServer.Files API returns 403 when child is forbidden

When enumerating a directory with the WebFiles API (/api/webserver/files?parent.id={id}) it is possible to get a 403 error due to a child virtual directory having a path that is not allowed. This behavior differs from the Core Files API (/api/files?parent.id={id}) where enumerating a directory that has read access will never respond with a 403 error.

Proposal

When enumerating a directory with the webfiles API and the path of a child is not allowed, that child webfile resource will have a NULL file_info field. The API will not return 403 until that child is specifically requested (/api/webserver/files/{id})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.