IIS вне домена и аутентификация при помощи клиентского сертификата: yu_xuan — LiveJournal

Client certificate

The last certificate we need is the client certificate. Since we already have a root certificate, let’s derive the client certificate from it as well:

Configure iis

First of all, you need to configure IIS to allow client certificate mapping authentication. As you can see in the screenshot below, there are two types of these. We need the IIS Client Certificate Mapping Authentication feature.

Configure iis to use your self signed certificates with your application including iis client certificate mapping authentication – blog.

I’m now assuming that you read my previous post about how to create self signed certificates for development and it might’ve left you thinking “Yay great! ….But how do I actually use them?”. This blog post will take you step by step through the manual process of configuring IIS on your PC or Windows Server to use your self signed certificates together with IIS client certificate mapping authentication.

Please note that I in my examples I use my localhost hosting and a random domain name but you can do this on your real server’s IIS if you have a static IP address from your internet service provider or your domain hosting company as well as configured your firewall, router etc. correctly where finally you can point your domain name to your that address. BUT I won’t recommend either together with self signed certificates unless your clients/users are willing to receive and install your self-signed root and client certificate. A good example of this is in a closed intranet where you have access to all the end-user’s computers because then you can install the certificates on their machines, which is necessary if you don’t want your users to get a big fat warning about trust issues with your self signed server certificate. If you are looking for a commercial production-worthy solution you should purchase your certificates instead of self signing. So now we have that out of the way I’m using a PC with Windows 8.1 Pro, IIS 8.5 and Visual Studio Premium 2022. (I’ve also tested with a Windows Server 2022 R2 Hyper-V VM on my PC).

Installing IIS
If you haven’t already installed IIS on the machine that will act as the hosting server, please do so by pressing the Windows button for a PC and search “Turn Windows features on or off” (or go to Control Panel and search). Check Internet Information Services and the following childnodes. 1 complete IIS install
(If you are running on .NET 3.5 you need to check the .NET Extensibility 3.5 and ASP.NET 3.5)

For Windows Server 2022 go to the Server Manager Dashboard Click add roles and features Choose role-based or feature-based installation and go next Select the server Enable the server role called Web Server (IIS) and following child elements Server IIS

Also make sure Application Development is checked with the following childnodes Server IIS application dev

Click OK and let Windows install.

Creating our sample project
For the sake of this demo we’ll create a really simple mini application that we will be hosting in the local IIS. (You can also just fork mine directly at Github)

In Visual Studio, create a new empty web application and reference web api 5 New Project

We’ll just need a reeeeaally simple controller:

using System.Web.Http;

namespace IISWithCertificatesSample.WebApi.Controllers
    public class CatsController : ApiController
        public IHttpActionResult Get()
            return Ok("A lot of cats meowing for food");

You should now be able to run both routes (F5) and surf to the localhost url with /api/cats (mine looks like http://localhost:62172/api/cats). Awesome, lets host this application using our local IIS.

NOTE: We will no longer be running the application directly from Visual Studio (F5) which is set to use IIS Express.

Configuring IIS
Open your IIS Manager (Windows button search for it). Add a new website and application pool with our sample application. (Right-click Sites Add Website) The path needs to be the folder where your web site documents are located, so if you have published your website point the path there. I’m just going to use the direct path to the project in Visual Studio for this very simple example.

Now let’s locally host this site by specifying the host name AKA. your domain name. 7 yourdomain.com

Since I’m just hosting locally I need to add the site to my local hosts file in order to bind my localhost IP address with the host name. This is done by running notepad as administrator and opening the hosts file in the path: %systemroot%System32driversetchosts file

Похожее:  Европейский пенсионный фонд личный кабинет: как войти и использовать сервис

Adding the following at the end: yourdomain.com www.yourdomain.com 8 hosts file

Now whenever I surf to yourdomain.com and www.yourdomain.com on my machine it will resolve the site with my newly added bindings to the IP address (which is localhost’s IP).

Let’s add the www. binding to your site in the IIS Manager as well 9 IIS bindings10 add http binding11 domain with www12 both http added

Surf to the domain name you set up in the bindings with or without www. and add the ending /api/cats and you should get the meowing cats. (If not try emptying the cache)

IMPORTANT: This is ONLY going to happen on the local machine because we altered the hosts file to redirect our requests of the domain name we added to the localhost IP address. It is meant for development and to be able to test your changes before deploying them to your real web hosting server.

Securing the server with SSL
Now we want to secure the cats by adding a SSL certificate to our Server.
In your IIS Manager go to your server (The top of the tree to the left) ➜ Scroll down and double-click Server Certificates. 13 IIS Server

(If your self signed certificate is already here, jump ahead to the bindings steps)

We need to import our self signed server certificate in order to enable https communication with SSL, so click Import… 14 Import server cert

Click the … and find your .pfx file, fill out the password (the -po parameter in your command batch file) and click OK 15 browse server cert

Your certificate is now added 16 cert added

Double-click the newly added cert to verify that it is trusted (Your self signed certificates were added to the correct stores in my previous post, so again: read it if you are lost right now ;-))

