NET Framework 4.5
soap
WCF
Web-сервис
wsdl
аутентификация
Технические вопросы
7.x

Аутентификация RPC

Коллеги, приветствую.

Пытаюсь аутентифицировать внешние запросы к WCF Web- сервису. Для этого передаю логин и пароль в заголовке SOAP.

using (UsrService client = new UsrService())
{
        client.Credentials = new System.Net.NetworkCredential("Пользователь 1", "Пользователь 1");
        client.SayHello();
}

И Web- сервис и его клиент работают на платформе .NET Framework 4.5.

Запрос не проходит аутентификацию и, насколько я понимаю, происходит редирект на форму логина.

http://localhost:8080/NuiLogin.aspx?ReturnUrl=%2f0%2fServiceModel%2fSimpleCustomService.svc

Что я вижу в своем консольном клиенте:

С чем это может быть связано?

Был бы весьма признателен за информацию.

Спасибо.

--
С уважением, Алексей Быков.

Нравится

5 комментариев

Если в клиенте я добавляю:

[code]
client.AllowAutoRedirect = true;
[/code]

То в консоли вижу следующее:

[xml]
Необработанное исключение: System.InvalidOperationException: Клиент обнаружил ти
п содержимого ответа "text/html; charset=utf-8", но ожидается тип "text/xml".
Сбой запроса с сообщением об ошибке:
--

bpm'online bank customer journey

