Системная ошибка 5 Отказано в доступе — как исправить?

При выполнении команд net user, net stop, net start и других в командной строке Windows 11 или Windows 10 вы можете получить сообщение: «Системная ошибка 5. Отказано в доступе». Начинающему пользователю не всегда ясно, чем вызвана ошибка и как решить проблему.
В этой инструкции подробно о том, почему возникает системная ошибка 5 при запуске и остановке служб или работе с учетными записями пользователе в командной строке.
Методы решения для «Системная ошибка 5. Отказано в доступе» при выполнении команд net stop, net start, net user

Причина того, что в результате выполнения команд сообщается о системной ошибке 5 «Отказано в доступе» в том, что командная строка (Терминал Windows или Windows PowerShell) запущен не от имени администратора. Или, в некоторых случаях — в том, что ваш пользователь и вовсе не имеет прав администратора на компьютере.
В первом случае решение будет простым: запустите командную строку от имени Администратора, для этого вы можете:
- Начать набирать «Командная строка» в поиске на панели задач Windows 11 или Windows 10, а затем в результатах поиска нажать «Запуск от имени Администратора».

- Нажать правой кнопкой мыши по кнопке «Пуск» и выбрать «Терминал Windows (Администратор)» или «Windows PowerShell (Администратор)»

- Использовать инструкции Как запустить командную строку от имени Администратора в Windows 11 и Как запустить командную строку от имени Администратора в Windows 10.
Ошибка не будет появляться после того, как вы запустите командную строку с соответствующими правами.
А вдруг и это будет интересно:
- Лучшие бесплатные программы для Windows
- Не удалось запустить службу Windows Audio на Локальный компьютер — как исправить?
- Ошибка DXGI ERROR DEVICE HUNG — как исправить?
- Как сбросить Windows на заводские настройки в командной строке
- Как создать отчет о работе Wi-Fi сети в Windows 11 и 10
- Устройство tap0901 — что это и как установить драйвер?
- Windows 11
- Windows 10
- Android
- Загрузочная флешка
- Лечение вирусов
- Восстановление данных
- Установка с флешки
- Настройка роутера
- Всё про Windows
- В контакте
- Одноклассники
-
Николай 17.01.2023 в 09:22
- Heretik 11.04.2023 в 10:13
«Access Denied» or other errors when you access or work with files and folders in Windows
Windows 8 Enterprise Windows 8 Pro Windows 8 Windows 7 Enterprise Windows 7 Professional Windows 7 Ultimate Windows 7 Home Premium Windows 7 Home Basic Windows 7 Starter Windows Vista Enterprise Windows Vista Ultimate Windows Vista Business Windows Vista Home Premium Windows Vista Home Basic Windows Vista Starter Microsoft Windows XP Professional Microsoft Windows XP Home Edition Microsoft Windows XP Starter Edition More. Less
Summary
When you try to access or work with files and folders in Windows, you experience one or more of the following issues:
- Issue 1: You receive an «Access Denied» error message or a similar message.
- Issue 2: You cannot access, change, save, or delete files and folders.
- Issue 3: You cannot open a file or folder after you install a new version of Windows.
Resolution
To resolve a particular issue, follow the steps for the issue that best describes your situation. Use the method for your version of Windows.
Note You may not always receive an “Access Denied” error message for these kinds of issues. If particular steps do not resolve the issue, try a different set of steps.
Issue 1: I receive an «Access Denied» error message when I try to access or work with files and folders
Cause An «Access Denied» error message can occur for one or more of the following reasons:
- The folder ownership has changed.
- You do not have the appropriate permissions.
- The file is encrypted.
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 8 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files or folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or folder, follow these steps:
- Press and hold the folder that you want to take ownership of, then tap Properties. (If you are using a mouse, right-click the folder, and then click Properties.)
- Tap or click the Security tab, tap or click Advanced, then tap or click Change. If you are prompted for an administrator password or for confirmation, type the password or provide confirmation.
- Type the name of the person that you want to give ownership to, and then click Check Names. Note The account name for the person that you are assigning ownership to is displayed.
- Click OK.
- If you want this person to be the owner of the files and subfolders that are contained in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You may not have the appropriate permissions Issues that you experience when you try to access files and folders may be related to permissions. Permissions are rules that determine whether you can access or change files and folders. To check permissions on a file or folder, follow these steps:
- Press and hold or right-click the file or folder, and then click Properties.
- Tap or click the Security tab.
- Under Group or user names, tap or click your name to see the permissions that you have.
To open a file, you have to have the Read permission. To change the permissions of a file or folder, follow these steps.
Important You must be logged on as an administrator to change permissions on files and folders.
- Press and hold or right-click the file or folder, and then tap or click Properties.
- Tap or click the Security tab.
- Under Group or user names, tap or click your name to see the permissions that you have.
- Tap or click Edit, tap or click your name, select the check boxes for the permissions that you must have, and then click OK.
The file or folder may be encrypted Encryption can help protect files and folders from unwanted access. You cannot open an encrypted file or folder without the certificate that was used to encrypt it. To determine whether a file or folder is encrypted, follow these steps:
- Press and hold or right-click the file or folder, and then tap or click Properties.
- Tap or click the General tab, and then tap or click Advanced.
If the Encrypt contents to secure data check box is selected, you have to have the certificate that was used to encrypt the file or folder to be able to open it. In this situation, you should obtain the certificate from the person who created or encrypted the file or folder, or have that person decrypt the file or folder.
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 7 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files or folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or a folder, follow these steps:
- Right-click the folder that you want to take ownership of, then click Properties.
- Click the Security tab, click Advanced, then click the Owner tab.
- Click Edit. Note If you are prompted for an administrator password or for confirmation, type the password or provide confirmation.
- Click the name of the person that you want to give ownership to.
- If you want this person to be the owner of files and subfolders in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You may not have the appropriate permissions Issues that you experience when you try to access files and folders may be related to permissions. Permissions are rules that determine whether you can access or change files and folders. To determine the permissions of the file or folder, follow these steps:
- Right-click the file or folder, then click Properties.
- Click the Security tab.
- Under Group or user names, click your name to see the permissions that you have.
To open a file, you have to have the Read permission. To change permissions on a file or folder, follow these steps.
Important You must be logged on as an administrator to change permissions on files and folders.
- Right-click the file or folder, and then click Properties.
- Click the Security tab.
- Under Group or user names, click your name to see the permissions that you have.
- Click Edit, click your name, select the check boxes for the permissions that you must have, and then click OK.
For more information about permissions, see What are permissions?.
The file or folder may be encrypted Encryption can help protect files and folders from unwanted access. You cannot open an encrypted file or folder without the certificate that was used to encrypt it. To determine whether a file or folder is encrypted, follow these steps:
- Right-click the file or folder, and then click Properties.
- Click the General tab, then click Advanced.
If the Encrypt contents to secure data check box is selected, you have to have the certificate that was used to encrypt the file or folder to be able to open it.
You should obtain the certificate from the person who created or encrypted the file or folder, or have that person decrypt the file or folder.
Issue 2: I cannot access, change, save, or delete files and folders
Cause A problem that prevents you from accessing or working with files and folders can occur for one or more of the following reasons:
- The folder ownership has changed
- You do not have the appropriate permissions
- The file is encrypted
- The file is corrupted
- The user profile is corrupted
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 8 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files or folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or folder, follow these steps:
- Press and hold the folder that you want to take ownership of, then tap Properties. (If you are using a mouse, right-click the folder, and then click Properties.)
- Tap or click the Security tab, tap or click Advanced, then tap or click Change. If you are prompted for an administrator password or for confirmation, type the password or provide confirmation.
- Type the name of the person that you want to give ownership to, and then click Check Names. Note The account name for the person that you are assigning ownership to is displayed.
- Click OK.
- If you want this person to be the owner of the files and subfolders that are contained in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You may not have the appropriate permissions Issues that you experience when you try to access files and folders may be related to permissions. Permissions are rules that determine whether you can access or change files and folders. To check permissions on a file or a folder, follow these steps:
- Press and hold or right-click the file or folder, and then click Properties.
- Tap or click the Security tab.
- Under Group or user names, tap or click your name to see the permissions that you have.
To open a file, you have to have the Read permission. To change the permissions of a file or folder, follow these steps.
Important You must be logged on as an administrator to change permissions on files and folders.
- Press and hold or right-click the file or folder, and then tap or click Properties.
- Tap or click the Security tab.
- Under Group or user names, tap or click your name to see the permissions that you have.
- Tap or click Edit, tap or click your name, select the check boxes for the permissions that you must have, and then click OK.
For more information about permissions, see What are permissions?.
The file or folder may be encrypted Encryption can help protect files and folders from unwanted access. You cannot open an encrypted file or folder without the certificate that was used to encrypt it. To determine whether a file or folder is encrypted, follow these steps:
- Press and hold or right-click the file or folder, and then tap or click Properties.
- Tap or click the General tab, and then tap or click Advanced.
If the Encrypt contents to secure data check box is selected, you have to have the certificate that was used to encrypt the file or folder to be able to open it. In this situation, you should obtain the certificate from the person who created or encrypted the file or folder, or have that person decrypt the file or folder.
The file or folder may be corrupted Files can become corrupted for several reasons. The most common reason is that you have a file open when your computer crashes or loses power. Most corrupted files cannot be repaired. In this situation, you should either delete the file or restore the file from a backup copy.
For more information about corrupted files and how to fix them, see Corrupted files: frequently asked questions.
Your local user profile may be corrupted Occasionally, Windows might not read your local user profile correctly. This may prevent you from accessing files and folders. In this situation, you may have to use a new local user profile. To create the profile, you must first create a local user account. When the new account is created, the profile is also created. To create a local user account, follow these steps:
- Swipe from the right edge of the screen, tap Settings, and then tap Change PC settings. (If you are using a mouse, point to the upper-right corner of the screen, move the mouse pointer down, click Settings, and then click Change PC settings)
- In the navigation pane, tap or click Users.
- Tap or Click Add a User, then tap or click Can they sign in without a Microsoft account?
- Tap or click Local account.
- Enter your new account name.
- If you want to use a password, enter and verify the password that you want to use. If you decide not to use a password, tap or click Next without entering a password.
- Tap or click Finish.
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 7 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files or folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or a folder, follow these steps:
- Right-click the folder that you want to take ownership of, and then click Properties.
- Click the Security tab, click Advanced, and then click the Owner tab.
- Click Edit. If you are prompted for an administrator password or for confirmation, type the password or provide confirmation.
- Click the name of the person that you want to give ownership to.
- If you want that person to be the owner of files and subfolders in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You may not have the appropriate permissions Issues that you experience when you try to access files and folders may be related to permissions. Permissions are rules that determine whether you can access or change files and folders. To check permissions on a file or a folder, follow these steps:
- Press and hold or right-click the file or folder, and then click Properties.
- Tap or click the Security tab.
- Under Group or user names, tap or click your name to see the permissions that you have.
To open a file, you have to have the Read permission. To change permissions on a file or folder, follow these steps.
Important You must be logged on as an administrator to change permissions on files and folders.
- Right-click the file or folder, and then click Properties.
- Click the Security tab.
- Under Group or user names, click your name to see the permissions you have.
- Click Edit, click your name, select the check boxes for the permissions that you must have, and then click OK.
For more information about permissions, see What are permissions?.
The file or folder may be encrypted Encryption can help protect files and folders from unwanted access. You cannot open an encrypted file or folder without the certificate that was used to encrypt it. To determine whether a file or folder is encrypted, follow these steps:
- Right-click the file, then click Properties.
- Click the General tab, and then click Advanced.
If the Encrypt contents to secure data check box is selected, you have to have the certificate that was used to encrypt the file or folder to be able to open it.
You should obtain the certificate from the person who created the file. For more information, see Import or export certificates and private keys.
The file or folder may be corrupted Files can become corrupted for several reasons. The most common reason is that you have a file open when your computer crashes or loses power. Most corrupted files cannot be repaired. In this situation, you should either delete the file or restore the file from a backup copy.
For more information about corrupted files and how to fix them, see Corrupted files: frequently asked questions.
Your user profile may be corrupted Occasionally, Windows might not read your local user profile correctly. This may prevent you from accessing files and folders. In this situation, you may have to use a new local user profile. To create the profile, you must first create a local user account. When the new account is created, the profile is also created.
For more information about how to create user profiles, see Fix a corrupted user profile. After the new user profile is created, you can copy your existing user files to the new profile so that you can access them.
Issue 3: I cannot open a file or folder after I upgrade to a new version of Windows
Cause Problems that prevent you from accessing files and folders after you upgrade to a new version of Windows can occur for one or more of the following reasons:
- The folder ownership has changed.
- The files are being stored in a Windows.old folder from your previous system.
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 8 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files and folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or a folder, follow these steps:
- Press and hold the folder that you want to take ownership of, then tap Properties. (If you are using a mouse, right-click the folder, and then click Properties.)
- Tap or click the Security tab, tap or click Advanced, then tap or click Change. If you are prompted for an administrator password or for confirmation, type the password or provide confirmation.
- Type the name of the person that you want to give ownership to, and then click Check Names. Note The account name for the person that you are assigning ownership to is displayed.
- Click OK.
- If you want this person to be the owner of the files and subfolders that are contained in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You have to recover files from the Windows.old folder If you recently upgraded your computer to Windows 8 from an earlier version of Windows, and you did not reformat the hard disk, you might still be able to access your old files from the Windows.old folder.
To fix this problem automatically, click the Fix it button or link. In the File Download dialog box, click Run, and then follow the steps in the Fix it Wizard. If you prefer to fix this problem yourself, go to the «Let me fix it myself» section.
- This wizard may be in English only. However, the automatic fix also works for other language versions of Windows.
- If you are not on the computer that has the problem, save the Fix it solution to a flash drive or a CD, and then run it on the computer that has the problem.
Let me fix it myself To manually retrieve the files, follow these steps:
- Open the desktop, tap the folder icon, and then click Computer. Or, press the Windows logo key+E.
- Double-tap or double-click the drive that Windows is installed on (typically, drive C).
- Double-tap or double-click the Windows.old folder.
- Double-tap or double-click the Users folder.
- Double-tap or double-click your user name.
- Open the folders that contain the files that you want to retrieve. For example, to retrieve files in the Documents folder, double-tap or double-click Documents.
- Copy the files that you want from each folder and paste them to a folder in Windows 8. For example, if you want to retrieve everything from the Documents folder, copy all the files and folders from the Documents folder in the Windows.old folder, and then paste them to the Documents library in Windows 8.
- Repeat steps 5-7 for each user account on your computer.
For more information about how to recover data from an earlier version of Windows, see Recover lost or deleted files.
You may not have ownership of a file or folder If you recently upgraded your computer to Windows 7 from an earlier version of Windows, some of your account information may have changed. Therefore, you may no longer have ownership of some files and folders. You might be able to resolve this issue by restoring your ownership of the files and folders.
To take ownership of a file or a folder, follow these steps:
- Right-click the folder that you want to take ownership of, and then click Properties.
- Click the Security tab, click Advanced, and then click the Owner tab.
- Click Edit. If you are prompted for an administrator password or confirmation, type the password or provide confirmation.
- Click the name of the person that you want to give ownership to.
- If you want that person to be the owner of files and subfolders in this folder, select the Replace owner on subcontainers and objects check box.
- Click OK.
You may have to recover files from the Windows.old folder If you recently upgraded your computer to Windows 7 from an earlier version of Windows, and you did not reformat your hard disk, you might still be able to access your old files from the Windows.old folder.
To fix this problem automatically, click the Fix it button or link. In the File Download dialog box, click Run, and then follow the steps in the Fix it Wizard.If you prefer to fix this problem yourself, go to the «Let me fix it myself» section.
- This wizard may be in English only. However, the automatic fix also works for other language versions of Windows.
- If you are not on the computer that has the problem, save the Fix it solution to a flash drive or a CD, and then run it on the computer that has the problem.
Let me fix it myself To manually retrieve the files, follow these steps:
- Click Start, then click Computer.
- Double-click the drive that Windows is installed on (typically, drive C).
- Double-click the Windows.old folder.
- Double-click the Users folder.
- Double-click your user name.
- Open the folders that contain the files that you want to retrieve. For example, to retrieve files in the Documents folder, double-click Documents.
- Copy the files that you want from each folder and paste them to a folder in Windows 7. For example, if you want to retrieve everything from the Documents folder, copy all the files and folders from the Documents folder in the Windows.old folder, and then paste them to the Documents library in Windows 7.
- Repeat steps 5-7 for each user account on your computer.
For more information about how to recover data from an earlier version of Windows, see Recover lost or deleted files.
Как исправить ошибку Relay access denied
Получили сбой в виде Access Relay Denied? Тогда срочно читайте наш гайд, чтобы узнать о причинах ошибки и методах её исправления.
Relay Access Denied — что это?
«Relay Access Denied» – это распространённая ошибка электронной почты, которая означает, что сервер не разрешает отправку писем на другой почтовый сервер.
.png)
Она может иметь вид:
EMAIL DELIVERY ERROR: the plugin WP Mail SMTP v2.8.1 logged this error during the last time it tried to send an email:
Mailer: Other SMTP SMTP Error: The following recipients failed: ivan@nic.ru: TenantAttribution; Relay Access Denied [QB1CAN01FT008.eop-CAN01.prod.protection.outlook.com]
Consider running an email test after fixing it.
Как исправить ошибку Access Relay Denied на стороне пользователя
Если вы пытаетесь отправить письмо и получаете подобное сообщение, вам стоит первым делом выполнить следующие шаги:
- Обратитесь за помощью к провайдеру электронной почты, чтобы проверить все настройки. Так вы сможете убедиться, что у вас есть правильные учётные данные, такие как почтовый сервер, имя пользователя и пароль.
- Затем узнайте, нет ли ограничений со стороны интернет-провайдера. Существует вероятность, что он блокирует порт 25 сервера исходящей почты (SMTP). В этом случае попробуйте изменить настройки, чтобы использовать порт 587 или 465 с активированным SSL.
- И, наконец, всегда существует вероятность срабатывания спам-фильтров на сервере получателя. Если это так, вам следует попросить своего провайдера электронной почты просмотреть файлы логов почтового сервера и получить из них дополнительную информацию о том, как решить эту проблему.
Как исправить ошибку Relay Access Denied на стороне провайдера
Причина 1. Сбой аутентификации
Если у всех ваших клиентов возникла подобная проблема, то скорее всего дело именно в ошибке аутентификации пользователя. В таком случае обязательно просмотрите настройки аутентификации на уровне сервера.
Например, если вы используете сервер Postfix, убедитесь, что SMTP-аутентификация включена.
Зачем это делать и почему настройки могли внезапно измениться? Иногда обновление серверного ПО может изменить конфигурацию. Поэтому, если ваш почтовый сервер всё время работал без сбоев, а затем внезапно начал выдавать ошибки, скорее всего, причина в последнем обновлении ПО.
Важно! Если вы привыкли обновлять свой сервер вручную, задумайтесь о настройке тестового сервера, аналогичного вашему основному.
Использование такого тестового сервера для проверки всех обновлений – это прекрасная возможность избежать нежелательных ошибок у ваших пользователей. Если в тестовой среде всё будет работать нормально, вы сможете уверенно продолжить и развернуть обновление уже в рабочей среде.
Причина 2. Нарушена маршрутизация почты
Ещё один из самых распространённых случаев – это проблемы с маршрутизацией почты. Мы рекомендуем воспользоваться любой панелью управления, чтобы решить ошибку Relay access denied: ispmanager, Plesk или cPanel.
ispmanager
- В левом меню выберите раздел Почта.
- Найдите опцию Почтовые домены и щёлкните по ней.
.png)
- Выберите почтовый домен и нажмите Удалить в панели выше.
.png)
Plesk
- В левом меню выберите раздел Почта.
- Откройте раздел Настройки почты.
- Щёлкните по нужному почтовому домену.
.png)
- Перед вами откроется меню, где вам необходимо снять флажок с опции «Активировать почтовую службу на этом домене».
- Подтвердите изменения, нажав Применить.
cPanel
- В разделе «Почта» перейдите в меню Маршрутизация почты.
.png)
- Выберите нужный домен из списка.
- Затем обратите внимание на раздел «Настроить маршрутизацию почты». Поставьте флажок напротив опции Удаленный почтовый обменник.
- Щёлкните Изменить.
Причина 3. База данных аутентификации повреждена
На таких платформах, как Plesk, имена пользователей, пароли и аутентифицированные IP-адреса хранятся в базе данных. Как и любая другая база данных, она может быть повреждена по многим причинам. Но вы всегда можете положиться на простую командную строку для восстановления базы данных.
mysqlcheck -r psa smtp_poplocks -uadmin -p
Эта команда выполнит проверку БД и исправит сбой, если она окажется повреждена.
Причина 4. Спам-фильтр на сервере-получателе возвращают электронные письма вашего пользователя
Если ваши пользователи отправляют электронные письма и затем получают их обратно с кодом ошибки:
454 4.7.1: Relay access denied
Скорее всего, ваш сервер не проходит спам-фильтр сервера получателя. Чаще всего это случается, когда ваш сервер попадает в RBL (Realtime Blackhole List). Разобраться в этом и проверить, не находится ли ваш сервер в чёрных списках, помогут такие сайты, как:
.png)
- В строке «Domain Name» введите IP-адрес сервера.
- Начните поиск, нажав MX Lookup.
.png)
- Введите IP-адрес сервера, который хотите проверить.
- Щёлкните Check RBL, чтобы запустить поиск.
Эти веб-инструменты предоставят вам всю информацию о любых чёрных списках, в которых вы могли оказаться, чтобы впоследствии вы могли запросить исключение вашего сервера из этих RBL.
Однако, прежде чем просить исключить ваш сервер из списка, устраните причину попадания в него. Например, если на вашем сервере был обнаружен спамер, вы должны решить эту проблему до подачи запроса на удаление из RBL-списка.
Заключение
В данной статье мы рассмотрели, что такое ошибка Relay Access Denied, её возможные причины возникновения и способы устранения.
Если у вас ещё остались вопросы, вы можете обратиться к нашим специалистам техподдержки, чтобы окончательно решить проблему.
Access Denied When you call a Web Service while Anonymous Authentication is turned Off
This article helps you resolve errors (Access Denied) that occur when you call a Web service application and Anonymous access authentication is turned off.
Original product version: Web Services Enhancements
Original KB number: 811318
Symptoms
When you try to call a Web service application and Anonymous access authentication is turned off, you may receive the following error message:
The request failed with HTTP status 401: Access Denied.
Description: An unhandled exception occurred during the execution of the current Web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The request failed with HTTP status 401: Access Denied.
Cause
When Anonymous access authentication is turned off for the Web service application, all the caller applications must provide the credentials before making any request. By default, the Web service client proxy does not inherit the credentials of the security context where the Web service client application is running.
To resolve this problem, you must use the Credentials property of the Web service client proxy to set the security credentials for Web service client authentication.
To set the Credentials property, use one of the following resolutions:
Resolution 1: Assign DefaultCredentials to Credentials property
Assign the DefaultCredentials to the Credentials property of the Web Service Proxy class to call the Web service while Anonymous access authentication is turned off. The DefaultCredentials property of the CredentialCache class provides system credentials of the security context where the application is running. To do this, use the following code:
Visual C# .NET Sample
//Assigning DefaultCredentials to the Credentials property //of the Web service client proxy (myProxy). myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials;
Visual Basic .NET Sample
'Assigning DefaultCredentials to the Credentials property 'of the Web service client proxy (myProxy). myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials
Resolution 2: Use the CredentialCache class
You may use the CredentialCache class to provide credentials for Web service client authentication. Create an instance of the CredentialCache class. Create an instance of NetworkCredential that uses the specified user name, password, and domain. Add the NetworkCredential to the CredentialCache class with the authentication type. To do this, use the following code:
Visual C# .NET Sample
//Create an instance of the CredentialCache class. CredentialCache cache = new CredentialCache(); // Add a NetworkCredential instance to CredentialCache. // Negotiate for NTLM or Kerberos authentication. cache.Add( new Uri(myProxy.Url), "Negotiate", new NetworkCredential("UserName", "Password", "Domain")); //Assign CredentialCache to the Web service Client Proxy(myProxy) Credetials property. myProxy.Credentials = cache;
Visual Basic .NET Sample
'Create an instance of the CredentialCache class. Dim cache As CredentialCache = New CredentialCache() 'Add a NetworkCredential instance to CredentialCache. 'Negotiate for NTLM or Kerberos authentication. cache.Add(New Uri(myProxy.Url), "Negotiate", New NetworkCredential("UserName", "Password", "Domain")) 'Assign CredentialCache to the Web service Client Proxy(myProxy) Credetials property. myProxy.Credentials = cache
The CredentialCache class and the NetworkCredential class belong to the System.Net namespace.
For more information about how to set the Credentials property, see the Steps to reproduce the behavior section in this article.
Status
This behavior is by design.
Steps to reproduce the behavior
DefaultCredentials represents the system credentials for the current security context where the application is running. For a client-side application, the default credentials are typically the Windows credentials such as user name, password, and domain of the user who is running the program. For ASP.NET programs, the default credentials are the user credentials of the identity for the ASP.NET worker process, or the user who is being impersonated. In the following sample ASP.NET program, DefaultCredentials represents the ASPNET user account (or NetworkService user account for applications run on Microsoft Internet Information Services [IIS] 6.0) because no impersonation is set to the caller.
- Create a new ASP.NET Web Service by using Visual C# .NET or Visual Basic .NET.
- Name the project WebServiceTest.
- By default, Service1.asmx is created.
- Uncomment the default WebMethod «HelloWorld()».
- On Build menu, select Build Solution.
- Turn off Anonymous access to WebServiceTest. To do this, follow these steps:
- In Control Panel, double-click Administrative Tools.
- Double-click Internet Information Services.
- Expand Internet Information Services, and then locate the WebServiceTest virtual directory.
- Right-click WebServiceTest, and then select Properties.
- Select the Directory Security tab.
- Under Anonymous access and authentication control, select Edit.
- In the Authentication Methods dialog box, select to clear the Anonymous access check box.
- Select to select the Integrated Windows authentication check box.
Note Verify that only Integrated Windows authentication is selected.
- Create a new ASP.NET Web Application by using Visual C# .NET or Visual Basic .NET. Name the project WebServiceCaller.
- By default, WebForm1.aspx is created.
- In Solution Explorer, right-click References, and then select Add Web Reference.
- In the Address text box, type the URL for WebServiceTest as follows: http://localhost/WebServiceTest/Service1.asmx
- Select Go or press ENTER, and then select Add Reference.
// Start an instance of the Web service client-side proxy. localhost.Service1 myProxy = new localhost.Service1(); Response.Write( myProxy.HelloWorld());Visual Basic .NET Sample:
'Start an instance of the Web service client-side proxy. Dim myProxy As localhost.Service1 = New localhost.Service1() Response.Write(myProxy.HelloWorld())myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials;Visual Basic .NET Sample:
myProxy.Credentials = System.Net.CredentialCache.DefaultCredentialsReferences
- HOW TO: Write a Simple Web Service by Using Visual C# .NET
- Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
- Securing XML Web Services Created Using ASP.NET
- CredentialCache Class
- CredentialCache.DefaultCredentials Property