17 trusted server cert

So far, so good! Now we can add the https binding, the same way as before but choose https with port 443, your domain as the host name and find your self signed certificate in the drop down list

18 bindings add ssl

Check the Server Name Indication box which enables our server to have multiple certificates installed on the same IP address by sending the hostname with the first stage of the SSL handshake. Repeat the same steps to add SSL for www.yourdomain.com but with a certificate where the CN name matches the domain name or a wildcard certificate
19 https www with wildcard

Our bindings are complete for now

19 All bindings

Tadaa, you can now use https://yourdomain.com/api/cats and https://www.yourdomain.com/api/cats

NOTE: Firefox doesn’t use the Windows certificate store, so you will have to add your root CA manually. Go to Firefox Settings Options Advanced View Certificates Authorities import your CARoot.cer file

IIS Client Certificate Mapping Authentication
We have now been through the uses of the root and server certificates and you are probably wondering what to do with the client certificate we also created in my previous post. This is for situations when we for example need to authenticate clients without a user login and password approach but rather want the server to ask the client to show it’s certificate and if it’s the correct one the client is allowed in. This can be done with a Many-To-One or a One-To-One mapping and I will show you how to do both manually in the IIS Manager.

First we need to install the feature, so bring up the “Turn Windows features on or off” again and install the following 20 IIS client cert mapping

We’ll tell our server to require a SSL certificate from the client 21 SSL Settings22 apply require ssl

Then we need to configure the server to know which client certificate it needs to validate, so go to the Configuration Editor and choose the iisClientCertificateMappingAuthentication section (you can also enter the path system.webServer/security/authentication/iisClientCertificateMappingAuthentication into the Section field) 24 iisClientCertMapAuth section

Many-To-One Mappings
If you want to map multiple client certificate to a single user this approach is what you need. You can also share client certificates like this by installing the client certificate (and the CA Root, since we are self-signing certificate) on other users on whichever machine to gain access as long as the client certificate matches the rule criterias of the mapping. It would for example be useful in a situation where you would want all users in an organization to gain access through a single user mapping.

Enable the client certificate mapping authentication 25 enable client auth

To add a mapping click the … of the manyToOneMappings 26 add mapping

Похожее:  Сетевая авторизация временно недоступна – Origin не входит в сеть в Windows, что делать, если не работает Ориджин

Here you add the users that you want to grant access.27 add new mapping

Fill out the properties for a mapping and repeat for each user you want to configure for access or denial. Remember that you need the client certificate and root CA certificate installed on all the user’s mmc.
28 manytoone mapping

IMPORTANT: In order for this to work you need to enter a valid username and password and since my computer is the server, the credentials will be my Windows username and password.

Now we need to create some rules to go with this mapping so the server can determine if a client is allowed in or not. It’s a  so click on the rules property and the … button

29 add rule

I will add one rule as an example where the server will check the client certificate to see if it’s signed by the correct CA root. Go ahead and add more rules for more safety, please visit the IIS Many-To-One Mapping reference for more documentation.
31 rule

Remember to apply the changes in the IIS Manager, so close the rules and mappings windows and click Apply 32 apply changes

Open a new incognito browser window to make sure to start from a clean slate cache and cookie-wise and enter your url with the /api/cats and see the browser prompting you for a certificate. Choose the ClientCert and click ok to gain access to the cats. 33 ok client cert

If this is not working make sure that your client certificate is in your CurrentUser/Personal store as well as in your browser’s certificate store. If yes, then go to Control Panel Internet Options Content and click Clear SSL state. 34 clear ssl state

Open a new incognito windows and try again, your browser should now prompt you for the client certificate.

NOTE: Remember as I explained earlier on, Firefox has it’s own certificate store so you need to import the client certificate into “Your Certificates” in order to use this.