.login-label-logo
{
background: url("terrasoft.axd?s=nui-binary-syssetting&r
=Logoimage");
background-repeat: no-repeat;
width: 223px;
height: 100px;
margin-bottom: 28px;
background-position: left bottom;
}

window.workspaceList = {'1': { value: 'Default', displayValue: 'Default' }};
window.supportInfo = [];
window.supportInfoCaption = '';
window.importantLinks = [];
window.importantLinksCaption = '';
window.productVersion = '7.7.0.2872';
window.loginTimeout = '30000';
window.workspaceCount = 1;
var Terrasoft = Terrasoft || {};
window.isNtlmLoginVisible = false;

var Terrasoft = Terrasoft || {};
Terrasoft.loaderBaseUrl = 'http://localhost:8080/';
Terrasoft.workspaceBaseUrl = 'http://localhost:8080/';

var FileAPI = {
staticPath: '../Resources/ui/FileAPI/',
flashUrl: '../Resources/ui/FileAPI/FileAPI.flash.swf',
flashImageUrl: '../Resources/ui/FileAPI/FileAPI.flash.image.swf' };

var Terrasoft = Terrasoft || {};Terrasoft.enablePerformanceManager = false;

requirejs.config({
paths: {
'core':'http://localhost:8080//core/ef58ab72c648daaa7af074e2526dffc3/Terrasoft/a
md/core',
'bootstrap':'http://localhost:8080//core/022b4acc49ebfbfb33b54d4f95393d2a/Terras
oft/amd/bootstrap',
'performancecountermanager':'http://localhost:8080//core/3bf271e2ad15f056eac25ab
fea30226a/Terrasoft/amd/performancecountermanager',
'loadbootstrap':'http://localhost:8080//core/b0ebbf0e263a02a3db86bf39761aba1c/Te
rrasoft/amd/bootstrap.login',
'jQuery':'http://localhost:8080//core/8d24859b5ac713ab6f05091492b6c631/jQuery/jQ
uery',
'jQuery-easing':'http://localhost:8080//core/a6f75e0c043a2a087837e5c113cc6f7a/jQ
ueryEasing/jQuery-easing',
'jsrender':'http://localhost:8080//core/77f59dfac75bba6c861fe26d75691086/jsrende
r/jsrender',
'ej-common-all':'http://localhost:8080//core/e8b46aebd6473a2f85386c0d072a2b93/Sy
ncfusion/min/ej-common-all',
'ej-diagram':'http://localhost:8080//core/89f5be5f51b070471058224a6550b99a/Syncf
usion/min/ej-diagram',
'process-schema-diagram':'http://localhost:8080//core/650e4ae64a84c1fd11caab7904
39c8ef/Terrasoft/designers/process-schema-designer/process-schema-diagram',
'process-schema-diagram-5x':'http://localhost:8080//core/b0b08b3ec18e7494d488622
07309479f/Terrasoft/designers/process-schema-designer/process-schema-diagram-5x'
,
'ckeditor-base':'http://localhost:8080//core/04628941838af9176121c9cd4332b49d/CK
Editor/ckeditor',
'html2canvas':'http://localhost:8080//core/524ae0cfb507a786266d32d9a16ccc42/html
2canvas/html2canvas'
},
shim: {'jQuery-easing': {'deps': ['jQuery']}, 'ej-common-all': {'deps': ['jQuery
-easing']}, 'ej-diagram': {'deps': ['ej-common-all', 'jsrender']}, 'process-sche
ma-diagram': {'deps': ['ej-diagram']}, 'process-schema-diagram-5x': {'deps': ['p
rocess-schema-diagram']}}});
require(['loadbootstrap'],function() {});

var Terrasoft = Terrasoft || {};
Terrasoft.isDebug = false;
Terrasoft.DataValueTypeRange = {INTEGER: {maxValue:2147483647,minValue:-21474836
48},FLOAT: {maxValue:79228162514264337593543950335,minValue:-7922816251426433759
3543950335},DATE_TIME: {maxValue:"0001-01-01T00:00:00.000",minValue:"0001-01-01T
00:00:00.000"}};
Terrasoft.storesConfig = [];
Terrasoft.storesConfig.push({levelName: 'ClientPageSession', type: 'Terrasoft.Me
moryStore', isCache: true});Terrasoft.storesConfig.push({levelName: 'Domain', ty
pe: 'Terrasoft.LocalStore', isCache: true});
if(Terrasoft.StoreManager){
Terrasoft.StoreManager.registerStores(Terrasoft.storesConfig);
}

--.
в System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClien
tMessage message, WebResponse response, Stream responseStream, Boolean asyncCall
)
в System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodNa
me, Object[] parameters)
в UsrService.SayHello() в c:\VS2015\Projects\WCFSharedDLL\WCFSharedDLL\TestPr
oxyClass.cs:строка 44
в ConsoleApplicationForTesting.Program.Main(String[] args) в c:\VS2015\Projec
ts\ConsoleApplicationForTesting\ConsoleApplicationForTesting\Program.cs:строка 1
6
Для продолжения нажмите любую клавишу . .
[/xml]

Т.е. исходный код страницы авторизации.

Решил таким образом. На уровне транспортного протокола передал учетные данные:

[code]
public const string authServiceUri =
"http://localhost:8080/ServiceModel/AuthService.svc/Login";
public static CookieContainer AuthCookie =
new CookieContainer();

public static bool TryLogin(string userName, string userPassword)
{
var authRequest = HttpWebRequest.Create(authServiceUri)
as HttpWebRequest;

authRequest.Method = "POST";
authRequest.ContentType = "application/json";
authRequest.CookieContainer = AuthCookie;

using (var requesrStream = authRequest.GetRequestStream())
{
using(var writer = new StreamWriter(requesrStream))
{
writer.Write(@"{
""UserName"":""" + userName + @""",
""UserPassword"":""" + userPassword + @"""
}");
}
}

using(var response = (HttpWebResponse)authRequest.GetResponse())
{
if (AuthCookie.Count > 0)
{
return true;
}
}
return false;
}
[/code]

Установил CookieContainer:

[code]
client.CookieContainer = AuthCookie;
[/code]

Стало возможным выполнять запросы к Web- сервису:

[code]
static void Main(string[] args)
{
using (UsrService client = new UsrService())
{
if(TryLogin("Пользователь 1", "Пользователь 1"))
{
client.CookieContainer = AuthCookie;
Console.WriteLine(client.SayHello());
}
}
}
[/code]

Хотя и осталось непонятным, почему не удалось аутентифицировать внешние запросы через передачу учетных данных в SOAP заголовке...

Здравствуйте.
Как вариант, в заголовок запроса можно было попробовать указать content-type "text/xml".

Здравствуйте, Александр. Хорошо, спасибо - попробую и отпишусь, что вышло.

Показать все комментарии