One-To-One Mappings
Let’s walk through the one-to-one mappings as well. This approach means that we need an individual client certificate for each user mapping. You can either disable the many-to-one mapping and use the same certificate and user or create new ones. Go back to the Configuration Editor and open the iisClientCertificateMappingAuthentication section again. Click the … of the oneToOneMappings. 35 enable one to one mappings

To add the mapping to the certificate we need to export the public key of the client certificate file. You can export this from your Machine Management Console (press the Windows button and search for mmc) Snap-in the Local Machine’s Certificate’s personal store and export the client ssl certificate you want to use without the private key in the base64 format. Export client certWithoug private keybase64 export

Right-click the newly exported certificate and open with notepad. Remove all the line-breaks in the certificate itself. Remove linebreaks

Now copy that into the certificate property field of the mapping and fill out the rest 38 add user mapping

IMPORTANT: In order for this to work you need to enter a valid username and password and since my computer is the server, the credentials will be a Windows username and password.

Again, remember to apply the changes. 39 apply changes

And there you go, try it out and when prompted choose the certificate you mapped to the user you just mapped.

I hope you found this post useful and for my next post I will be going through how to use self signed certificates together with Windows Azure and how to configure the IIS by C# code, take a look at it here: http://vhod-v-lichnyj-kabinet.ru/2022/04/21/configure-a-windows-azure-cloud-service-to-use-your-self-signed-certificates-for-iis-client-certificate-mapping-authentication/

Have a good one =)

Iis вне домена и аутентификация при помощи клиентского сертификата

Мне необходимо настроить аутентификацию при помощи клиентских сертификатов между несколькими недоменными серверами, которые обращаются друг к другу по HTTPS.

Основные требования:

  • Разрешать подключаться только по сертификатам, выданным определенным CA (поле issuer).
  • Проверять кому выдан сертификат (поле subject) нет необходимости, поскольку выдается сертификат на этом CA строго ограниченному кругу лиц/серверов.
  • Все настройки производить через командную строку (для последующего запихивания команд в скрипт).

Для аутентификации без домена существует два варианта маппинга сертификатов: One-to-One и Many-to-One:

  • При использовании маппинга One-to-One, создается жесткое соответствие между клиентским сертификатом и учетной записью на сервере, при этом сервер использует копию каждого клиентского сертификата для проверки того, что ему предоставляет при аутентификации клиент. 
  • Many-to-One использует одну учетную запись на сервере и не нуждается в копиях клиентских сертификатов. Вместо этого используются правила проверки на соответствие полей subject и/или issuer, предоставляемого клиентом сертификата.

В моем случае удобнее использовать Many-to-One.

Похожее:  Аутентификация - Безопасность - Полное руководство по Yii 2.0 на русском

Итак, для настройки необходимо проделать следующие действия:

1. Устанавливаем роль IIS под названием ‘IISCertificateMappingAuthentication’

cmd /c start /w pkgmgr.exe /iu:IIS-IISCertificateMappingAuthentication

2. Включаем для сайта required client certificate

%systemroot%system32inetsrvappcmd.exe set config 'Site Name' /section:system.webServer/security/access /sslFlags:"Ssl, SslNegotiateCert, SslRequireCert" /commit:apphost

Site Name‘ – здесь и в следующих командах, имя сайта, для которого включаем настройку

3. Включаем для сайта аутентификацию IIS certificate mapping

%systemroot%system32inetsrvappcmd.exe set config 'Site Name'
/section:system.webServer/security/authentication/iisClientCertificateMappingAuthentication /enabled:true /oneToOneCertificateMappingsEnabled:false /commit:apphost

4. Включаем для сайта Many-to-One mapping

%systemroot%system32inetsrvappcmd.exe set config 'Site Name' /section:system.webServer/security/authentication/iisClientCertificateMappingAuthentication / "manyToOneMappings.[name='Name of the mapping',enabled='true',permissionMode='Allow',userName='username',password='password',description='Description']" /commit:apphost

name – логическое имя маппинга, которое будет использоваться дальше для добавления (или удаления) правил
userName – имя учетной записи на сервере, к которой прикручиваем сертификаты
password – пароль учетной записи (в конфиге он хранится в зашифрованном виде)
description – какое-то понятное мне описание

5. Добавляем правило, по которому будет проверяться сертификат

%systemroot%system32inetsrvappcmd.exe set config 'Site Name' /section:system.webServer/security/authentication/iisClientCertificateMappingAuthentication / "manyToOneMappings.[name='Name of the mapping'].rules.[certificateField='Issuer',certificateSubField='CN',matchCriteria='name of the CA',compareCaseSensitive='true']" /commit:apphost

certificateField – поле, которое будем проверять (как уже говорил выше, можно проверять либо subject, либо issuer)
certificateSubField – дочернее поле, которое будем проверять (мне достаточно поглядеть на CN)
matchCriteria – шаблон, по которому будет производиться проверка (может в себе содержать * или ?)
compareCaseSensitive – чувствительность к регистру


These are the prerequisites needed for this walkthrough.  I won’t be covering how to create or do these things.

Self-signed root certificate

To generate the root certificate, use the following command line:

makecert -r -pe -n "CN=WebSSLTestRoot"
         -b 12/22/2022 -e 12/23/2022
         -ss root -sr localmachine -len 2048

The makecert command has a lot of options, some of which we use here:

The result is a trusted root certificate as you can see in the screenshot below.

Step 1: getting the certificate blob

The oneToOneMappings collection item has an attribute called certificate.  The required value for this attribute is not the certificate has but the actual certificate blob.  Here’s how you extract it.

  1. Right click on your .cer file.
  2. Select Open With…  in the context menu
  3. Select Notepad from the list of Other Programs and click OK. [Note: Notepad may be hidden beneath a drop down in the Vista/Windows 2008 list view]
  4. This is what should be displayed in notepad:







    34q2qQgHa7ao11TcQMDYlJMrqET05MWFY1/Vso leujLoIGTfdHOuz4IBVoeUE y


    tdUn732GQOqYf4wY8jOD2zUJDUG4HXm6ib8ajwIDAQABo4IB TCCAfUwDgYDVR0P





    MBaAFMxzlGbmkp2 phhDg7TPfi83d7UVMHMGA1UdHwRsMGowaKBmoGSGL2h0dHA6








    Zh hJzIPA5pQLbccx4vjWB4cWEYxzcoKYCuUdZrfPFXO1a5kQAj8IZ0/6bhMceyR


    dRqa8DEC74CQN4rQuz395ECm M/hQnN dHOygV8n9swd0bdNq8qypwfVUes5HIpj

    LFmKTuGyFSVj7jv 64oTxvxtYX2QFp9q6Bi qj0uyrX8Xjxy5rPSVPEfnxPCBg58



  6. Format the certificate blob to be a single line.
  7. Save this file as clientCertBlob.txt

Настройка vpn и 802.11x wirelless

В обоих случаях (VPN и беспроводных сетей) вам потребуется использовать RADIUS для аутентификации пользователей. В Windows Server 2008 R2 есть свой RADIUS сервер, реализованный в службе Network Policy Server (NPS). После того, как роль NPS установлена, вам необходимо авторизовать сервер в Active Directory (если NPS установлен на рядовом сервере).

Далее, вам нужно настроить клиенты RADIUS (точки доступа, серверы VPN). После того, как клиенты настроены и сконфигурированы, можно настраивать политики доступа к беспроводным сетям и/или VPN. Вот пример, как настраивается NPS для беспроводных сетей:

Установка и настройка веб-сервера iis

Во-первых, нам нужно установить роль IIS (если он ещё не установлен) — Installing IIS 7.5 on Windows Server 2008 R2. По умолчанию IIS не поддерживает клиентскую аутентификацию по сертификатам, поэтому эту поддержку нужно добавить:

  1. В Server Manager выберите установленную роль Web Server (IIS).
  2. В меню Actions выберите Add Role Services.
  3. В списке компонентов промотайте до раздела Security и в нём установите чек-боксы напротив: Client Certificate Mapping Authentication и IIS Client Certificate Mapping Authentication.
  4. В диалоговом окне нажмите Next –> Install.

Когда эти компоненты установлены, запустите Internet Information Services Manager. Выделите корневой узел вашего веб-сервера и в средней панели выберите Authentication. Найдите в списке Active Directory Client Certificate Authentication и убедитесь, что он Enabled.

Следующим этапом следует выбрать веб-сайт, который будет использовать аутентификацию пользователей по сертификатам и настроить для него SSL. Если у вас уже есть серверный сертификат, можете сразу приступать к настройке биндинга. Если нету, можете использовать эту статью для запроса сертификата с корпоративного CA — Web server certificate enrollment with SAN extension.

Биндинг настраиваетя следующим образом:


These are the Code Snippets to perform walkthrough steps 2 and 3.  All of this was generated using Configuration Editor’s Script Generation.

AppCmd specific instructions

C# Code:

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *